2017-08-06 177 views

回答

0

跟着conventions,user_role_id應該命名爲「role_id」,role_id只有「id」,user_name應該是「username」或者在你的Auth configuration裏面改變默認的字段名稱用於你的連接形式。

public function initialize() 
    { 
//... 
    $this->loadComponent('Auth', [ 
       'loginRedirect' => [ 
       'controller' => 'Pages', 
       'action' => 'welcome', 
       'prefix' => 'admin' 
       ], 
       'logoutRedirect' => [ 
       'controller' => 'Users', 
       'action' => 'login', 
       'prefix' => false 
       ], 
       'authError' => 'Unauthorized access...', 
       'authenticate' => [ 
       'Form' => [ 
        'fields' => ['username' => 'user_name', 'password' => 'password'] 
       ] 
       ], 
       'authorize' => 'Controller', 
       'unauthorizedRedirect' => [ 
        'controller' => 'Pages', 
        'action' => 'unauthorized' 
       ], 
      ]); 
// ... 
} 

和裏面你的AppController使somtehing這樣

public function isAuthorized($user) 
     { 

      if(!is_null($this->Auth->user())): // if user is logged 

      $action = $this->request->getParam('action'); // get name action 

      $this->loadModel('Roles'); // load your model Roles 
      $query = $this->Authorizations->find() // find inside Roles 
      ->where([ 
      'Roles.role_id IN' => $user['user_role_id'], // where role_id is like user_role_id of current user 
      'Roles.ctl_'.$action => 1 // and where ctl_[action] is set to 1 
      ])->toArray(); 

      if (!empty($query)): // if we find an occurence, we allow the action 
       return true; 
      else: // else we don't authorize 
       return false, 
      endif; 

      /* previous lines can be change with this ----> return (!empty($query)); */ 
      else: // if user is not connected we don't allow action 
      return false 
      endif; 
    } 

和完成,我認爲這是更好地使用「前綴」,前綴U可以簡化授權程序(將沒有前綴我允許,前綴檢查我的角色表),爲此,你必須只需在您isAuthorized功能的beginin添加這些行:

if (!$this->request->getParam('prefix')) { 
    return true; 
} 

希望它可以幫助

相關問題