Yii框架RBAC模型,试图理解

时间:2014-04-23 06:14:49

标签: php yii rbac

在accessRules中,无论如何我添加了某个角色允许的所有操作,如下面的

    array('allow',
        'actions'=>array(‘create’,'view’),
        'roles'=>array('role1'),

我为什么要创建操作?创建如下所示的单独操作有什么好处?我知道如果我创建操作我可以使用checkAccess方法,但在accessRules中我列出了允许某个角色执行的所有操作,所以我不必向该角色添加操作吗?

_authManager->createOperation("createPost ", "create a new post");
_authManager->createOperation("readPost ", "read post");
$role = $this->_authManager->createRole("role1");
$role->addChild("createPost");
$role->addChild("readPost");

我检查过,如果我允许删除和管理员的role1操作,即使我没有将该操作添加到role1,也允许执行这些操作。

    array('allow',
        'actions'=>array(‘admin’,'delete’),
        'roles'=>array('role1'),

那么,当不强制执行限制时,向角色添加操作有什么好处?

1 个答案:

答案 0 :(得分:2)

您需要添加到UserIdentity setRole方法

class UserIdentity extends CUserIdentity
{
    private $id;

    public function authenticate()
    {
        $record=User::model()->findByAttributes(array('email'=>$this->username));
        if($record===null)
            $this->errorCode=self::ERROR_USERNAME_INVALID;
        else if($record->password!==md5($this->password))
            $this->errorCode=self::ERROR_PASSWORD_INVALID;
        else
        {
            $this->id=$record->id;
            $this->setState('roles', $record->roles);            
            $this->errorCode=self::ERROR_NONE;
        }
        return !$this->errorCode;
    }

    public function getId(){
        return $this->id;
    }
}

WebUser组件

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);
    }
}

检查full description there