使用用户名登录或使用Cakephp 3登录 [英] Login with username or email with Cakephp 3
本文介绍了使用用户名登录或使用Cakephp 3登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用用户名或电子邮件登录.所以我想动态更改Auth字段.
I want to do a login with username or email. So I want to change Auth fields dynamically.
如何像Cakehp 2一样修改$ this-> Auth字段?
How can I modify $this->Auth fields as Cakehp 2 did?
在cakephp 2中,您可以执行以下操作:
In cakephp 2 you could do:
$this->Auth->authenticate = array(
'Form' => array(
'fields' => array('username' => 'email', 'password' => 'password'),
),
);
我试图像这样更改身份验证,但是它不起作用:
I've tried to change authenticate like this but it doesn't work:
$this->Auth->config('authenticate', [
'Form' => [
'fields' => ['username' => 'email', 'password' => 'password']
]
]);
谢谢!
推荐答案
我找到了解决方案!
我假设用户名是字母数字(字母和数字).
I assumed that username is alphaNumeric (letters and numbers).
记住要添加 $ this-> Auth-> constructAuthenticate();
AppController.php
AppController.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'
]
]);
}
}
UsersController.php
UsersController.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'));
}
}
}
login.ctp
login.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>
这篇关于使用用户名登录或使用Cakephp 3登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文