From 0eda53c484688f017807b04e6d977ca3c49216e5 Mon Sep 17 00:00:00 2001 From: Brady Wetherington Date: Fri, 23 Oct 2020 16:55:10 -0700 Subject: [PATCH] Add a new custom validator for Users to prevent someone from managing themselves --- app/Models/User.php | 2 +- app/Providers/ValidationServiceProvider.php | 21 +++++++++++++++++++++ resources/lang/en/validation.php | 1 + 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/app/Models/User.php b/app/Models/User.php index 297a8f460e..d5868ce600 100755 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -74,7 +74,7 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo 'password' => 'required|min:8', 'locale' => 'max:10|nullable', 'website' => 'url|nullable', - 'manager_id' => 'nullable|exists:users,id', + 'manager_id' => 'nullable|exists:users,id|cant_manage_self', 'location_id' => 'exists:locations,id|nullable', ]; diff --git a/app/Providers/ValidationServiceProvider.php b/app/Providers/ValidationServiceProvider.php index 1fd815084a..b8e028226e 100644 --- a/app/Providers/ValidationServiceProvider.php +++ b/app/Providers/ValidationServiceProvider.php @@ -107,6 +107,27 @@ class ValidationServiceProvider extends ServiceProvider return preg_match('/\p{Z}|\p{S}|\p{P}/', $value); }); + Validator::extend('cant_manage_self', function ($attribute, $value, $parameters, $validator) { + // $value is the actual *value* of the thing that's being validated + // $attribute is the name of the field that the validation is running on - probably manager_id in our case + // $parameters are the optional parameters - an array for everything, split on commas. But we don't take any params here. + // $validator gives us proper access to the rest of the actual data + $data = $validator->getData(); + + if(array_key_exists("id", $data)) { + if ($value && $value == $data['id']) { + // if you definitely have an ID - you're saving an existing user - and your ID matches your manager's ID - fail. + return false; + } else { + return true; + } + } else { + // no 'id' key to compare against (probably because this is a new user) + // so it automatically passes this validation + return true; + } + }); + } diff --git a/resources/lang/en/validation.php b/resources/lang/en/validation.php index e399504d08..31ba3761e8 100644 --- a/resources/lang/en/validation.php +++ b/resources/lang/en/validation.php @@ -117,6 +117,7 @@ return array( "hashed_pass" => "Your current password is incorrect", "statuslabel_type" => "You must select a valid status label type", ], + 'cant_manage_self' => "A user cannot be their own manager", /* |--------------------------------------------------------------------------