Can authorize method in Request class return customized message for HandlesAuthorization trait?
Asked Answered
K

2

11

I have the following code in Request class to check if the user is authorized to perform update.

HandlesAuthorization trait, by default gives default message. Is there any way to return customized message? I saw the authorize method in Request class can return boolean value only.

class UpdateRoleRequest extends Request
{
    private $UserPermissionsSession;

    public function __construct(IRole $Role) {
        $this->UserPermissionsSession = new UserPermissionsSession();
    }

    public function authorize() {
        $UserID = \Auth::user()->UserID;
        return $this->UserPermissionsSession->CheckPermissionExists($UserID);
    }

}
Knapp answered 29/9, 2017 at 19:7 Comment(1)
you can implement failedAuthorization method on requestSkinflint
A
14

I believe you shouldn't look at HandlesAuthorization trait. All you need to do is implementing failedAuthorization method in your request class.

In FormRequest class it's defined like this:

/**
 * Handle a failed authorization attempt.
 *
 * @return void
 *
 * @throws \Illuminate\Auth\Access\AuthorizationException
 */
protected function failedAuthorization()
{
    throw new AuthorizationException('This action is unauthorized.');
}

so all you need is to override this method in your UpdateRoleRequest class for example like this:

protected function failedAuthorization()
{
    throw new \Illuminate\Auth\Access\AuthorizationException('User has to be an admin.');
}
Alcorn answered 4/10, 2017 at 17:55 Comment(2)
Thank you so much, but what if i want to have this custom message only in one condition? I want to send that custom message only if a condition is true, otherwise i want another check that has nothing to do with user being admin, and i want default message in that case.Pedantry
Thank you but unfortunately some one deleted your answer and took the chance to make this page better....Pedantry
P
1

To provide a solution answering @Pooria Honarmand's question for anyone else wondering the same;
If you have more specific messages for different conditions that you already checked in the authorize method and you don't want to repeat those checks here, just introduce one or more class-based variables.

Here is one example having only one condition which does result in a non-standard message: private bool $hasMissingClientId = false;

public function authorize(): bool
{
    // several other checks

    if (empty($user->client_id)) {
        $this->hasMissingClientId = true;
        return false;
    }
    return true;
}

protected function failedAuthorization()
{
    if ($this->hasMissingClientId) {
        throw new AuthorizationException('User has to be assigned to specific client.');
    }
    parent::failedAuthorization();
}
Pursue answered 19/2, 2021 at 11:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.