如何为客人分配一个角色&权限

时间:2016-06-07 13:31:59

标签: php laravel laravel-5.2 entrust

我目前正在尝试为任何访客分配“访客”角色,以便他们可以拥有权限。我目前有以下代码,这是一些中间件的一部分,这似乎是错误的地方拥有它,我会假设有一个更好的地方,我尝试使用服务提供商,但我无法附加组

 if($this->auth->guest())
    {
        $user = new User();
        $user->username = 'Guest';

        $role = Role::where('name', '=', 'guest')
                ->with('perms')
                ->first();


        $user->perms = new Collection();
        $user->perms->add($role);

        $perms = explode('|', $permissions);

        foreach($user->perms as $p) {
            foreach($p->perms as $pp) {
                foreach($perms as $perm) {
                    if($perm === $pp->name)
                        return $next($request);
                }
            }
        }
    }

正如您所看到的,这非常特定于中间件,理想情况下我想在第一个可能的实例中攻击该角色,以便它可以在应用程序的任何部分中使用

2 个答案:

答案 0 :(得分:0)

在这种情况下只使用会话

  session::put('role',$role);

并在视图中

 @if(Session::has('role') == 'whatever') 
 // show this content

同样适用于权限 在会话中添加一组权限,然后使用in_array

答案 1 :(得分:0)

我认为这个地方是对的,但请记住,您正在对每个请求执行此验证,它看起来很重。那么,为什么不使用会话或缓存?

使用会话:

if($this->auth->guest()){
    $userPerms = [];

    if (\Session::has('permissions')){
        $userPerms = \Session::get('permissions');
    }
    else{
        $user = new User();
        $user->username = 'Guest';
        // the rest of your code here...
        $userPerms = $user->perms;

        // update the session the first time
        \Session::put('permissions', userPerms)
    }

    // comparison here
}

您可以使用Cache提供程序应用相同的逻辑。

相关问题