A free open source IT asset/license management system
Add AssetModel files endpoints to API
r-xyz4ec361c71835
diff --git a/app/Http/Controllers/Api/AssetModelFilesController.php b/app/Http/Controllers/Api/AssetModelFilesController.phpnew file mode 100644index 0000000000..9d17de4aec--- /dev/null+++ b/app/Http/Controllers/Api/AssetModelFilesController.php@@ -0,0 +1,200 @@+<?php++namespace App\Http\Controllers\Api;++use App\Helpers\StorageHelper;+use Illuminate\Support\Facades\Storage;+use App\Helpers\Helper;+use App\Http\Controllers\Controller;+use App\Models\AssetModel;+use App\Models\Actionlog;+use App\Http\Requests\UploadFileRequest;+use Illuminate\Http\JsonResponse;+use Illuminate\Support\Facades\Log;+use Symfony\Component\HttpFoundation\StreamedResponse;+use Symfony\Component\HttpFoundation\BinaryFileResponse;+++/**+ * This class controls file related actions related+ * to assets for the Snipe-IT Asset Management application.+ *+ * Based on the Assets/AssetFilesController by A. Gianotto <[email protected]>+ *+ * @version v1.0+ * @author [T. Scarsbrook] [<[email protected]>]+ */+class AssetModelFilesController extends Controller+{+ /**+ * Accepts a POST to upload a file to the server.+ *+ * @param \App\Http\Requests\UploadFileRequest $request+ * @param int $assetModelId+ * @since [v7.0.12]+ * @author [r-xyz]+ */+ public function store(UploadFileRequest $request, $assetModelId = null) : JsonResponse+ {+ // Start by checking if the asset being acted upon exists+ if (! $assetModel = AssetModel::find($assetModelId)) {+ return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/models/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/assetmodels')) {+ Storage::makeDirectory('private_uploads/assetmodels', 775);+ }++ // Loop over the attached files and add them to the asset+ foreach ($request->file('file') as $file) {+ $file_name = $request->handleFile('private_uploads/assetmodels/','model-'.$asset->id, $file);++ $asset->logUpload($file_name, e($request->get('notes')));+ }++ // All done - report success+ return response()->json(Helper::formatStandardApiResponse('success', $asset, trans('admin/models/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/models/message.upload.nofiles')), 500);+ }++ /**+ * List the files for an asset.+ *+ * @param int $assetModelId+ * @since [v7.0.12]+ * @author [r-xyz]+ */+ public function list($assetModelId = null) : JsonResponse+ {+ // Start by checking if the asset being acted upon exists+ if (! $assetModel = AssetModel::find($assetModelId)) {+ return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/models/message.does_not_exist')), 404);+ }++ // the asset is valid+ if (isset($assetModel->id)) {+ $this->authorize('view', $assetModel);++ // Check that there are some uploads on this asset that can be listed+ if ($assetModel->uploads->count() > 0) {+ $files = array();+ foreach ($assetModel->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/models/message.upload.success')));+ }++ // There are no files.+ return response()->json(Helper::formatStandardApiResponse('success', array(), trans('admin/models/message.upload.success')));+ }++ // Send back an error message+ return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/models/message.download.error')), 500);+ }++ /**+ * Check for permissions and display the file.+ *+ * @param int $assetModelId+ * @param int $fileId+ * @return \Illuminate\Http\JsonResponse+ * @throws \Illuminate\Auth\Access\AuthorizationException+ * @since [v7.0.12]+ * @author [r-xyz]+ */+ public function show($assetModelId = null, $fileId = null) : JsonResponse | StreamedResponse | Storage | StorageHelper | BinaryFileResponse+ {+ // Start by checking if the asset being acted upon exists+ if (! $assetModel = AssetModel::find($assetModelId)) {+ return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/models/message.does_not_exist')), 404);+ }++ // the asset is valid+ if (isset($assetModel->id)) {+ $this->authorize('view', $assetModel);++ // Check that the file being requested exists for the asset+ if (! $log = Actionlog::whereNotNull('filename')->where('item_id', $assetModel->id)->find($fileId)) {+ return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/models/message.download.no_match', ['id' => $fileId])), 404);+ }++ // Form the full filename with path+ $file = 'private_uploads/assetmodels/'.$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/models/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/models/message.download.error', ['id' => $fileId])), 500);+ }++ /**+ * Delete the associated file+ *+ * @param int $assetModelId+ * @param int $fileId+ * @since [v7.0.12]+ * @author [r-xyz]+ */+ public function destroy($assetModelId = null, $fileId = null) : JsonResponse+ {+ // Start by checking if the asset being acted upon exists+ if (! $assetModel = AssetModel::find($assetModelId)) {+ return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/models/message.does_not_exist')), 404);+ }++ $rel_path = 'private_uploads/assetmodels';++ // the asset is valid+ if (isset($assetModel->id)) {+ $this->authorize('update', $assetModel);++ // 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/models/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/models/message.deletefile.error')), 500);+ }++ return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/models/message.deletefile.error')), 500);+ }+}diff --git a/resources/lang/en-GB/admin/models/message.php b/resources/lang/en-GB/admin/models/message.phpindex ae3bc34eed..18a3fb10ce 100644--- a/resources/lang/en-GB/admin/models/message.php+++ b/resources/lang/en-GB/admin/models/message.php@@ -43,5 +43,11 @@ return array('success' => 'Model deleted!|:success_count models deleted!','success_partial' => ':success_count model(s) were deleted, however :fail_count were unable to be deleted because they still have assets associated with them.'),+ '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',+ ],);diff --git a/routes/api.php b/routes/api.phpindex 0eb0d834cf..b57ed08976 100644--- a/routes/api.php+++ b/routes/api.php@@ -797,7 +797,40 @@ Route::group(['prefix' => 'v1', 'middleware' => ['api', 'throttle:api']], functi'restore'])->name('api.models.restore');+ Route::post('{id}/restore',+ [+ Api\AssetModelsController::class,+ 'restore'+ ]+ )->name('api.models.restore');++ Route::post('{model_id}/files',+ [+ Api\AssetModelFilesController::class,+ 'store'+ ]+ )->name('api.models.files');+ Route::get('{model_id}/files',+ [+ Api\AssetModelFilesController::class,+ 'list'+ ]+ )->name('api.models.files');++ Route::get('{model_id}/file/{file_id}',+ [+ Api\AssetModelFilesController::class,+ 'show'+ ]+ )->name('api.models.assets.file');++ Route::delete('{model_id}/file/{file_id}',+ [+ Api\AssetModelFilesController::class,+ 'destroy'+ ]+ )->name('api.models.file');});Route::resource('models',diff --git a/tests/Feature/AssetModels/Api/AssetModelFilesTest.php b/tests/Feature/AssetModels/Api/AssetModelFilesTest.phpnew file mode 100644index 0000000000..c22609c0c7--- /dev/null+++ b/tests/Feature/AssetModels/Api/AssetModelFilesTest.php@@ -0,0 +1,120 @@+<?php++namespace Tests\Feature\AssetModels\Api;++use App\Models\AssetModel;+use App\Models\User;+use Illuminate\Http\UploadedFile;+use Tests\TestCase;++class AssetModelFilesTest extends TestCase+{+ public function testAssetModelApiAcceptsFileUpload()+ {+ // Upload a file to a model++ // Create a model to work with+ $model = AssetModel::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.models.files.store', ['model_id' => $model[0]["id"]]), [+ 'file' => [UploadedFile::fake()->create("test.jpg", 100)]+ ])+ ->assertOk();+ }++ public function testAssetModelApiListsFiles()+ {+ // List all files on a model++ // Create an model to work with+ $model = AssetModel::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.models.files.index', ['model_id' => $model[0]["id"]]))+ ->assertOk()+ ->assertJsonStructure([+ 'status',+ 'messages',+ 'payload',+ ]);+ }++ public function testAssetModelApiDownloadsFile()+ {+ // Download a file from a model++ // Create a model to work with+ $model = AssetModel::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.models.files.store', ['model_id' => $model[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.models.files.index', ['model_id' => $model[0]["id"]]))+ ->assertOk();++ // Get the file+ $this->actingAsForApi($user)+ ->get(+ route('api.models.files.show', [+ 'model_id' => $model[0]["id"],+ 'file_id' => $result->decodeResponseJson()->json()["payload"][0]["id"],+ ]))+ ->assertOk();+ }++ public function testAssetModelApiDeletesFile()+ {+ // Delete a file from a model++ // Create a model to work with+ $model = AssetModel::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.models.files.store', ['model_id' => $model[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.models.files.index', ['model_id' => $model[0]["id"]]))+ ->assertOk();++ // Delete the file+ $this->actingAsForApi($user)+ ->delete(+ route('api.models.files.destroy', [+ 'model_id' => $model[0]["id"],+ 'file_id' => $result->decodeResponseJson()->json()["payload"][0]["id"],+ ]))+ ->assertOk();+ }+}