email - 使用 Cakephp 3 使用用户名或电子邮件登录

标签 email authentication cakephp-3.0

我想用用户名或电子邮件登录。所以我想动态更改 Auth 字段。

如何像 Cakehp 2 那样修改 $this->Auth 字段?

在 cakephp 2 你可以这样做:

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

我试图像这样更改身份验证,但它不起作用:

$this->Auth->config('authenticate', [
    'Form' => [
        'fields' => ['username' => 'email', 'password' => 'password']
    ]
]);

谢谢!

最佳答案

我找到了解决方案!

我假设用户名是 alphaNumeric(字母和数字)。

记得加$this->Auth->constructAuthenticate();
应用 Controller .php

use Cake\Controller\Controller;
use Cake\Event\Event;
use Cake\Core\Configure;

class AppController extends Controller
{
    public function initialize()
    {
        parent::initialize();
        $this->loadComponent('Flash');
        $this->loadComponent('Auth', [
            'loginRedirect' => [
                'controller' => 'Users',
                'action'     => 'index'
            ],
            'logoutRedirect' => [
                'controller' => 'Users',
                'action'     => 'login'
            ]
        ]);
    }
}

用户 Controller .php

use App\Controller\AppController;
use Cake\Validation\Validation;

class UsersController extends AppController
{
    public function login()
    {
        if ($this->request->is('post')) {

            if (Validation::email($this->request->data['username'])) {
                $this->Auth->config('authenticate', [
                    'Form' => [
                        'fields' => ['username' => 'email']
                    ]
                ]);
                $this->Auth->constructAuthenticate();
                $this->request->data['email'] = $this->request->data['username'];
                unset($this->request->data['username']);
            }

            $user = $this->Auth->identify();

            if ($user) {
                $this->Auth->setUser($user);
                return $this->redirect($this->Auth->redirectUrl());
            }

            $this->Flash->error(__('Invalid username or password, try again'));
        }
    }
}

登录.ctp

<div class="form">
<?= $this->Flash->render('auth') ?>
<?= $this->Form->create() ?>
    <fieldset>
        <legend><?= __('Please enter your username and password') ?></legend>
        <?= $this->Form->input('username') ?>
        <?= $this->Form->input('password') ?>
    </fieldset>
<?= $this->Form->button(__('Login')); ?>
<?= $this->Form->end() ?>
</div>

关于email - 使用 Cakephp 3 使用用户名或电子邮件登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30648852/

相关文章:

javascript - 使用 :roles 在 meteor-app 中构建角色管理

cakephp - 在 CakePHP 3 中即时更改缓存配置

CakePHP 3.x 中的 MongoDB 配置

PostgreSQL 多种认证方式

node.js - 如何使用 Passport.js 返回到当前哈希位置?

postgresql - bugzilla 无法连接到 postgres 服务器

java - 将 Spinners 的文本发送到邮件

cakephp - 列出 Cakephp 3 中的所有 Controller / Action

c# - 发送匿名邮件 C#

email - Postfix 不会发送电子邮件