authentication - Login with username or email with Cakephp 3 -
i want login username or email. want change auth fields dynamically.
how can modify $this->auth fields cakehp 2 did?
in cakephp 2 do:
$this->auth->authenticate = array( 'form' => array( 'fields' => array('username' => 'email', 'password' => 'password'), ), );
i've tried change authenticate doesn't work:
$this->auth->config('authenticate', [ 'form' => [ 'fields' => ['username' => 'email', 'password' => 'password'] ] ]);
thanks!
i've found solution!
i assumed username alphanumeric (letters , numbers).
remember add $this->auth->constructauthenticate();
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
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
<div class="form"> <?= $this->flash->render('auth') ?> <?= $this->form->create() ?> <fieldset> <legend><?= __('please enter username , password') ?></legend> <?= $this->form->input('username') ?> <?= $this->form->input('password') ?> </fieldset> <?= $this->form->button(__('login')); ?> <?= $this->form->end() ?> </div>
Comments
Post a Comment