cakephp - 使用 CakePHP 检查登录时的用户角色?

标签 cakephp cakephp-2.2

我想为我的网站创建一个管理面板,为此我创建了 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/

相关文章:

postgresql - 带有 PostgreSQL 的 CakePHP 2.2 新行插入失败 - 数据库错误 : Undefined table: 7 ERROR: relation "table_id_seq" does not exist

php - 如何从 CakePHP 2.2 Controller 返回 JSON?

cakephp - WKHTMLTOPDF 内部错误

CakePHP 全局 slug 路由器

CakePHP 2.2 saveAll 多模型验证

php - CakePHP 2.x - 每个项目的虚拟字段最大值

php - 我如何在cakephp中使用插件主题来显示错误消息?

php - SQLSTATE[HY000] [1045] 使用 CakePHP 拒绝用户 'username' @'localhost' 的访问

php - 日志中有很多Cakephp警告

php - cakePHP 3.0 HABTM关系保存数据