Skip to content

A free open source IT asset/license management system

Merge branch 'develop' into bug/sc-24884

Spencer Long53ccd196d72f
diff --cc app/Http/Controllers/Api/AssetsController.php
index 28dcaab2fd,57307acbb3..b7a136bb80
--- a/app/Http/Controllers/Api/AssetsController.php
+++ b/app/Http/Controllers/Api/AssetsController.php
@@@ -633,85 -632,95 +633,89 @@@ class AssetsController extends Controll
* Accepts a POST request to update an asset
*
* @author [A. Gianotto] [<[email protected]>]
- * @param \App\Http\Requests\ImageUploadRequest $request
* @since [v4.0]
- * @return \Illuminate\Http\JsonResponse
*/
- public function update(ImageUploadRequest $request, $id)
+ public function update(UpdateAssetRequest $request, Asset $asset): JsonResponse
{
- $this->authorize('update', Asset::class);
+ $asset->fill($request->validated());
- if ($asset = Asset::find($id)) {
- $asset->fill($request->all());
-
- ($request->filled('model_id')) ?
- $asset->model()->associate(AssetModel::find($request->get('model_id'))) : null;
- ($request->filled('rtd_location_id')) ?
- $asset->location_id = $request->get('rtd_location_id') : '';
- ($request->filled('company_id')) ?
- $asset->company_id = Company::getIdForCurrentUser($request->get('company_id')) : '';
-
- ($request->filled('rtd_location_id')) ?
- $asset->location_id = $request->get('rtd_location_id') : null;
-
- /**
- * this is here just legacy reasons. Api\AssetController
- * used image_source once to allow encoded image uploads.
- */
- if ($request->has('image_source')) {
- $request->offsetSet('image', $request->offsetGet('image_source'));
- }
-
- $asset = $request->handleImages($asset);
- $model = AssetModel::find($asset->model_id);
+ if ($request->has('model_id')) {
+ $asset->model()->associate(AssetModel::find($request->validated()['model_id']));
+ }
+ if ($request->has('company_id')) {
+ $asset->company_id = Company::getIdForCurrentUser($request->validated()['company_id']);
+ }
+ if ($request->has('rtd_location_id') && !$request->has('location_id')) {
+ $asset->location_id = $request->validated()['rtd_location_id'];
+ }
+ if ($request->input('last_audit_date')) {
+ $asset->last_audit_date = Carbon::parse($request->input('last_audit_date'))->startOfDay()->format('Y-m-d H:i:s');
+ }
+
+ /**
+ * this is here just legacy reasons. Api\AssetController
+ * used image_source once to allow encoded image uploads.
+ */
+ if ($request->has('image_source')) {
+ $request->offsetSet('image', $request->offsetGet('image_source'));
+ }
+
+ $asset = $request->handleImages($asset);
+ $model = $asset->model;
-
- // Update custom fields
- if (($model) && (isset($model->fieldset))) {
- foreach ($model->fieldset->fields as $field) {
- $field_val = $request->input($field->db_column, null);
-
- if ($request->has($field->db_column)) {
- if ($field->field_encrypted == '1') {
- if (Gate::allows('admin')) {
- $asset->{$field->db_column} = Crypt::encrypt($field_val);
+
+ // Update custom fields
+ $problems_updating_encrypted_custom_fields = false;
+ if (($model) && (isset($model->fieldset))) {
+ foreach ($model->fieldset->fields as $field) {
+ $field_val = $request->input($field->db_column, null);
+
+ if ($request->has($field->db_column)) {
+ if ($field->element == 'checkbox') {
+ if(is_array($field_val)) {
+ $field_val = implode(',', $field_val);
+ }
}
- }
- if ($field->element == 'checkbox') {
- if(is_array($field_val)) {
- $field_val = implode(',', $field_val);
- $asset->{$field->db_column} = $field_val;
+ if ($field->field_encrypted == '1') {
+ if (Gate::allows('admin')) {
+ $field_val = Crypt::encrypt($field_val);
+ } else {
+ $problems_updating_encrypted_custom_fields = true;
+ continue;
+ }
}
- }
- else {
$asset->{$field->db_column} = $field_val;
}
}
}
+ }
+ if ($asset->save()) {
+ if (($request->filled('assigned_user')) && ($target = User::find($request->get('assigned_user')))) {
+ $location = $target->location_id;
+ } elseif (($request->filled('assigned_asset')) && ($target = Asset::find($request->get('assigned_asset')))) {
+ $location = $target->location_id;
+ Asset::where('assigned_type', Asset::class)->where('assigned_to', $asset->id)
+ ->update(['location_id' => $target->location_id]);
+ } elseif (($request->filled('assigned_location')) && ($target = Location::find($request->get('assigned_location')))) {
+ $location = $target->id;
+ }
- if ($asset->save()) {
- if (($request->filled('assigned_user')) && ($target = User::find($request->get('assigned_user')))) {
- $location = $target->location_id;
- } elseif (($request->filled('assigned_asset')) && ($target = Asset::find($request->get('assigned_asset')))) {
- $location = $target->location_id;
-
- Asset::where('assigned_type', \App\Models\Asset::class)->where('assigned_to', $id)
- ->update(['location_id' => $target->location_id]);
- } elseif (($request->filled('assigned_location')) && ($target = Location::find($request->get('assigned_location')))) {
- $location = $target->id;
- }
-
- if (isset($target)) {
- $asset->checkOut($target, Auth::user(), date('Y-m-d H:i:s'), '', 'Checked out on asset update', e($request->get('name')), $location);
- }
-
- if ($asset->image) {
- $asset->image = $asset->getImageUrl();
- }
+ if (isset($target)) {
+ $asset->checkOut($target, Auth::user(), date('Y-m-d H:i:s'), '', 'Checked out on asset update',
+ e($request->get('name')), $location);
+ }
+ if ($asset->image) {
+ $asset->image = $asset->getImageUrl();
++
+ if ($problems_updating_encrypted_custom_fields) {
+ return response()->json(Helper::formatStandardApiResponse('success', $asset, trans('admin/hardware/message.update.encrypted_warning')));
+ } else {
+ return response()->json(Helper::formatStandardApiResponse('success', $asset, trans('admin/hardware/message.update.success')));
+ }
}
--
- return response()->json(Helper::formatStandardApiResponse('success', $asset, trans('admin/hardware/message.update.success')));
- // commenting to make this clear, this was removed in favor of the above temporarily because it breaks jamf2snipe
- // return response()->json(Helper::formatStandardApiResponse('success', (new AssetsTransformer)->transformAsset($asset), trans('admin/hardware/message.update.success')));
- return response()->json(Helper::formatStandardApiResponse('error', null, $asset->getErrors()), 200);
}
-
- return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/hardware/message.does_not_exist')), 200);
+ return response()->json(Helper::formatStandardApiResponse('error', null, $asset->getErrors()), 200);
}
diff --cc database/factories/AssetFactory.php
index 3fa23e9217,6c5e883636..970c196c95
--- a/database/factories/AssetFactory.php
+++ b/database/factories/AssetFactory.php
@@@ -354,16 -354,16 +355,26 @@@ class AssetFactory extends Factor
return $this->state(['requestable' => false]);
}
-
+ public function noPurchaseOrEolDate()
+ {
+ return $this->afterCreating(function (Asset $asset) {
+ $asset->update([
+ 'purchase_date' => null,
+ 'asset_eol_date' => null
+ ]);
+ });
+ }
++
++
+ public function hasEncryptedCustomField(CustomField $field = null)
+ {
+ return $this->state(function () use ($field) {
+ return [
+ 'model_id' => AssetModel::factory()->hasEncryptedCustomField($field),
+ ];
+ });
+ }
+
-
/**
* This allows bypassing model level validation if you want to purposefully
* create an asset in an invalid state. Validation is turned back on
diff --cc tests/Feature/Api/Assets/AssetUpdateTest.php
index ec00724cd7,ed830c379c..baff41e5cd
--- a/tests/Feature/Api/Assets/AssetUpdateTest.php
+++ b/tests/Feature/Api/Assets/AssetUpdateTest.php
@@@ -3,263 -3,53 +3,307 @@@
namespace Tests\Feature\Api\Assets;
use App\Models\Asset;
-use App\Models\CustomField;
+use App\Models\AssetModel;
+use App\Models\Company;
+use App\Models\Location;
+use App\Models\Statuslabel;
+use App\Models\Supplier;
use App\Models\User;
++use App\Models\CustomField;
+ use Illuminate\Support\Facades\Crypt;
use Tests\TestCase;
class AssetUpdateTest extends TestCase
{
-
+ public function testThatANonExistentAssetIdReturnsError()
+ {
+ $this->actingAsForApi(User::factory()->editAssets()->createAssets()->create())
+ ->patchJson(route('api.assets.update', 123456789))
+ ->assertStatusMessageIs('error');
+ }
+
+ public function testRequiresPermissionToUpdateAsset()
+ {
+ $asset = Asset::factory()->create();
+
+ $this->actingAsForApi(User::factory()->create())
+ ->patchJson(route('api.assets.update', $asset->id))
+ ->assertForbidden();
+ }
+
+ public function testGivenPermissionUpdateAssetIsAllowed()
+
+ {
+ $asset = Asset::factory()->create();
+
+ $this->actingAsForApi(User::factory()->editAssets()->create())
+ ->patchJson(route('api.assets.update', $asset->id), [
+ 'name' => 'test'
+ ])
+ ->assertOk();
+ }
+
+ public function testAllAssetAttributesAreStored()
+ {
+ $asset = Asset::factory()->create();
+ $user = User::factory()->editAssets()->create();
+ $userAssigned = User::factory()->create();
+ $company = Company::factory()->create();
+ $location = Location::factory()->create();
+ $model = AssetModel::factory()->create();
+ $rtdLocation = Location::factory()->create();
+ $status = Statuslabel::factory()->create();
+ $supplier = Supplier::factory()->create();
+
+ $response = $this->actingAsForApi($user)
+ ->patchJson(route('api.assets.update', $asset->id), [
+ 'asset_eol_date' => '2024-06-02',
+ 'asset_tag' => 'random_string',
+ 'assigned_user' => $userAssigned->id,
+ 'company_id' => $company->id,
+ 'last_audit_date' => '2023-09-03 12:23:45',
+ 'location_id' => $location->id,
+ 'model_id' => $model->id,
+ 'name' => 'A New Asset',
+ 'notes' => 'Some notes',
+ 'order_number' => '5678',
+ 'purchase_cost' => '123.45',
+ 'purchase_date' => '2023-09-02',
+ 'requestable' => true,
+ 'rtd_location_id' => $rtdLocation->id,
+ 'serial' => '1234567890',
+ 'status_id' => $status->id,
+ 'supplier_id' => $supplier->id,
+ 'warranty_months' => 10,
+ ])
+ ->assertOk()
+ ->assertStatusMessageIs('success')
+ ->json();
+
+ $updatedAsset = Asset::find($response['payload']['id']);
+
+ $this->assertEquals('2024-06-02', $updatedAsset->asset_eol_date);
+ $this->assertEquals('random_string', $updatedAsset->asset_tag);
+ $this->assertEquals($userAssigned->id, $updatedAsset->assigned_to);
+ $this->assertTrue($updatedAsset->company->is($company));
+ $this->assertTrue($updatedAsset->location->is($location));
+ $this->assertTrue($updatedAsset->model->is($model));
+ $this->assertEquals('A New Asset', $updatedAsset->name);
+ $this->assertEquals('Some notes', $updatedAsset->notes);
+ $this->assertEquals('5678', $updatedAsset->order_number);
+ $this->assertEquals('123.45', $updatedAsset->purchase_cost);
+ $this->assertTrue($updatedAsset->purchase_date->is('2023-09-02'));
+ $this->assertEquals('1', $updatedAsset->requestable);
+ $this->assertTrue($updatedAsset->defaultLoc->is($rtdLocation));
+ $this->assertEquals('1234567890', $updatedAsset->serial);
+ $this->assertTrue($updatedAsset->assetstatus->is($status));
+ $this->assertTrue($updatedAsset->supplier->is($supplier));
+ $this->assertEquals(10, $updatedAsset->warranty_months);
+ $this->assertEquals('2023-09-03 00:00:00', $updatedAsset->last_audit_date->format('Y-m-d H:i:s'));
+ }
+
+ public function testAssetEolDateIsCalculatedIfPurchaseDateUpdated()
+ {
+ $asset = Asset::factory()->laptopMbp()->noPurchaseOrEolDate()->create();
+
+ $this->actingAsForApi(User::factory()->editAssets()->create())
+ ->patchJson((route('api.assets.update', $asset->id)), [
+ 'purchase_date' => '2021-01-01',
+ ])
+ ->assertOk()
+ ->assertStatusMessageIs('success')
+ ->json();
+
+ $asset->refresh();
+
+ $this->assertEquals('2024-01-01', $asset->asset_eol_date);
+ }
+
+ public function testAssetEolDateIsNotCalculatedIfPurchaseDateNotSet()
+ {
+ $asset = Asset::factory()->laptopMbp()->noPurchaseOrEolDate()->create();
+
+ $this->actingAsForApi(User::factory()->editAssets()->create())
+ ->patchJson(route('api.assets.update', $asset->id), [
+ 'name' => 'test asset',
+ 'asset_eol_date' => '2022-01-01'
+ ])
+ ->assertOk()
+ ->assertStatusMessageIs('success')
+ ->json();
+
+ $asset->refresh();
+
+ $this->assertEquals('2022-01-01', $asset->asset_eol_date);
+ }
+
+ public function testAssetEolExplicitIsSetIfAssetEolDateIsExplicitlySet()
+ {
+ $asset = Asset::factory()->laptopMbp()->create();
+
+ $this->actingAsForApi(User::factory()->editAssets()->create())
+ ->patchJson(route('api.assets.update', $asset->id), [
+ 'asset_eol_date' => '2025-01-01',
+ ])
+ ->assertOk()
+ ->assertStatusMessageIs('success')
+ ->json();
+
+ $asset->refresh();
+
+ $this->assertEquals('2025-01-01', $asset->asset_eol_date);
+ $this->assertTrue($asset->eol_explicit);
+ }
+
+ public function testAssetTagCannotUpdateToNullValue()
+ {
+ $asset = Asset::factory()->laptopMbp()->create();
+
+ $this->actingAsForApi(User::factory()->editAssets()->create())
+ ->patchJson(route('api.assets.update', $asset->id), [
+ 'asset_tag' => null,
+ ])
+ ->assertOk()
+ ->assertStatusMessageIs('error');
+ }
+
+ public function testAssetTagCannotUpdateToEmptyStringValue()
+ {
+ $asset = Asset::factory()->laptopMbp()->create();
+
+ $this->actingAsForApi(User::factory()->editAssets()->create())
+ ->patchJson(route('api.assets.update', $asset->id), [
+ 'asset_tag' => "",
+ ])
+ ->assertOk()
+ ->assertStatusMessageIs('error');
+ }
+
+ public function testModelIdCannotUpdateToNullValue()
+ {
+ $asset = Asset::factory()->laptopMbp()->create();
+
+ $this->actingAsForApi(User::factory()->editAssets()->create())
+ ->patchJson(route('api.assets.update', $asset->id), [
+ 'model_id' => null
+ ])
+ ->assertOk()
+ ->assertStatusMessageIs('error');
+ }
+
+ public function testModelIdCannotUpdateToEmptyStringValue()
+ {
+ $asset = Asset::factory()->laptopMbp()->create();
+
+ $this->actingAsForApi(User::factory()->editAssets()->create())
+ ->patchJson(route('api.assets.update', $asset->id), [
+ 'model_id' => ""
+ ])
+ ->assertOk()
+ ->assertStatusMessageIs('error');
+ }
+
+ public function testStatusIdCannotUpdateToNullValue()
+ {
+ $asset = Asset::factory()->laptopMbp()->create();
+
+ $this->actingAsForApi(User::factory()->editAssets()->create())
+ ->patchJson(route('api.assets.update', $asset->id), [
+ 'status_id' => null
+ ])
+ ->assertOk()
+ ->assertStatusMessageIs('error');
+ }
+
+ public function testStatusIdCannotUpdateToEmptyStringValue()
+ {
+ $asset = Asset::factory()->laptopMbp()->create();
+
+ $this->actingAsForApi(User::factory()->editAssets()->create())
+ ->patchJson(route('api.assets.update', $asset->id), [
+ 'status_id' => ""
+ ])
+ ->assertOk()
+ ->assertStatusMessageIs('error');
+ }
+
+ public function testIfRtdLocationIdIsSetWithoutLocationIdAssetReturnsToDefault()
+ {
+ $location = Location::factory()->create();
+ $asset = Asset::factory()->laptopMbp()->create([
+ 'location_id' => $location->id
+ ]);
+ $rtdLocation = Location::factory()->create();
+
+ $this->actingAsForApi(User::factory()->editAssets()->create())
+ ->patchJson(route('api.assets.update', $asset->id), [
+ 'rtd_location_id' => $rtdLocation->id
+ ]);
+
+ $asset->refresh();
+
+ $this->assertTrue($asset->defaultLoc->is($rtdLocation));
+ $this->assertTrue($asset->location->is($rtdLocation));
+ }
+
+ public function testIfLocationAndRtdLocationAreSetLocationIdIsLocation()
+ {
+ $location = Location::factory()->create();
+ $asset = Asset::factory()->laptopMbp()->create();
+ $rtdLocation = Location::factory()->create();
+
+ $this->actingAsForApi(User::factory()->editAssets()->create())
+ ->patchJson(route('api.assets.update', $asset->id), [
+ 'rtd_location_id' => $rtdLocation->id,
+ 'location_id' => $location->id
+ ]);
+
+ $asset->refresh();
+
+ $this->assertTrue($asset->defaultLoc->is($rtdLocation));
+ $this->assertTrue($asset->location->is($location));
+ }
- }
++
+ public function testEncryptedCustomFieldCanBeUpdated()
+ {
+ $this->markIncompleteIfMySQL('Custom Fields tests do not work on MySQL');
+
+ $field = CustomField::factory()->testEncrypted()->create();
+ $asset = Asset::factory()->hasEncryptedCustomField($field)->create();
+ $superuser = User::factory()->superuser()->create();
+
+ $this->actingAsForApi($superuser)
+ ->patchJson(route('api.assets.update', $asset->id), [
+ $field->db_column_name() => 'This is encrypted field'
+ ])
+ ->assertStatusMessageIs('success')
+ ->assertOk();
+
+ $asset->refresh();
+ $this->assertEquals('This is encrypted field', Crypt::decrypt($asset->{$field->db_column_name()}));
+ }
+
+ public function testPermissionNeededToUpdateEncryptedField()
+ {
+ $this->markIncompleteIfMySQL('Custom Fields tests do not work on MySQL');
+
+ $field = CustomField::factory()->testEncrypted()->create();
+ $asset = Asset::factory()->hasEncryptedCustomField($field)->create();
+ $normal_user = User::factory()->editAssets()->create();
+
+ $asset->{$field->db_column_name()} = Crypt::encrypt("encrypted value should not change");
+ $asset->save();
+
+ // test that a 'normal' user *cannot* change the encrypted custom field
+ $this->actingAsForApi($normal_user)
+ ->patchJson(route('api.assets.update', $asset->id), [
+ $field->db_column_name() => 'Some Other Value Entirely!'
+ ])
+ ->assertStatusMessageIs('success')
+ ->assertOk()
+ ->assertMessagesAre('Asset updated successfully, but encrypted custom fields were not due to permissions');
+
+ $asset->refresh();
+ $this->assertEquals("encrypted value should not change", Crypt::decrypt($asset->{$field->db_column_name()}));
+ }
+ }