CakePHP DC Users 8.5.1 customising to use email

111 views Asked by At

I have a CakePHP application running on Cake PHP 3.8.13 and CakeDC Users 8.5.1.

I am currently able to log on using the username field, but I would like to use the email field for authentication. I have followed the instructions on https://github.com/CakeDC/users/blob/master/Docs/Documentation/Configuration.md#using-the-users-email-to-login but the system is still trying to use the username field. If I change email to username in the src/Template/Plugin/CakeDC/Users/Users/login.ctp I can log in using the username.

How can I get it to use the email field instead?

src/Application.php

<?php

namespace App;

use Cake\Core\Configure;
use Cake\Core\Exception\MissingPluginException;
use Cake\Error\Middleware\ErrorHandlerMiddleware;
use Cake\Http\BaseApplication;
use Cake\Http\Middleware\SecurityHeadersMiddleware;
use Cake\Routing\Middleware\AssetMiddleware;
use Cake\Routing\Middleware\RoutingMiddleware;
use Cake\Http\Middleware\EncryptedCookieMiddleware;

class Application extends BaseApplication
{
    /**
     * {@inheritDoc}
     */
    public function bootstrap()
    {
        // Call parent to load bootstrap from files.
        parent::bootstrap();
        $this->addPlugin('AuditStash');

        if (PHP_SAPI === 'cli') {
            try {
                $this->addPlugin('Bake');
            } catch (MissingPluginException $e) {
                // Do not halt if the plugin is missing
            }
            $this->addPlugin('Migrations');
        }

        /*
         * Only try to load DebugKit in development mode
         * Debug Kit should not be installed on a production system
         */
        if (Configure::read('debug')) {
            $this->addPlugin(\DebugKit\Plugin::class);
        }
        $this->addPlugin(\CakeDC\Users\Plugin::class);
        Configure::write('Users.config', ['users']);
        $identifiers = Configure::read('Auth.Identifiers');
        $identifiers['Authentication.Password']['fields']['username'] = 'email';
        Configure::write('Auth.Identifiers', $identifiers);
    }

    /**
     * Setup the middleware queue your application will use.
     *
     * @param \Cake\Http\MiddlewareQueue $middlewareQueue The middleware queue to setup.
     * @return \Cake\Http\MiddlewareQueue The updated middleware queue.
     */
    public function middleware($middlewareQueue)
    {
        $securityHeaders = new SecurityHeadersMiddleware();
        $securityHeaders
            ->setCrossDomainPolicy()
            ->setReferrerPolicy()
            ->setXFrameOptions()
            ->setXssProtection()
            ->noOpen()
            ->noSniff();

        $middlewareQueue
            // Add security headers
            ->add($securityHeaders)

            // Catch any exceptions in the lower layers,
            // and make an error page/response
            ->add(ErrorHandlerMiddleware::class)

            // Handle plugin/theme assets like CakePHP normally does.
            ->add(new AssetMiddleware([
                'cacheTime' => Configure::read('Asset.cacheTime')
            ]))

            // Add routing middleware.
            // Routes collection cache enabled by default, to disable route caching
            // pass null as cacheConfig, example: `new RoutingMiddleware($this)`
            // you might want to disable this cache in case your routing is extremely simple
            ->add(new RoutingMiddleware($this, '_cake_routes_'));

        $cookies = new EncryptedCookieMiddleware(
        // Names of cookies to protect
            ['remember_me', 'csrfToken'],
            Configure::read('Security.cookieKey')
        );

        $middlewareQueue->add($cookies);
        return $middlewareQueue;
    }
}

src/config/users.php

<?php
return [
    // Table used to manage users
    'table' => 'Users',
    // Controller used to manage users plugin features & actions
    'controller' => 'Users',
    // configure Auth component
    'auth' => true,
    // Password Hasher
    'passwordHasher' => '\Cake\Auth\DefaultPasswordHasher',
    // token expiration, 1 hour
    'Token' => ['expiration' => 3600],
    'Email' => [
        // determines if the user should include email
        'required' => true,
        // determines if registration workflow includes email validation
        'validate' => true,
    ],
    'Registration' => [
        // determines if the register is enabled
        'active' => false,
        // determines if the reCaptcha is enabled for registration
        'reCaptcha' => true,
        // allow a logged in user to access the registration form
        'allowLoggedIn' => false,
        //ensure user is active (confirmed email) to reset his password
        'ensureActive' => false,
        // default role name used in registration
        'defaultRole' => 'user',
    ],
    'reCaptcha' => [
        // reCaptcha key goes here
        'key' => null,
        // reCaptcha secret
        'secret' => null,
        // use reCaptcha in registration
        'registration' => false,
        // use reCaptcha in login, valid values are false, true
        'login' => false,
    ],
    'Tos' => [
        // determines if the user should include tos accepted
        'required' => true,
    ],
    'Social' => [
        // enable social login
        'login' => false,
        // enable social login
        'authenticator' => 'CakeDC/Users.Social',
    ],
    'GoogleAuthenticator' => [
        // enable Google Authenticator
        'login' => false,
        'issuer' => null,
        // The number of digits the resulting codes will be
        'digits' => 6,
        // The number of seconds a code will be valid
        'period' => 30,
        // The algorithm used
        'algorithm' => 'sha1',
        // QR-code provider (more on this later)
        'qrcodeprovider' => null,
        // Random Number Generator provider (more on this later)
        'rngprovider' => null
    ],
    'Profile' => [
        // Allow view other users profiles
        'viewOthers' => false,
        'route' => ['plugin' => 'CakeDC/Users', 'controller' => '\Users', 'action' => 'profile'],
    ],
    'Key' => [
        'Session' => [
            // session key to store the social auth data
            'social' => 'Users.social',
            // userId key used in reset password workflow
            'resetPasswordUserId' => 'Users.resetPasswordUserId',
        ],
        // form key to store the social auth data
        'Form' => [
            'social' => 'social'
        ],
        'Data' => [
            // data key to store the users email
            'email' => 'email',
            // data key to store email coming from social networks
            'socialEmail' => 'info.email',
            // data key to check if the remember me option is enabled
            'rememberMe' => 'remember_me',
        ],
    ],
    // Avatar placeholder
    'Avatar' => ['placeholder' => 'CakeDC/Users.avatar_placeholder.png'],
    'RememberMe' => [
        // configure Remember Me component
        'active' => false,
        'checked' => true,
        'Cookie' => [
            'name' => 'remember_me',
            'Config' => [
                'expires' => '1 month',
                'httpOnly' => true,
            ]
        ]
    ],
];

src/Template/Plugin/CakeDC/Users/Users/login.ctp

<?php
use Cake\Core\Configure;
?>
<div class="users form">
    <?= $this->Flash->render('auth') ?>
    <?= $this->Form->create() ?>
    <fieldset>
        <legend><?= __d('CakeDC/Users', 'Please enter your username and password') ?></legend>
        <?= $this->Form->control('email', ['required' => true]) ?>
        <?= $this->Form->control('password', ['required' => true]) ?>
    </fieldset>
    <?= $this->Form->button(__d('CakeDC/Users', 'Login')); ?>
    <?= $this->Form->end() ?>
</div>

1

There are 1 answers

0
steinkel On BEST ANSWER

Add this code

$identifiers = Configure::read('Auth.Identifiers');
$identifiers['Authentication.Password']['fields']['username'] = 'email';
Configure::write('Auth.Identifiers', $identifiers);

to your pluginBootstrap() function in Application, or ensure the identifier configuration is correctly updated in the config/users.php file, so the plugin will be able to read it and configure Authentication internally.