douzhengnao8265 2018-11-30 07:28
浏览 18

我应该在Laravel 5中使用“盖茨”?

I store list of permissions in database.

I have a resource controller:

class UserController extends Controller {

   public function store(Request $request) {
       if (Gate::denies('create-user', User::class)) {

       }       

       /**
        when I use controller helper it throws 
        Illuminate\Auth\Access\AuthorizationException

        like this $this->authorize('create-user', User::class); 
       */

       return response()->json(User::create($request->validated()));
   }   

}

In my case more convenient use Gate::allows way because I have a specific list of permissions.

But how can I throw Illuminate\Auth\Access\AuthorizationException? if a user does not have permission to do this action.

I have to use Gate::allows instead of $this->authorize because in my UserPolicy I have to specify the name of a permission like this:

class UserPolicy
{
    use HandlesAuthorization;

     public function create(User $user)
     {
        $has = MyPermissionModel::hasAccess($user, 'create-user');
        return $has;
     }
}

But if I use Gates it seems more clear and correct:

class AuthServiceProvider extends ServiceProvider
{ 
    public function boot()
    { 
      Gate::define('create-user', 'App\Policies\UserPolicy@create');
    }
}

And now I can check access anywhere, not only inside UserController.

So my questions are:

What is a better way to check permissions when I store my permissions dynamically in DB?

How can I throw Illuminate\Auth\Access\AuthorizationException? if I use Gates.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥500 火焰左右视图、视差(基于双目相机)
    • ¥100 set_link_state
    • ¥15 虚幻5 UE美术毛发渲染
    • ¥15 CVRP 图论 物流运输优化
    • ¥15 Tableau online 嵌入ppt失败
    • ¥100 支付宝网页转账系统不识别账号
    • ¥15 基于单片机的靶位控制系统
    • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
    • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
    • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本