繁体   English   中英

Spatie / Laravel-Permission映射具有控制器方法的权限

[英]Spatie/Laravel-Permission mapping permissions with controller methods

有谁知道一种使用权限授权映射控制器方法的方法?

假设我有20个控制器,它们具有indexstoreshowdelete方法,并且我不想为了这个... DRY而在该控制器的每个方法中都添加相应的权限。

我想做的是尝试将权限与控制器操作映射在一起。

一个例子是:

https://laravel.com/docs/5.5/authorization#writing-gates

Gate :: resource('posts','PostPolicy');

这与手动定义以下Gate定义相同:

Gate :: define('posts.view','PostPolicy @ view');

Gate :: define('posts.create','PostPolicy @ create');

Gate :: define('posts.update','PostPolicy @ update');

Gate :: define('posts.delete','PostPolicy @ delete');

对我来说,这样的事情适合:

Permission::map('route', 'permission');
Permission::map('users.store', 'create-user');

甚至更好

Permission::mapResource('users', '????');

如果您有更好的建议,我为此创建了一个特质。

namespace App\Traits;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Pluralizer;
use Spatie\Permission\Exceptions\UnauthorizedException;

trait Authorisation
{
    private $permissions = [
        'index'   => 'view',
        'store'   => 'create',
        'show'    => 'view',
        'update'  => 'edit',
        'destroy' => 'delete'
    ];

    private $action;

    public function callAction($method, $parameters)
    {

        $permission = $this->getPermission($method);

        if(($permission && Auth::user()->can($permission)) || !$permission)
            return parent::callAction($method, $parameters);

        if(Request::ajax()) {
            return response()->json([
                'response' => str_slug($permission.'_not_allowed', '_')
            ], 403);
        }

        throw UnauthorizedException::forPermissions([$permission]);
    }

    public function getPermission($method)
    {
        if(!$this->action = array_get($this->getPermissions(), $method)) return null;

        return  $this->routeName() ?  $this->actionRoute() : $this->action;
    }

    public function registerActionPermission($action, $permission) {
        $this->permissions[$action] = $permission;
    }

    private function actionRoute() {
        return Pluralizer::singular($this->action . '-' . $this->routeName());
    }

    private function routeName() {
        return explode('.', Request::route()->getName())[0];
    }

    private function getPermissions()
    {
        return $this->permissions;
    }
}

并在控制器中使用它,例如:

use Authorisation;

并且如果想要对$permissions中不存在的操作的自定义$permissions

$this->registerActionPermission('action_name', 'action-permission');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM