[英]Logging in using different user roles in CakePHP?
我正在使用CakePHP开发一个系统,其中用户可以是A,B或C。例如学生,老师和其他一些角色。 是否可以让他们全部通过1个链接登录? 所以不是/ students / login和/ teachers / login,而是像www.somewebsite / login这样的所有人?
对于不同类型的用户使用不同的控制器根本没有任何意义,您只需要复制代码即可。 如果您需要根据角色采取不同的操作,则可以在login方法中执行此操作,方法是从login()方法中调用afterStudentLogin()之类的其他方法,然后在其中执行特定于角色的操作。 这样做的原因是,单个方法始终应该只执行一项任务,因此您可以在单独的方法中将特定于角色的代码与其分离。
public function login() {
if ($this->Auth->user()) {
/* ... */
$callback = 'after' . $this->Auth->user('role') . 'Login');
$this->{$callback}($this->Auth->user());
/* ... */
}
}
即使用户类型非常不同,他们也将共享一个共同的事物:登录。 在这种情况下,有一个用户表,例如有student_profils
表和teacher_profiles
表。 如果差异只是几个字段,我会将它们全部放在一个表格(如profiles
。
如果要使用/ login而不是/ users / login,则应使用routing 。
Router::connect(
'/login',
array(
'controller' => 'users',
'action' => 'login'
)
);
您也可以查看此Users插件 ,其中涵盖了许多与用户相关的常见任务。 这是一个简单的多角色授权适配器 。
一个简单的基本登录功能取决于用户组,如下所示
<?php
public function login() {
//if user already logged in call routing function...
if($this->Session->read('Auth.User')) {
$this->routing();
}
if ($this->request->is('post')) {
if ($this->Auth->login()) {
//if user status is active...
if ($this->Auth->user('status') == 1){
//redirect users based on his group id...
if($this->Auth->User('group_id')==1){
$this->redirect($this->Auth->redirect('/admins/dashboard'));
}
else if($this->Auth->User('group_id')==2){
$this->redirect($this->Auth->redirect('/teachers/dashboard'));
}
else if($this->Auth->User('group_id')==3){
$this->redirect($this->Auth->redirect('/students/dashboard'));
}
}
else{
$this->Session->delete('User');
$this->Session->destroy();
$this->Session->setFlash('Your account is not yet activated. Please activate your account to login.', 'warning');
}
}
else {
$this->Session->setFlash('Your username or password was incorrect.', 'error');
}
}
}
//just route the loggedin users to his proper channel...
public function routing() {
if($this->Session->read('Auth.User.Group.id') == 1) {
$this->redirect('/admins/dashboard');
}
else if($this->Session->read('Auth.User.Group.id') == 2) {
$this->redirect('/teachers/dashboard');
}
else if($this->Session->read('Auth.User.Group.id') == 3) {
$this->redirect('/students/dashboard');
}
else {
$this->Session->destroy();
$this->redirect('/');
}
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.