CakePHP 3.5 Auth使用多个表

时间:2018-04-06 13:03:32

标签: cakephp cakephp-3.0

我有一个Auth进程,可以正常使用一个userModel。但不仅仅是因为我的数据库架构,我需要一个登录方法/操作,它适用于多个模型

到目前为止,我已经尝试了我能够想到或在网上找到的所有内容 - 比如在Cake 3中编辑this Cake 1.3 solution以及我能找到的其他一些提示。

然而,我无法弄明白。

感谢您的回答。

我的AppController组件加载:

$this->loadComponent('ExtendedAuth', [
    'authenticate' => [
        'Form' => [
            //'userModel' => 'Admins',
            'fields' => [
                'username' => 'email',
                'password' => 'password'
            ]
        ]
    ],
    'loginAction' => [
        'controller' => 'Admins',
        'action' => 'login'
    ],
    // If unauthorized, return them to page they were just on
    'unauthorizedRedirect' => $this->referer(),
]);

我的ExtendedAuthComponent:

class ExtendedAuthComponent extends AuthComponent
{

    function identify($user = null, $conditions = null) {

        $models = array('Admins', 'Users');

        foreach ($models as $model) {

            //$this->userModel = $model; // switch model
            parent::setConfig('authenticate', [
                AuthComponent::ALL => [
                    'userModel' => $model
                ]
            ]);

            $result = parent::identify(); // let cake do its thing

            if ($result) {
                return $result; // login success
            }
        }
        return null; // login failure
    }
}

EDIT1:情况描述

我有两个单独的表(管理员,用户)。我只需要一个登录操作,尝试在用户之前使用Admins表。由于应用程序逻辑,我不能将它们与“is_admin”标志组合在一个表中。基本上我需要的是代替在Auth config中设置的一个特定userModel,我需要一组模型。听起来很简单,但我无法实现它。

EDIT2:选择解决方案

根据下面的答案,我决定更新我的架构。 Auth users表只是具有登录凭据和角色的简化表,其他角色特定字段则位于单独的表中,这些表用作其他特定于角色的表的连接。尽管答案并不是问题的完全解决方案,但它让我更多地考虑了架构的任何可能的变化,因此我找到了这个解决方案,因此我将其标记为解决方案。我也很感谢所有评论。

1 个答案:

答案 0 :(得分:3)

正如Mark在评论中所说:不要使用两个用户表。如果类似于admin_profiles和user_profiles,则在单独的表中添加类型字段或角色或其他任何关联数据。

不要扩展Auth组件。我不建议再以任何方式使用它,因为它将在即将发布的3.7 / 4.0版本中被弃用。而是Use the new official authenticationauthorization插件。

如果你坚持不懈的道路,并希望让你的生活更加艰难,那就去吧,但是你应该仍然不要扩展auth组件,而是编写自定义身份验证适配器。这是实现自定义2-table-weirdness的正确位置。 Read this section of the manual关于如何做到这一点。