From 17cc632a3b61ed88872e6028f3781992906be1f8 Mon Sep 17 00:00:00 2001 From: snipe Date: Thu, 29 Aug 2024 14:50:07 +0100 Subject: [PATCH] Validator for users switching companies Signed-off-by: snipe --- app/Http/Requests/SaveUserRequest.php | 12 ++++----- ...erCannotSwitchCompaniesIfItemsAssigned.php | 26 +++++++++++++++++++ 2 files changed, 32 insertions(+), 6 deletions(-) create mode 100644 app/Rules/UserCannotSwitchCompaniesIfItemsAssigned.php diff --git a/app/Http/Requests/SaveUserRequest.php b/app/Http/Requests/SaveUserRequest.php index e16826d16c..4506a2abcd 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 { @@ -35,12 +36,9 @@ class SaveUserRequest extends FormRequest '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')); - } - } + 'nullable', + 'exists:companies,id', + ] ]; @@ -60,11 +58,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..0a53a02bd7 --- /dev/null +++ b/app/Rules/UserCannotSwitchCompaniesIfItemsAssigned.php @@ -0,0 +1,26 @@ +route('user')->id); + if (($value) && ($user->allAssignedCount() > 0) && (Setting::getSettings()->full_multiple_companies_support)) { + $fail(trans('admin/users/message.error.multi_company_items_assigned')); + } + } +}