如何验证用户名和密码以外的其他字段?

时间:2016-08-08 21:12:22

标签: cakephp cakephp-3.0

在我的登录页面上,有三个字段:角色,用户名和密码。角色是一个选择选项,您可以选择客户或承包商。

在我的数据库中有一个用户是客户。

说,用户想登录,但他不小心选择了承包商。他按下了登录按钮,但由于他不是承包商,所以不会让他离开。

你怎么能做到这一点?我试过这个:

public function initialize()
{
    $this->loadComponent('Flash');
    $this->loadComponent('Auth', [
        'loginRedirect' => [
            'controller' => 'Articles',
            'action' => 'index'
        ],
        'logoutRedirect' => [
            'controller' => 'Pages',
            'action' => 'display',
            'home'
        ],
        'authenticate' => [
            'Form' => [
                'fields' => ['role' => 'role', 'username' => 'username', 'password' => 'password']
            ]
        ]
    ]);
}

但它没有用。

这是我的观点:

<?= $this->Flash->render() ?>
<?= $this->Form->create('User', array('class' => 'login-form')) ?>
<div class="form-group">
<?php
    $array = array('client' => 'Client', 'contractor' => 'Contractor');
    echo $this->Form->input(
        'role',
        array('label' => false, 'options' => $array, 'default' => 'client')
    );

?>

</div>
<div class="form-group">
    <?= $this->Form->input('username', array( 'label' => false, 'placeholder' => 'Username...' )) ?>
</div>
<div class="form-group">
    <?= $this->Form->input('password', array( 'label' => false, 'placeholder' => 'Password...' )) ?>    
</div>
<?= $this->Form->button(__('Sign in!')); ?>
<?= $this->Form->end() ?>

这是我的控制者:

  if ($this->request->is('post')) {
        $user = $this->Auth->identify();
        if ($user) {
            $this->Auth->setUser($user); // hydration
            return $this->redirect($this->Auth->redirectUrl());
        }
                                    // use the layout/login.ctp layout
        $this->Flash->error(__('Invalid username or password, try again'));
    }

    // use the login layout
    $this->viewBuilder()->layout("login");

1 个答案:

答案 0 :(得分:0)

您想仔细阅读this section of the manual,直到最后。

你所做的事情是行不通的,因为:

  

fields用于识别用户的字段。您可以使用密钥用户名和密码分别指定用户名和密码字段。

接下来几行

  

自3.1起已弃用userFields选项。在自定义查找程序中使用select()。

哪个应该带您到: Customising Find Query

所以只需实现一个自定义查找程序并告诉表单身份验证适配器使用它:

public function initialize()
{
    parent::initialize();
    $this->loadComponent('Auth', [
        'authenticate' => [
            'Form' => [
                'finder' => 'auth'
            ]
        ],
    ]);
}