Login with username or email with Cakephp 3

aleixfabra picture aleixfabra · Jun 4, 2015 · Viewed 11.6k times · Source

I want to do a login with username or email. So I want to change Auth fields dynamically.

How can I modify $this->Auth fields as Cakehp 2 did?

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']
    ]
]);

Thanks!

Answer

aleixfabra picture aleixfabra · Jun 5, 2015

I've found the solution!

I assumed that username is alphaNumeric (letters and numbers).

Remember to 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 your username and password') ?></legend>
        <?= $this->Form->input('username') ?>
        <?= $this->Form->input('password') ?>
    </fieldset>
<?= $this->Form->button(__('Login')); ?>
<?= $this->Form->end() ?>
</div>