Validator for users switching companies

Signed-off-by: snipe <snipe@snipe.net>
This commit is contained in:
snipe 2024-08-29 14:50:07 +01:00
parent b64ed254e0
commit 17cc632a3b
2 changed files with 32 additions and 6 deletions

View file

@ -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:

View file

@ -0,0 +1,26 @@
<?php
namespace App\Rules;
use App\Models\Setting;
use App\Models\User;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Contracts\Validation\DataAwareRule;
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'));
}
}
}