A free open source IT asset/license management system
Location Scoping: Fixed ordering for company check on user save
snipea6c82eec7b3a
diff --git a/app/Http/Requests/SaveUserRequest.php b/app/Http/Requests/SaveUserRequest.phpindex 87cbe2bac9..b948911c13 100644--- a/app/Http/Requests/SaveUserRequest.php+++ b/app/Http/Requests/SaveUserRequest.php@@ -36,6 +36,7 @@ class SaveUserRequest extends FormRequest'company_id' => ['nullable', 'integer', 'exists:companies,id'],'company_ids' => 'nullable|array','company_ids.*' => 'integer|exists:companies,id',+ 'location_id' => 'nullable|integer|exists:locations,id|fmcs_location',];switch ($this->method()) {diff --git a/app/Importer/UserImporter.php b/app/Importer/UserImporter.phpindex 4aa92a0032..0182c400c1 100644--- a/app/Importer/UserImporter.php+++ b/app/Importer/UserImporter.php@@ -5,6 +5,7 @@ namespace App\Importer;use App\Models\Asset;use App\Models\Company;use App\Models\Department;+use App\Models\Location;use App\Models\Setting;use App\Models\User;use App\Notifications\WelcomeNotification;@@ -146,6 +147,18 @@ class UserImporter extends ItemImporterunset($this->item['activated']);}+ if (! $this->validateFmcsLocation($this->item['location_id'] ?? null, $companyIds)) {+ $loc = Location::find($this->item['location_id']);+ $msg = trans('validation.fmcs_location', [+ 'location' => $loc?->name ?? $this->item['location_id'],+ 'location_company' => $loc?->company?->name ?? trans('general.unassigned'),+ ]);+ $this->log($msg);+ $this->addErrorToBag($user, 'location_id', $msg);++ return;+ }+$user->update($this->sanitizeItemForUpdating($user));// Why do we have to do this twice? Update should@@ -181,6 +194,18 @@ class UserImporter extends ItemImporter$this->item['password'] = $this->tempPassword;$this->log('No matching user, creating one');++ if (! $this->validateFmcsLocation($this->item['location_id'] ?? null, $companyIds)) {+ $msg = trans('validation.fmcs_location', [+ 'location' => Location::find($this->item['location_id'])?->name ?? $this->item['location_id'],+ 'location_company' => Location::find($this->item['location_id'])?->company?->name ?? trans('general.unassigned'),+ ]);+ $this->log($msg);+ $this->addErrorToBag(new User, 'location_id', $msg);++ return;+ }+$user = new User;$user->created_by = auth()->id();@@ -268,6 +293,37 @@ class UserImporter extends ItemImporter* we need to set those empty strings to null to avoid passing bad data to the database* (ie ending up with 0000-00-00 instead of the intended null).*/+ /**+ * Returns true when the given location is compatible with the given company IDs under+ * FMCS location scoping rules. Mirrors the fmcs_location custom validator.+ *+ * @param int[] $companyIds+ */+ private function validateFmcsLocation(?int $locationId, array $companyIds): bool+ {+ $settings = Setting::getSettings();++ if ($settings->full_multiple_companies_support != '1' || $settings->scope_locations_fmcs != '1') {+ return true;+ }++ if (empty($companyIds) || ! $locationId) {+ return true;+ }++ $location = Location::find($locationId);++ if (! $location) {+ return true;+ }++ if ($location->company_id === null) {+ return (bool) $settings->null_company_is_floater;+ }++ return in_array($location->company_id, $companyIds);+ }+private function handleEmptyStringsForDates(): void{if ($this->item['start_date'] === '') {diff --git a/app/Models/User.php b/app/Models/User.phpindex e43f45cc23..a7f46a0561 100644--- a/app/Models/User.php+++ b/app/Models/User.php@@ -127,7 +127,7 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo'locale' => 'max:10|nullable','website' => 'url|nullable|max:191','manager_id' => 'nullable|exists:users,id|cant_manage_self',- 'location_id' => 'exists:locations,id|nullable|fmcs_location',+ 'location_id' => 'exists:locations,id|nullable','start_date' => 'nullable|date_format:Y-m-d','end_date' => 'nullable|date_format:Y-m-d|after_or_equal:start_date','autoassign_licenses' => 'boolean',diff --git a/app/Providers/ValidationServiceProvider.php b/app/Providers/ValidationServiceProvider.phpindex b8f096aed2..0d14c4260f 100644--- a/app/Providers/ValidationServiceProvider.php+++ b/app/Providers/ValidationServiceProvider.php@@ -373,10 +373,23 @@ class ValidationServiceProvider extends ServiceProvider(array) ($data['company_ids'] ?? []),[$data['company_id'] ?? null])));+ // No company context available (e.g. model-level validation before companies are+ // persisted) — nothing to compare against, so skip the check.+ if (empty($companyIds)) {+ return true;+ }+$location = Location::find($value);- if ($location && ! in_array($location->company_id, $companyIds)) {- return false;+ if ($location) {+ if ($location->company_id === null) {+ // Null-company location: accessible to companied users only when floater is on.+ return (bool) $settings->null_company_is_floater;+ }++ if (! in_array($location->company_id, $companyIds)) {+ return false;+ }}}diff --git a/tests/Feature/Importing/Api/ImportUsersFmcsLocationTest.php b/tests/Feature/Importing/Api/ImportUsersFmcsLocationTest.phpnew file mode 100644index 0000000000..702cd9470c--- /dev/null+++ b/tests/Feature/Importing/Api/ImportUsersFmcsLocationTest.php@@ -0,0 +1,115 @@+<?php++namespace Tests\Feature\Importing\Api;++use App\Models\Company;+use App\Models\Import;+use App\Models\Location;+use App\Models\User;+use Illuminate\Testing\TestResponse;+use Tests\Support\Importing\CleansUpImportFiles;+use Tests\Support\Importing\UsersImportFileBuilder as ImportFileBuilder;++/**+ * Validates that FMCS location scoping is enforced during user imports when+ * full_multiple_companies_support + scope_locations_fmcs are both enabled.+ */+class ImportUsersFmcsLocationTest extends ImportDataTestCase+{+ use CleansUpImportFiles;++ protected function importFileResponse(array $parameters = []): TestResponse+ {+ if (! array_key_exists('import-type', $parameters)) {+ $parameters['import-type'] = 'user';+ }++ return parent::importFileResponse($parameters);+ }++ public function test_user_and_location_in_same_company_is_imported()+ {+ $this->settings->enableScopedLocationsWithFullMultipleCompanySupport();++ $company = Company::factory()->create();+ $location = Location::factory()->create(['company_id' => $company->id]);++ $importFileBuilder = ImportFileBuilder::new([+ 'companyName' => $company->name,+ 'location' => $location->name,+ ]);++ $row = $importFileBuilder->firstRow();+ $import = Import::factory()->users()->create(['file_path' => $importFileBuilder->saveToImportsDirectory()]);++ $this->actingAsForApi(User::factory()->superuser()->create());+ $this->importFileResponse(['import' => $import->id])->assertOk();++ $this->assertTrue(User::where('username', $row['username'])->exists(), 'User should be created when location matches company');+ }++ public function test_user_and_location_in_different_companies_is_rejected()+ {+ $this->settings->enableScopedLocationsWithFullMultipleCompanySupport();++ [$companyA, $companyB] = Company::factory()->count(2)->create();+ $location = Location::factory()->create(['company_id' => $companyB->id]);++ $importFileBuilder = ImportFileBuilder::new([+ 'companyName' => $companyA->name,+ 'location' => $location->name,+ ]);++ $row = $importFileBuilder->firstRow();+ $import = Import::factory()->users()->create(['file_path' => $importFileBuilder->saveToImportsDirectory()]);++ $this->actingAsForApi(User::factory()->superuser()->create());+ $this->importFileResponse(['import' => $import->id])->assertInternalServerError();++ $this->assertFalse(User::where('username', $row['username'])->exists(), 'User should not be created when location is in a different company');+ }++ public function test_null_company_location_with_floater_on_is_imported()+ {+ $this->settings->enableScopedLocationsWithFullMultipleCompanySupport();+ $this->settings->enableFloaterMode();++ $company = Company::factory()->create();+ $location = Location::factory()->create(['company_id' => null]);++ $importFileBuilder = ImportFileBuilder::new([+ 'companyName' => $company->name,+ 'location' => $location->name,+ ]);++ $row = $importFileBuilder->firstRow();+ $import = Import::factory()->users()->create(['file_path' => $importFileBuilder->saveToImportsDirectory()]);++ $this->actingAsForApi(User::factory()->superuser()->create());+ $this->importFileResponse(['import' => $import->id])->assertOk();++ $this->assertTrue(User::where('username', $row['username'])->exists(), 'User should be created when location has no company and floater is on');+ }++ public function test_null_company_location_with_floater_off_is_rejected()+ {+ $this->settings->enableScopedLocationsWithFullMultipleCompanySupport();+ $this->settings->disableFloaterMode();++ $company = Company::factory()->create();+ $location = Location::factory()->create(['company_id' => null]);++ $importFileBuilder = ImportFileBuilder::new([+ 'companyName' => $company->name,+ 'location' => $location->name,+ ]);++ $row = $importFileBuilder->firstRow();+ $import = Import::factory()->users()->create(['file_path' => $importFileBuilder->saveToImportsDirectory()]);++ $this->actingAsForApi(User::factory()->superuser()->create());+ $this->importFileResponse(['import' => $import->id])->assertInternalServerError();++ $this->assertFalse(User::where('username', $row['username'])->exists(), 'User should not be created when location has no company and floater is off');+ }+}diff --git a/tests/Feature/Users/Ui/FmcsLocationValidationTest.php b/tests/Feature/Users/Ui/FmcsLocationValidationTest.phpnew file mode 100644index 0000000000..cf0607062d--- /dev/null+++ b/tests/Feature/Users/Ui/FmcsLocationValidationTest.php@@ -0,0 +1,149 @@+<?php++namespace Tests\Feature\Users\Ui;++use App\Models\Company;+use App\Models\Location;+use App\Models\User;+use Tests\TestCase;++/**+ * Validates that FMCS location scoping is enforced (and not over-enforced) when+ * creating or updating a user via the UI with scope_locations_fmcs enabled.+ *+ * Rules under test:+ * 1. User + location in the same company → allowed.+ * 2. User in company A, location in company B → rejected.+ * 3. Location with no company + floater ON → allowed.+ * 4. Location with no company + floater OFF → rejected.+ * 5. No company selected for user → location company is irrelevant → allowed.+ */+class FmcsLocationValidationTest extends TestCase+{+ private function basePayload(array $overrides = []): array+ {+ return array_merge([+ 'first_name' => 'Test',+ 'last_name' => 'User',+ 'username' => 'fmcs-test-'.uniqid(),+ 'password' => 'testpassword1235!!',+ 'password_confirmation' => 'testpassword1235!!',+ ], $overrides);+ }++ public function test_user_and_location_in_same_company_is_allowed_on_create()+ {+ $this->settings->enableScopedLocationsWithFullMultipleCompanySupport();++ $company = Company::factory()->create();+ $location = Location::factory()->create(['company_id' => $company->id]);++ $this->actingAs(User::factory()->superuser()->create())+ ->post(route('users.store'), $this->basePayload([+ 'company_ids' => [$company->id],+ 'location_id' => $location->id,+ ]))+ ->assertSessionHasNoErrors()+ ->assertRedirect();+ }++ public function test_user_and_location_in_different_companies_is_rejected_on_create()+ {+ $this->settings->enableScopedLocationsWithFullMultipleCompanySupport();++ [$companyA, $companyB] = Company::factory()->count(2)->create();+ $location = Location::factory()->create(['company_id' => $companyB->id]);++ $this->actingAs(User::factory()->superuser()->create())+ ->post(route('users.store'), $this->basePayload([+ 'company_ids' => [$companyA->id],+ 'location_id' => $location->id,+ ]))+ ->assertSessionHasErrors('location_id');+ }++ public function test_null_company_location_with_floater_on_is_allowed_on_create()+ {+ $this->settings->enableScopedLocationsWithFullMultipleCompanySupport();+ $this->settings->enableFloaterMode();++ $company = Company::factory()->create();+ $location = Location::factory()->create(['company_id' => null]);++ $this->actingAs(User::factory()->superuser()->create())+ ->post(route('users.store'), $this->basePayload([+ 'company_ids' => [$company->id],+ 'location_id' => $location->id,+ ]))+ ->assertSessionHasNoErrors()+ ->assertRedirect();+ }++ public function test_null_company_location_with_floater_off_is_rejected_on_create()+ {+ $this->settings->enableScopedLocationsWithFullMultipleCompanySupport();+ $this->settings->disableFloaterMode();++ $company = Company::factory()->create();+ $location = Location::factory()->create(['company_id' => null]);++ $this->actingAs(User::factory()->superuser()->create())+ ->post(route('users.store'), $this->basePayload([+ 'company_ids' => [$company->id],+ 'location_id' => $location->id,+ ]))+ ->assertSessionHasErrors('location_id');+ }++ public function test_no_company_selected_allows_any_location_on_create()+ {+ $this->settings->enableScopedLocationsWithFullMultipleCompanySupport();++ $company = Company::factory()->create();+ $location = Location::factory()->create(['company_id' => $company->id]);++ $this->actingAs(User::factory()->superuser()->create())+ ->post(route('users.store'), $this->basePayload([+ 'location_id' => $location->id,+ ]))+ ->assertSessionHasNoErrors()+ ->assertRedirect();+ }++ public function test_user_and_location_in_same_company_is_allowed_on_update()+ {+ $this->settings->enableScopedLocationsWithFullMultipleCompanySupport();++ $company = Company::factory()->create();+ $location = Location::factory()->create(['company_id' => $company->id]);+ $user = User::factory()->create();++ $this->actingAs(User::factory()->superuser()->create())+ ->put(route('users.update', $user), [+ 'first_name' => $user->first_name,+ 'username' => $user->username,+ 'company_ids' => [$company->id],+ 'location_id' => $location->id,+ ])+ ->assertSessionHasNoErrors()+ ->assertRedirect();+ }++ public function test_user_and_location_in_different_companies_is_rejected_on_update()+ {+ $this->settings->enableScopedLocationsWithFullMultipleCompanySupport();++ [$companyA, $companyB] = Company::factory()->count(2)->create();+ $location = Location::factory()->create(['company_id' => $companyB->id]);+ $user = User::factory()->create();++ $this->actingAs(User::factory()->superuser()->create())+ ->put(route('users.update', $user), [+ 'first_name' => $user->first_name,+ 'username' => $user->username,+ 'company_ids' => [$companyA->id],+ 'location_id' => $location->id,+ ])+ ->assertSessionHasErrors('location_id');+ }+}