Laravel 的用户授权

简介

Gates 是用来判断用户是否有权限执行某个动作的闭包函数。

定义

Gates 通常在 App\Providers\AuthServiceProvider 中定义。

Gates 的第一个参数为用户实例,支持可选参数,如 Eloquent 模型:

public function boot()
{
    $this->registerPolicies();

    // 定义编辑设置的权限
    Gate::define('edit-settings', function ($user) {
        return $user->isAdmin;
    });

    // 定义更新文章的权限
    Gate::define('update-post', function ($user, $post) {
        return $user->id === $post->user_id;
    });
}
public function boot()
{
    $this->registerPolicies();

    Gate::define('update-post', 'App\Policies\PostPolicy@update');
}

使用

if (Gate::allows('edit-settings')) {
    // 当前用户可以编辑设置
}

if (Gate::allows('update-post', $post)) {
    // 当前用户可以更新文章
}

if (Gate::denies('update-post', $post)) {
    // 当前用户不能更新文章
}

if (Gate::forUser($user)->allows('update-post', $post)) {
    // 指定用户可以更新文章
}

if (Gate::forUser($user)->denies('update-post', $post)) {
    // 指定用户不能更新文章
}

参数上下文

Gate::define('create-post', function ($user, $category, $extraFlag) {
    return $category->group > 3 && $extraFlag === true;
});

if (Gate::check('create-post', [$category, $extraFlag])) {
    // The user can create the post...
}

授权响应

use Illuminate\Support\Facades\Gate;
use Illuminate\Auth\Access\Response;

Gate::define('edit-settings', function ($user) {
    return $user->isAdmin
                ? Response::allow()
                : Response::deny('You must be a super administrator.');
});
// inspect 获取 Gate 返回的完整授权响应
$response = Gate::inspect('edit-settings', $post);

if ($response->allowed()) {
    // 当前行为已授权...
} else {
    echo $response->message();
}

授权拦截

// 在所有其他授权检查之前执行
Gate::before(function ($user, $ability) {
    if ($user->isSuperAdmin()) {
        return true;
    }
});

// 在所有其他授权检查后执行
Gate::after(function ($user, $ability, $result, $arguments) {
    if ($user->isSuperAdmin()) {
        return true;
    }
});

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章