配置cakephp的Auth-Component时,我在使用'contains'-index (described here)时遇到问题......
我想要实现的是基于权限的授权(而不是'admin','user'等角色)。 所以,留在经常使用的博客示例中,我有一个表'权限',可能有字段ID和名称,并包含条目:
1: editOwnPosts
2: editAllPosts
这些权利与用户相关联,如下所示:
/*
* Model/User.php:
*/
public $hasAndBelongsToMany = array(
'Right' => array(
'className' => 'Right',
'joinTable' => 'rights_users',
'foreignKey' => 'user_id',
'associationForeignKey' => 'right_id',
)
);
/*
* Model/Right.php:
*/
public $hasAndBelongsToMany = array(
'User' => array(
'className' => 'User',
'joinTable' => 'rights_users',
'foreignKey' => 'right_id',
'associationForeignKey' => 'user_id',
)
);
现在,对于每个授权,我都需要用户的权利。因此,例如,如果他尝试编辑帖子,我会检查用户的权限数组是否包含值'editAllPost'。如果是,我的授权函数返回true。否则检查,如果它包含“editOwnPosts”,如果Post是用户'则返回true,否则返回false。
好吧,我在this question的答案中找到了我认为可以解决的问题:使用cakephp 2.2中引入的'contains'-Key。所以我在AppController.php中写道:
public $components = array(
'Auth' => array(
...,
'authenticate' => array(
'Form' => array(
'userModel' => 'User',
'fields' => array('username' => 'mail'),
'contain' => array('Right')
),
),
'authorize' => array('Controller')
);
并且测试它是否正在做我想要的,也在AppController.php中:
public function isAuthorized($user) {
var_dump($this->Auth->user());
return true;
}
但是我在任何页面上看到的var_dump只包含来自用户模型本身的直接数据,而不是相关的权利。
我只是犯了一个小错误,或者我的'包含'指数的目的/功能完全错了吗?
答案 0 :(得分:0)
您是否为clean model cache设置了debug = 2?
答案 1 :(得分:0)
我今天遇到了同样的问题。这是因为经过身份验证的用户存储在会话中。当您登录我们的用户时,他/她的信息将存储在会话中。
因此,如果您要向用户添加其他包含,则必须确保从应用中注销所有用户。再次登录后,新的包含模型关联可通过$ this-> Auth-> user(' ContainModel.fieldname')获得。