我想使用用户名或电子邮件登录。所以我想动态更改 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']
]
]);
Thanks!
我找到了解决方案!
我假设用户名是字母数字(字母和数字)。
记得添加$this->Auth->constructAuthenticate();
应用程序控制器.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'
]
]);
}
}
用户控制器.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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)