我正在使用 CakePHP 制作一个系统,其中用户可以是 A、B 或 C。比如学生、教师和其他角色。是否可以让他们都通过 1 个链接登录?所以不是 /students/login 和 /teachers/login,而是像 www.somewebsite/login 这样的东西?
问问题
3614 次
2 回答
4
为不同类型的用户使用不同的控制器根本没有任何意义,你只会重复代码。如果您需要根据角色采取不同的操作,您可以在您的登录方法中执行此操作,方法是在您的 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'
)
);
您还可以查看此用户插件,该插件涵盖了许多常见的用户相关任务。这是一个简单的多角色授权适配器。
于 2013-07-23T11:53:35.800 回答
1
根据用户组的简单基本登录功能如下所示
<?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('/');
}
}
?>
于 2013-07-23T12:29:10.287 回答