我正在使用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