9

我在请求类中有以下代码来检查用户是否有权执行更新。

HandlesAuthorization trait, 默认情况下给出默认消息。有没有办法返回自定义消息?我只看到了Request classcan return booleanvalue 中的 authorize 方法。

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);
    }

}
4

2 回答 2

9

我相信你不应该看HandlesAuthorization特质。您需要做的就是failedAuthorization在您的请求类中实现方法。

FormRequest类中它是这样定义的:

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

所以你只需要在你的UpdateRoleRequest类中重写这个方法,例如:

protected function failedAuthorization()
{
    throw new \Illuminate\Auth\Access\AuthorizationException('User has to be an admin.');
}
于 2017-10-04T17:55:49.557 回答
1

为其他想知道相同问题的人提供回答@Pooria Honarmand 问题的解决方案;
如果您已经在authorize方法中检查了针对不同条件的更具体的消息,并且您不想在此处重复这些检查,只需引入一个或多个基于类的变量。

这是一个示例,它只有一个条件会导致非标准消息: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();
}
于 2021-02-19T11:37:58.237 回答