gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 16:52:09 25 4
gpt4 key购买 nike

我想用用户名或电子邮件登录。所以我想动态更改 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com