今天遇到了权限控制的问题,后台不同级别的用户登录后看到的内容是不一样的。网上查了下,说Yii中有自带的RBAC权限控制,大概看了下,没理解太明白。然后就是采用filter进行过滤验证,看着这个还不错。下面简单说下我是我怎么用的,不对的地方希望大神们给予指教。

1.在cp_user表里增加了一个level字段,代表用户的级别,1代表管理员admin,2代表普通用户common_user

2.在components的UserIdentity.php里添加用户角色

class UserIdentity extends CUserIdentity
{
    /**
     * Authenticates a user.
     * The example implementation makes sure if the username and password
     * are both 'demo'.
     * In practical applications, this should be changed to authenticate
     * against some persistent user identity storage (e.g. database).
     * @return boolean whether authentication succeeds.
     */
    public function authenticate()
    {
        $username=strtolower($this->username);
        $user=User::model()->find('LOWER(username)=?',array($username));
        if($user===null)
            $this->errorCode=self::ERROR_USERNAME_INVALID;
        else if($user->password!=$this->password)
            $this->errorCode=self::ERROR_PASSWORD_INVALID;
        else
        {
            $this->username=$user->username;
                         $this->setState('roles', $user->level==1?'admin':'commen_user');   //添加用户角色
            $this->errorCode=self::ERROR_NONE;
        }
                                                                                                                                                                                    
        return $this->errorCode==self::ERROR_NONE;
    }
                                                                                                                                                                         
}

上面这句$this->setState('roles',$user->level==1?'admin':'commen_user')非常重要,这里表示添加了一个用户的角色

3.重写CWebUser,放在components文件夹下(WebUser.php)

class WebUser extends CWebUser
{
 /**
 * Overrides a Yii method that is used for roles in controllers (accessRules).
 *
 * @param string $operation Name of the operation required (here, a role).
 * @param mixed $params (opt) Parameters for this operation, usually the object to access.
 * @return bool Permission granted?
 */
 public function checkAccess($operation, $params=array())
 {
        if (empty($this->id)) {
        // Not identified => no rights
        return false;
        }
        $role = $this->getState("roles");
        if ($role ==='admin') { //管理员
        return true; // admin role has access to everything
        }
        // allow access if the operation request is the current user's role
        return ($operation === $role);
        }
}

4.控制器里修改

public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete', // we only allow deletion via POST request
        );
    }
    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array('allow',  // allow all users to perform 'index' and 'view' actions
                'actions'=>array('index','view','login','passwordupdate'),
                'users'=>array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions'=>array('create','update','getuser','delete'),
                 'roles'=>array('admin'),//表示只有角色为admin的用户才能访问
            ),
            array('deny',  // deny all users
                'users'=>array('*'),
            ),
        );
    }

5.修改配置文件main.php

'user'=>array(
            // enable cookie-based authentication
                        'class'=>'WebUser',
            'allowAutoLogin'=>true,
            'loginUrl' => array('/user/login'),
        ),

6.视图中如何用?

array('name'=>'status', 'type'=>'html', 'value'=>'Customer::showStatus($data->status, $data->id)','visible'=>  Yii::app()->user->checkAccess('admin')),
                                                        array('name'=>'employee_id', 'type'=>'html', 'value'=>'Customer::isDivided($data->employee_id, $data->id)','visible'=> Yii::app()->user->checkAccess('admin')),

原理:当用户登录的时候,获取用户的level字段,并添加相应的角色,若是1则该用户为admin,否则就是common_user.然后重写CWebUser中的checkAccess方法,如果是admin,则有权操作相应的权限。最后在控制器里rules里定义规则,有一个roles属性,我们给它设置为admin,表示只有角色为admin的才能进行相关的action操作。