2016-06-07 76 views
1

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

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); 
       } 
      } 
     } 
    } 

正如你可以看到这是非常具体的中间件,理想的情况是我想要攻击的第一个可能的情况下的作用,因此它可以在应用程序

回答

0

只是使用会话中的任何部分进行使用这种情况下

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

,并在六EW

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

同样适用权限 添加烫发的阵列到会话,然后使用in_array

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提供相同的逻辑。