2012-04-05 15 views
2

在我的Cake應用程序中,我正在進行基本身份驗證。我寧願保持簡單和語義(不喜歡ACL),所以我只是簡單地檢查用戶的角色,並相應地允許或拒絕。現在CakePHP:Auth錯誤,即使允許執行動作

,授權預期的所有功能,但我發現了一個奇怪的問題,無論用戶是否嘗試允許的動作或者不要在那裏驗證錯誤消息顯示。它們在註銷後仍然可見。

這裏的AppController中:

public $components = array(
    'Session', 
    'Password', 
    'Auth' => array(
     'loginRedirect' => array('controller' => 'users', 'action' => 'index'), 
     'logoutRedirect' => array('controller' => 'pages', 'action' => 'display', 'home'), 
     'authError' => "Sorry, you're not allowed to do that.", 
     'authorize' => array('Controller') 
    ), 
    'RequestHandler' 
); 

public function beforeFilter() { 
    $this->set('loggedIn', $this->Auth->loggedIn()); 
    $this->set('current_user', $this->Auth->user()); 
    $this->set('admin', $this->_isAdmin()); 
    $this->set('coach', $this->_isCoach()); 
    $this->Auth->allow('login', 'logout', 'display'); 
} 

public function isAuthorized($user) { 
    if (isset($user['role']) && $user['role'] === 'admin') { 
     return true; 
    } 
    return false; 
} 

的beforeFilter並從另一個控制器isAuthorized:

public function beforeFilter() { 
    parent::beforeFilter(); 
} 

public function isAuthorized($user) { 
    if ($user['role'] === 'coach') { 
     if ($this->action === 'index') { 
      return true; 
     } 
     if (in_array($this->action, array('view', 'edit', 'delete'))) { 
      $id = $this->request->params['pass'][0]; 
      $this->User->id = $id; 
      if ($this->User->field('client_id') === $user['client_id']) 
       return true; 
      } else { 
       return false; 
      } 
     } 
     return false; 
    } 
    return parent::isAuthorized($user); 
} 

回答

1

我決定做這在我的用戶控制,而是和一切似乎運作良好,加它更清潔/更具可讀性:

public function isAuthorized($user = null) { 
    switch($this->action) { 
     case "index": 
     case "add": 
      if ($user['role'] == 'coach') { 
       return true; 
      } 
      break; 

     case "view": 
     case "edit": 
     case "delete": 
      $id = $this->request->params['pass'][0]; 
      $this->User->id = $id; 
      if ($user['role'] == 'coach' && $this->User->field('client_id') == $user['client_id']) { 
       return true; 
      } 
      break; 
    } 
    return parent::isAuthorized($user); 
} 
相關問題