我想为我的网站创建一个管理面板,为此我创建了 admin.ctp
。在数据库表名称 user 中包含列 role
,其中 role=admin/regular(user)。
只有一个登录表单,问题是,是否可以进行“检查”,如果user.role=admin
则重定向到admin/user/dashboard
如果user.role=regular
那么layout=default
?我的 AppController.php 包含:
function beforeFilter(){
$this->Auth->allow('index','view','login','home');
$this->set('admin',$this->_isAdmin());
$this->set('logged_in',$this->Auth->loggedIn());
$this->set('current_user',$this->Auth->User());
if ((isset($this->params['prefix']) && ($this->params['prefix'] == 'admin'))) {
$this->layout = 'admin';
}
和usersController.php
function beforeFilter(){
parent::beforeFilter();
$this->Auth->allow('*');
if($this->action=='add' || $this->action=='edit'){
$this->Auth->authenticate=$this->User;
}
}
function login(){
if(!($this->Auth->loggedIn())){
if ($this->request->is('post')) {
if ($this->Auth->login()) {
if($user['role'] === 'admin'){
$this->redirect($this->Auth->redirect('admin',array('controller' => 'user','action' => 'admin_dashboard')));
}
$this->redirect($this->Auth->redirect(array('controller' => 'posts','action' => 'index')));
} else {
$this->Session->setFlash('Your username/password combination was incorrect.',
'alert',array(
'plugin' => 'TwitterBootstrap',
'class' => 'alert-error'
));
$this->set('forget', 'Forgot Your Password');
}
}
}else
{
$this->redirect($this->Auth->redirect(array('controller' => 'posts','action' => 'index')));
}
}
使用cakephp 2.2.3。 提前致谢!
最佳答案
这就是我的做法(请记住根据您的组模型相应地更改field('name')
)。
if ($this->Auth->login())
{
this->User->Group->id = $this->Auth->user('group_id');
switch ($this->User->Group->field('name'))
{
case 'admin':
$this->redirect($this->Auth->redirect('admin',array('controller' => 'user','action' => 'admin_dashboard')));
break;
case 'regular':
$this->redirect($this->Auth->redirect(array('controller' => 'posts','action' => 'index')));
break;
default:
//...
break;
}
}
关于cakephp - 使用 CakePHP 检查登录时的用户角色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14407049/