Hi, I have a class that extends Table and I need to get the currently logged user id (from the Auth component) to use inside a validation rule (using RulesChecker).
I can’t find any clean way to do it. any ideas?
class PlanillasTable extends Table{
...
public function buildRules(RulesChecker $rules) {
$rules->add(
function ($entity, $options) {
if ($entity->userId==$currentlyLoggedUser) return true;
else return false;
},
'validUser',
[
'errorField' => 'author',
'message' => 'author is not valid'
]
);
}
}
Rules are more suited for keeping the internal DB state consistent. Checking against the user, which is essentially a request parameter, should probably be done in validator. The question then is how to make the user available to the validator. This can be done in different ways, here’s what the Cookbook suggests [1]:
If you need to pass additional data to your validation methods such as the current user’s id, you can use a custom dynamic provider from your controller.
$this->Examples->validator('default')->provider('passed', [
'userid' => $this->Auth->user('id')
]);
Then in the validator method
public function customValidationMethod($check, array $context)
{
$userid = $context['providers']['passed']['userid'];
}
[1] https://book.cakephp.org/3/en/core-libraries/validation.html#using-custom-validation-rules
I mulled about it and I don’t like the way the Cookbook does it at all. There 're different approaches, but here’s what I would probably do:
Custom validation provider validating against the current user:
class CurrentUserValidationProvider
{
protected $CurrentUser;
public function __construct($CurrentUser)
{
$this->CurrentUser = $CurrentUser;
}
public function validateIsOwner($value, $context): bool
{
// Some kind of permission check against the $CurrentUser
return $value == $this->CurrentUser;
}
}
Where the user is available set the provider:
$this->PlanillasTable->getValidator()->setProvider(
'currentUser',
new CurrentUserValidationProvider($currentlyLoggedUser)
);
Attach the rule where appropriate:
$valiator->add('author_id', 'isOwner', [
'provider' => 'currentUser',
'rule' => 'validateIsOwner',
]);
Still not very nice. And you have to take care that the author_id is present.
Thanks for the answer. I was able to solve the issue