Winter CMS resources and help articles

Simple and to the point. Optimized by the community.

Use email address instead of username for backend admins

0
by LukeTowers, last modified on March 26th, 2022

By default, Winter requires a backend user to login with a unique username. Add the following code to your Plugin's boot method to replace the username with an email address.

use Backend\Models\User;
use Backend\Controllers\Users;

class Plugin extends PluginBase
{
    public $elevated = true;

    public function boot()
    {
        // Replace the login page's login field placeholder to say 'email' instead of 'username'
        Event::listen('translator.beforeResolve', function ($key, $replaces, $locale) {
            switch ($key) {
                case 'backend::lang.account.login_placeholder':
                    return 'email';
                case 'backend::lang.user.menu_label':
                    return 'Users';
                case 'backend::lang.user.menu_description':
                    return 'Manage all users';
            }
        });

        // Use the email address to process logins
        User::$loginAttribute = 'email';

        User::extend(function($model) {
            // Remove the login rules. The email will be used so no additional 
            // validation is needed here.
            $model->rules = array_merge($model->rules, [
                'login' => '',
            ]);

            // Copy email over to the login attribute
            $model->bindEvent('model.beforeSave', function () use ($model) {
                $model->login = $model->email;
            });
        });

        // Remove the login attribute from backend forms and use only the email attribute
        Event::listen('backend.form.extendFieldsBefore', function ($form) {
            if (!$form->model instanceof User || !$form->getController() instanceof Users) {
                return;
            }
            $fields = $form->tabs['fields'];

            // Remove the login field and make email full width
            if (isset($fields['email']) && is_array($fields['email'])) {
                unset($fields['login']);
                $fields['email'] = array_merge($fields['email'], [
                    'span' => 'full',
                ]);
                $form->tabs = array_merge($form->tabs, ['fields' => $fields]);
            }
        });

        // Remove the login column from the backend list
        Users::extendListColumns(function ($list, $model) {
            $list->removeColumn('login');
        });
    }
}

Discussion

0 comments

We use cookies to measure the performance of this website. Do you want to accept these cookies?