I
I
Igor2019-07-20 00:43:46
PHP
Igor, 2019-07-20 00:43:46

Checking user actions directly in controller method?

Colleagues, good night!
Is there a practice of checking permissions in a controller method?
Me about it:
Method in controller

public function delete()
{
        $this->checkPermission($this->getRole('email'), Action::DELETE);  // Проверка 
        ...
}

I mixed the permission check methods with "Trait" into the base controller.
Now the checkPermission
checkPermission method has appeared in all controllers, it takes the following parameters
1 - Role
2 - Action
That is, in the method that we want to check permission, is it possible for the current user to use this method
If yes, then we don't interfere
. If not, then we throw an exception from the trait or immediately send a message.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
kafkiansky, 2019-07-20
@IgorPI

The trait is redundant here, use DI. Yes, you can check permissions in the controller, as symphony does, for example.

D
Dmitry Derepko, 2019-07-20
@xEpozZ

Make new methods to make your life easier:

public function checkDeletePermission($role) {
    $this->checkPermission($this->getRole($role), Action::DELETE);
}
public function checkReadPermission($role) {
    $this->checkPermission($this->getRole($role), Action::READ);
}
public function checkCreatePermission($role) {
    $this->checkPermission($this->getRole($role), Action::CREATE);
}

And you can also make 1 method with checks by methods, for example:
Controller:
__checkActionsPermissions
____return ['actionView' => ['role' => 'email', 'permission' => Action::VIEW]];
Next, before calling your action, first run this method through validators / checkers.
As a result, you will not pollute your methods with extra code that is not directly related to the essence.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question