使用控制器方法

时间:2018-01-25 21:49:08

标签: php laravel laravel-authorization

有没有人知道用权限授权映射控制器方法的方法?

让我们说我有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', '????');

1 个答案:

答案 0 :(得分:0)

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

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

中不存在的操作的自定义权限
$this->registerActionPermission('action_name', 'action-permission');