Skip to content

A free open source IT asset/license management system

Validation rules to prevent switchng user companies if assets are assigned

snipeabb422153903
diff --git a/app/Http/Requests/SaveUserRequest.php b/app/Http/Requests/SaveUserRequest.php
index f778d016df..5a47362cfc 100644
--- a/app/Http/Requests/SaveUserRequest.php
+++ b/app/Http/Requests/SaveUserRequest.php
@@ -6,6 +6,7 @@ use App\Models\Setting;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
+use App\Rules\UserCannotSwitchCompaniesIfItemsAssigned;
class SaveUserRequest extends FormRequest
{
@@ -34,14 +35,7 @@ class SaveUserRequest extends FormRequest
$rules = [
'department_id' => 'nullable|exists:departments,id',
'manager_id' => 'nullable|exists:users,id',
- 'company_id' => [
- // determines if the user is being moved between companies and checks to see if they have any items assigned
- function ($attribute, $value, $fail) {
- if (($this->has('company_id')) && ($this->user?->allAssignedCount() > 0) && (Setting::getSettings()->full_multiple_companies_support)) {
- $fail(trans('admin/users/message.error.multi_company_items_assigned'));
- }
- }
- ]
+ 'company_id' => ['nullable','exists:companies,id']
];
switch ($this->method()) {
@@ -60,11 +54,13 @@ class SaveUserRequest extends FormRequest
$rules['first_name'] = 'required|string|min:1';
$rules['username'] = 'required_unless:ldap_import,1|string|min:1';
$rules['password'] = Setting::passwordComplexityRulesSaving('update').'|confirmed';
+ $rules['company_id'] = [new UserCannotSwitchCompaniesIfItemsAssigned()];
break;
// Save only what's passed
case 'PATCH':
$rules['password'] = Setting::passwordComplexityRulesSaving('update');
+ $rules['company_id'] = [new UserCannotSwitchCompaniesIfItemsAssigned()];
break;
default:
diff --git a/app/Rules/UserCannotSwitchCompaniesIfItemsAssigned.php b/app/Rules/UserCannotSwitchCompaniesIfItemsAssigned.php
new file mode 100644
index 0000000000..c3dd58f424
--- /dev/null
+++ b/app/Rules/UserCannotSwitchCompaniesIfItemsAssigned.php
@@ -0,0 +1,23 @@
+<?php
+
+namespace App\Rules;
+use App\Models\Setting;
+use App\Models\User;
+use Closure;
+use Illuminate\Contracts\Validation\ValidationRule;
+
+class UserCannotSwitchCompaniesIfItemsAssigned implements ValidationRule
+{
+ /**
+ * Run the validation rule.
+ *
+ * @param \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail
+ */
+ public function validate(string $attribute, mixed $value, Closure $fail): void
+ {
+ $user = User::find(request()->route('user')->id);
+ if (($value) && ($user->allAssignedCount() > 0) && (Setting::getSettings()->full_multiple_companies_support)) {
+ $fail(trans('admin/users/message.error.multi_company_items_assigned'));
+ }
+ }
+}