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

 

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