2

我的 Users 表有一大堆字段,其中大部分我不需要/不想存储在 Auth User 会话中。您如何限制登录用户的会话中存储哪些字段?

我知道您可以使用“包含”键选择关联模型的字段,但通常要选择顶级模型的字段,您会使用“字段”键。但在 Auth 的情况下,'fields' 键用于选择通过哪些字段对用户进行身份验证,而不是在会话中包含哪些字段。

为了给出一些上下文,这是我到目前为止的代码......我会怎么做才能使只有电子邮件和名字字段存储在身份验证会话中,而不是用户表中的所有字段。

$this->Auth->authenticate = array(
    'Blowfish' => array(
        'fields' => array(
            'username' => 'email',
            'password' => 'password',
        )
    )
);
4

3 回答 3

2

我赞成有用的答案,尽管是解决方案 - 谢谢。

我认为“正确”的答案是开箱即用的 CakePHP Auth 组件无法做到这一点,您必须破解它(例如,使用以下解决方案之一)。我查看了_findUserBaseAuthenticate.php 中的方法,它证实了这一点。

如果 CakePHP 核心开发人员正在阅读(DeEuroMarK?),这可能是一个很常见的要求,我认为这是一个值得内置的功能。

建议的实现:只需将您想要的字段作为额外字段包含在“字段”数组中 - 并假设除“用户名”和“密码”之外的每个键都是应包含在身份验证会话中的额外字段。这样它与其他模型查找语法一致。

例子:

$this->Auth->authenticate = array(
    'Blowfish' => array(
        'fields' => array(
            'username' => 'email',
            'password' => 'password',
            'another_field',
            'yet_another_field'
        )
    )
);
于 2013-06-25T07:18:05.327 回答
1

在我的 UsersController 的 beforeFilter 中,我有一些类似于您的登录名的内容。

然后我将 afterLogin 函数设置为重定向

 $this->Auth->loginRedirect = array('controller' => 'users', 'action' => 'afterLogin');
 $this->Auth->loginRedirectTrue = array('controller' => 'users', 'action' => 'index');
 $this->Auth->logoutRedirect = array('controller' => 'pages', 'action' => 'display');

登录功能进行一些检查,然后重定向到

if ($this->Auth->login()){
    // code here
    $this->redirect($this->Auth->redirect());
}

和 afterLogin 这样的功能

 function afterLogin(){
    $session = $this->Session->read('Auth');
    $user_id = $session['User']['id'];

    // change this to find only the fields you need and then override the Auth.User...
    $user = $this->User->findById($user_id);
    if (!empty($user)){
        $this->Session->write('Auth.UserProfile', $user['UserProfile']);
    }
    $this->redirect($this->Auth->loginRedirectTrue);
 }

您应该更改 findById 以满足您的需要,然后覆盖会话中的 Auth.User 字段。

祝你好运!

于 2013-06-24T14:17:38.837 回答
0

我认为最简单的方法是添加如下内容:

将包含添加到您的 Auth-Component 配置

$this->loadComponent('Auth', [
        'authorize' => 'Controller',
        'loginRedirect' => [
            'controller' => 'Users',
            'action' => 'index'
        ],
        'logoutRedirect' => [
            'controller' => 'Users',
            'action' => 'login'
        ],
        'authenticate' => [
            'Form' => [
                'fields' => ['username' => 'email'],
                'contain' => ['Groups']
            ]
        ],
        'unauthorizedRedirect' => $this->referer()
    ]);
...

并在您的登录操作中将用户保存在会话中:

$foundUser = $this->Auth->identify();
if ($foundUser) {
    $this->Auth->setUser($foundUser);
}
...

这会将包含的组添加到 Auth.User

适用于 CakePhp3 - 在旧版本中可能会有所不同。

于 2015-05-05T08:25:22.340 回答