我正在使用CakePHP 2.3.6。在一個項目中,我有兩種類型的用戶:Students
和Admin
。所以,我爲兩種類型的用戶創建了2 Controllers
,即StudentsController
和AdminsController
。我爲這兩個控制器配置了不同的Authentication
配置,所以我在2個控制器中分別配置了AuthComponent
。我想爲兩種用戶提供一個通用的login()
函數實現,這樣我就不必再編寫兩次相同的代碼。Cakephp - 2個不同用戶的用戶管理系統
這裏是我的代碼:
AppController.php:
public $components=array('Session','RequestHandler','Acl','Auth'=>array('authorize'=>array('Actions'=>array('actionPath'=>'controllers'))));
StudentsController.php:
public function beforeFilter(){
parent::beforeFilter();
$this->Auth->loginRedirect=array('controller'=>'students','action'=>'editProfile');
$this->Auth->logoutRedirect=array('controller'=>'students','action'=>'index');
$this->Auth->authenticate=array('Form'=>array('scope'=>array('User.group_id'=>2),'userModel'=>'User','fields'=>array('username'=>'username','password'=>'password')));
$this->Auth->unauthorizedRedirect=array('controller'=>'users','action'=>'login');
$this->Auth->loginAction=array('controller'=>'users','action'=>'login');
$this->Auth->allow('login','index','createProfile');
$this->layout='student_layout';
}
AdminsController.php:
public function beforeFilter(){
parent::beforeFilter();
$this->Auth->loginRedirect=array('controller'=>'admins','action'=>'myJobs');
$this->Auth->logoutRedirect=array('controller'=>'admins','action'=>'index');
$this->Auth->authenticate=array('Form'=>array('scope'=>array('User.group_id'=>1),'userModel'=>'User','fields'=>array('username'=>'username','password'=>'password')));
$this->Auth->authError='Did you really think you are allowed to see that ?';
$this->Auth->unauthorizedRedirect=array('controller'=>'admin','action'=>'index');
$this->Auth->loginAction=array('controller'=>'users','action'=>'login');
$this->Auth->allow('index');
$this->layout='admin_layout';
}
UsersController.php:
public function login(){
if($this->request->is('post'))
if($this->Auth->login()){
$welcome=($this->Auth->user('group_id')==2)?'Welcome '.$this->Student->field('name',array('Student.id'=>$this->Auth->user('id'))):(($this->Auth->user('group_id')==1)?"<p style='margin-left:20px;color:#366;'><strong>Welcome Admin, You have successfully entered to your Admin Panel!</strong></p>":"");
$this->Session->setFlash($welcome);
return $this->redirect($this->Auth->redirect());
}else{
$this->Session->setFlash('Invalid username or password, please try again');
$this->set('title_for_layout','Error - Login');
}
}
所以,我想這login
將在users/login
進行處理,爲用戶的。我知道,我的代碼有點複雜。實際上,我的AdminsController
的index
頁面包含login form
,它提交給users/login
。
我的意思是,login
邏輯應該在users/login
處理,但login page(login form)
可以爲用戶的不同,唯一重要的是,那些forms
應該向users/login
。
現在,有了這些配置,Students
着訪問editProfile
,並在Admin Panel
Admins
着訪問anything
。
我認爲我的問題是成功登錄後redirecting
。這就是爲什麼我在登錄功能$this->redirect($this->Auth->redirect())
之前使用return
。
那麼,問題在哪裏?我該怎麼辦 ?
請幫幫我。
謝謝。
看起來很有用,但不幸的是我仍然面臨這個問題。其實,我認爲我的問題是在正確的地方'配置''AuthComponent'。但是,還是非常感謝。你有其他想法嗎?@Prakash Saini – 2014-10-04 12:24:07