diff --git a/app/Http/Controllers/Api/AssetFilesController.php b/app/Http/Controllers/Api/AssetFilesController.php new file mode 100644 index 0000000000..d8bc5e3841 --- /dev/null +++ b/app/Http/Controllers/Api/AssetFilesController.php @@ -0,0 +1,219 @@ + + * + * @version v1.0 + * @author [T. Scarsbrook] [] + */ +class AssetFilesController extends Controller +{ + /** + * Accepts a POST to upload a file to the server. + * + * @param \App\Http\Requests\UploadFileRequest $request + * @param int $assetId + * @return \Illuminate\Http\JsonResponse + * @throws \Illuminate\Auth\Access\AuthorizationException + * @since [v6.0] + * @author [T. Scarsbrook] [] + */ + public function store(UploadFileRequest $request, $assetId = null) + { + // Start by checking if the asset being acted upon exists + if (! $asset = Asset::find($assetId)) { + return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/hardware/message.does_not_exist')), 404); + } + + // Make sure we are allowed to update this asset + $this->authorize('update', $asset); + + if ($request->hasFile('file')) { + // If the file storage directory doesn't exist; create it + if (! Storage::exists('private_uploads/assets')) { + Storage::makeDirectory('private_uploads/assets', 775); + } + + // Loop over the attached files and add them to the asset + foreach ($request->file('file') as $file) { + $file_name = $request->handleFile('private_uploads/assets/','hardware-'.$asset->id, $file); + + $asset->logUpload($file_name, e($request->get('notes'))); + } + + // All done - report success + return response()->json(Helper::formatStandardApiResponse('success', $asset, trans('admin/hardware/message.upload.success'))); + } + + // We only reach here if no files were included in the POST, so tell the user this + return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/hardware/message.upload.nofiles')), 500); + } + + /** + * List the files for an asset. + * + * @param int $assetId + * @return \Illuminate\Http\JsonResponse + * @throws \Illuminate\Auth\Access\AuthorizationException + * @since [v6.0] + * @author [T. Scarsbrook] [] + */ + public function list($assetId = null) + { + // Start by checking if the asset being acted upon exists + if (! $asset = Asset::find($assetId)) { + return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/hardware/message.does_not_exist')), 404); + } + + // the asset is valid + if (isset($asset->id)) { + $this->authorize('view', $asset); + + // Check that there are some uploads on this asset that can be listed + if ($asset->uploads->count() > 0) { + $files = array(); + foreach ($asset->uploads as $upload) { + array_push($files, $upload); + } + // Give the list of files back to the user + return response()->json(Helper::formatStandardApiResponse('success', $files, trans('admin/hardware/message.upload.success'))); + } + + // There are no files. + return response()->json(Helper::formatStandardApiResponse('success', array(), trans('admin/hardware/message.upload.success'))); + } + + // Send back an error message + return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/hardware/message.download.error')), 500); + } + + /** + * Check for permissions and display the file. + * + * @param int $assetId + * @param int $fileId + * @return \Illuminate\Http\JsonResponse + * @throws \Illuminate\Auth\Access\AuthorizationException + * @since [v6.0] + * @author [T. Scarsbrook] [] + */ + public function show($assetId = null, $fileId = null) + { + // Start by checking if the asset being acted upon exists + if (! $asset = Asset::find($assetId)) { + return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/hardware/message.does_not_exist')), 404); + } + + // the asset is valid + if (isset($asset->id)) { + $this->authorize('view', $asset); + + // Check that the file being requested exists for the asset + if (! $log = Actionlog::whereNotNull('filename')->where('item_id', $asset->id)->find($fileId)) { + return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/hardware/message.download.no_match', ['id' => $fileId])), 404); + } + + // Form the full filename with path + $file = 'private_uploads/assets/'.$log->filename; + \Log::debug('Checking for '.$file); + + if ($log->action_type == 'audit') { + $file = 'private_uploads/audits/'.$log->filename; + } + + // Check the file actually exists on the filesystem + if (! Storage::exists($file)) { + return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/hardware/message.download.does_not_exist', ['id' => $fileId])), 404); + } + + if (request('inline') == 'true') { + + $headers = [ + 'Content-Disposition' => 'inline', + ]; + + return Storage::download($file, $log->filename, $headers); + } + + return StorageHelper::downloader($file); + } + + // Send back an error message + return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/hardware/message.download.error', ['id' => $fileId])), 500); + } + + /** + * Delete the associated file + * + * @param int $assetId + * @param int $fileId + * @return \Illuminate\Http\JsonResponse + * @throws \Illuminate\Auth\Access\AuthorizationException + * @since [v6.0] + * @author [T. Scarsbrook] [] + */ + public function destroy($assetId = null, $fileId = null) + { + // Start by checking if the asset being acted upon exists + if (! $asset = Asset::find($assetId)) { + return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/hardware/message.does_not_exist')), 404); + } + + $rel_path = 'private_uploads/assets'; + + // the asset is valid + if (isset($asset->id)) { + $this->authorize('update', $asset); + + // Check for the file + $log = Actionlog::find($fileId); + if ($log) { + // Check the file actually exists, and delete it + if (Storage::exists($rel_path.'/'.$log->filename)) { + Storage::delete($rel_path.'/'.$log->filename); + } + // Delete the record of the file + $log->delete(); + + // All deleting done - notify the user of success + return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/hardware/message.deletefile.success')), 200); + } + + // The file doesn't seem to really exist, so report an error + return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/hardware/message.deletefile.error')), 500); + } + + return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/hardware/message.deletefile.error')), 500); + } +} diff --git a/app/Http/Requests/UploadFileRequest.php b/app/Http/Requests/UploadFileRequest.php index d91d0bf0b8..4762e52b75 100644 --- a/app/Http/Requests/UploadFileRequest.php +++ b/app/Http/Requests/UploadFileRequest.php @@ -2,12 +2,14 @@ namespace App\Http\Requests; +use App\Http\Traits\ConvertsBase64ToFiles; use enshrined\svgSanitize\Sanitizer; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Log; class UploadFileRequest extends Request { + use ConvertsBase64ToFiles; /** * Determine if the user is authorized to make this request. * diff --git a/resources/lang/en-GB/admin/hardware/message.php b/resources/lang/en-GB/admin/hardware/message.php index 3af3dbc6e3..7185cd8dcf 100644 --- a/resources/lang/en-GB/admin/hardware/message.php +++ b/resources/lang/en-GB/admin/hardware/message.php @@ -51,6 +51,13 @@ return [ 'invalidfiles' => 'One or more of your files is too large or is a filetype that is not allowed. Allowed filetypes are png, gif, jpg, doc, docx, pdf, and txt.', ], + 'download' => [ + 'error' => 'File(s) not downloaded. Please try again.', + 'success' => 'File(s) successfully downloaded.', + 'does_not_exist' => 'No file exists', + 'no_match' => 'No matching record for that asset/file', + ], + 'import' => [ 'error' => 'Some items did not import correctly.', 'errorDetail' => 'The following Items were not imported because of errors.', diff --git a/routes/api.php b/routes/api.php index 8adb0af619..1f43af7431 100644 --- a/routes/api.php +++ b/routes/api.php @@ -544,13 +544,36 @@ Route::group(['prefix' => 'v1', 'middleware' => ['api', 'throttle:api']], functi 'restore' ] )->name('api.assets.restore'); + Route::post('{asset_id}/files', + [ + Api\AssetFilesController::class, + 'store' + ] + )->name('api.assets.files'); + + Route::get('{asset_id}/files', + [ + Api\AssetFilesController::class, + 'list' + ] + )->name('api.assets.files'); + + Route::get('{asset_id}/file/{file_id}', + [ + Api\AssetFilesController::class, + 'show' + ] + )->name('api.assets.file'); + + Route::delete('{asset_id}/file/{file_id}', + [ + Api\AssetFilesController::class, + 'destroy' + ] + )->name('api.assets.file'); }); - - - - Route::resource('hardware', Api\AssetsController::class, ['names' => [ diff --git a/tests/Feature/Api/Assets/AssetFilesTest.php b/tests/Feature/Api/Assets/AssetFilesTest.php new file mode 100644 index 0000000000..2c19d5dc77 --- /dev/null +++ b/tests/Feature/Api/Assets/AssetFilesTest.php @@ -0,0 +1,120 @@ +count(1)->create(); + + // Create a superuser to run this as + $user = User::factory()->superuser()->create(); + + //Upload a file + $this->actingAsForApi($user) + ->post( + route('api.assets.files', ['asset_id' => $asset[0]["id"]]), [ + 'file' => [UploadedFile::fake()->create("test.jpg", 100)] + ]) + ->assertOk(); + } + + public function testAssetApiListsFiles() + { + // List all files on an asset + + // Create an asset to work with + $asset = Asset::factory()->count(1)->create(); + + // Create a superuser to run this as + $user = User::factory()->superuser()->create(); + + // List the files + $this->actingAsForApi($user) + ->getJson( + route('api.assets.files', ['asset_id' => $asset[0]["id"]])) + ->assertOk() + ->assertJsonStructure([ + 'status', + 'messages', + 'payload', + ]); + } + + public function testAssetApiDownloadsFile() + { + // Download a file from an asset + + // Create an asset to work with + $asset = Asset::factory()->count(1)->create(); + + // Create a superuser to run this as + $user = User::factory()->superuser()->create(); + + //Upload a file + $this->actingAsForApi($user) + ->post( + route('api.assets.files', ['asset_id' => $asset[0]["id"]]), [ + 'file' => [UploadedFile::fake()->create("test.jpg", 100)] + ]) + ->assertOk(); + + // List the files to get the file ID + $result = $this->actingAsForApi($user) + ->getJson( + route('api.assets.files', ['asset_id' => $asset[0]["id"]])) + ->assertOk(); + + // Get the file + $this->actingAsForApi($user) + ->get( + route('api.assets.file', [ + 'asset_id' => $asset[0]["id"], + 'file_id' => $result->decodeResponseJson()->json()["payload"][0]["id"], + ])) + ->assertOk(); + } + + public function testAssetApiDeletesFile() + { + // Delete a file from an asset + + // Create an asset to work with + $asset = Asset::factory()->count(1)->create(); + + // Create a superuser to run this as + $user = User::factory()->superuser()->create(); + + //Upload a file + $this->actingAsForApi($user) + ->post( + route('api.assets.files', ['asset_id' => $asset[0]["id"]]), [ + 'file' => [UploadedFile::fake()->create("test.jpg", 100)] + ]) + ->assertOk(); + + // List the files to get the file ID + $result = $this->actingAsForApi($user) + ->getJson( + route('api.assets.files', ['asset_id' => $asset[0]["id"]])) + ->assertOk(); + + // Delete the file + $this->actingAsForApi($user) + ->delete( + route('api.assets.file', [ + 'asset_id' => $asset[0]["id"], + 'file_id' => $result->decodeResponseJson()->json()["payload"][0]["id"], + ])) + ->assertOk(); + } +}