【问题标题】:cakephp Auth - can't get data from associated table via 'contain'cakephp Auth - 无法通过“包含”从关联表中获取数据
【发布时间】:2013-09-09 08:23:34
【问题描述】:

在配置 cakephp 的 Auth-Component 时,我在使用 'contain'-index (described here)...时遇到问题...

我想要实现的是基于权限的授权(而不是像“管理员”、“用户”等角色)。 因此,在常用的博客示例中,我有一个表“权限”,其中可能包含字段 id 和 name 并包含条目:

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 中引入的“包含”-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 只包含来自用户模型本身的直接数据,而不是相关的权限。

我只是犯了一个小错误,还是我完全错误地理解了“包含”索引的目的/功能?

【问题讨论】:

    标签: php cakephp authentication authorization


    【解决方案1】:

    您是否为清理模型缓存设置了 debug =2?

    【讨论】:

    • 是的,已经设置好了。现在它起作用了,我认为问题是,我还没有将可包含行为添加到模型中......但是,我遇到了相反的问题,包含获取太多......但我会为此发布另一个问题...
    【解决方案2】:

    我今天也遇到了同样的问题。这是因为经过身份验证的用户存储在会话中。当您登录我们的用户时,他/她的信息将存储在会话中。

    因此,如果您想为您的用户添加额外的内容,您必须确保从您的应用中注销所有用户。再次登录后,新的包含模型关联可通过 $this->Auth->user('ContainModel.fieldname') 获得。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多