douyinmian8151 2018-08-10 19:37
浏览 57
已采纳

用户角色 - 使用Gate还是不使用?

I need to implement simple User Role such as Admin, Moderator, and Analytics.

I don't need to add permission/features on each role. A user can be assigned to 1 role only.

There might be many way to implement this in Laravel, I am looking decent way implementing this and secure.

Would Gate facade be right approach for this? Or create a Role model with methods. Something like: if ($user->hasRole(['admin', 'moderator'])) { //can view this feature } in blade or controller. There might be a cleaner way than this and role check in middleware.

  • 写回答

1条回答 默认 最新

  • douyi7055 2018-08-10 20:37
    关注

    Regardless of whether you use Middleware, Request authorize method, Policies or Gates (which can be used as a Middleware), you would still need Role model.

    Roles table will be the place you store all the roles and attach them to users by their name or slugs.

    1. Create a Role model.

      • Id
      • Name
    2. If you're sure, that a user can only have 1 Role, then add role_id to your users table.

    3. Add the relationships inside the User and Role models.

    User.php

    public function role()
    {
        return $this->hasOne(Role::class);
    }
    

    Role.php

    public function user()
    {
         return $this->belongsTo(User::class);
    }
    

    4. In your AuthServiceProvider.php, you can define the gates:

    (assuming role_id is not nullable)

    Gate::define('do-this', function ($user) {
        return in_array($user->role->name, DoThisClass::allowedRoles());
    });
    
    1. In your blades, you can check if the user has permission for certain tasks using @can directives.:

      @can('do-this')
          <button>You can definitely do this!</button>
      @endcan
      
    2. In your Routes, you can check if user is authorized by using Gates as a Middleware:

      Route::group(['middleware' => ['can:do-this']], function () {
          Route::get('do-this', 'DoThisController@action');
      });
      

    Why should you tie Gates with names rather than ID of Roles?

    Since Roles can be deleted and it's super unreadable to use their ID, I would recommend using Role names.

    The IDs can mismatch in the code and the databases when different enviroments are used.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单