Search code examples
phpauthenticationprocesswire

ProcessWire: Let users login using either e-mail or name instead of only name


in ProcessWire admin you're only able to log in using your name (username) but as I'm using e-mail log in in front end I want to use e-mail for backend, too.

How can I change admin login form to allow e-mail-address?


Solution

  • Here is the solution I came up with

    I placed those hooks in my site/init.php file

    // change login name input label to e-mail-address
    $wire->addHookAfter('ProcessLogin::buildLoginForm', function(HookEvent $event) {
        // on liner as we don't change anything else
        $event->return->get('login_name')->set('label', $event->_('E-Mail-Address'));
    });
    
    // hook into session::login to get user by mail
    $wire->addHookBefore('Session::login', function(HookEvent $event) {
        // need to get email from $input as processLogin::execute is pageName sanitizing
        $email = $event->input->post->email('login_name');
        // stop here if login_name not a valid email
        if (!$email) return;
        // new selector arrays don't seem to work on $user so using $pages here
        $user = $event->pages->get([['email', $email]]);
        // if valid user set login name argument
        if ($user->id) $event->setArgument('name', $user->name);
    });
    

    bare in mind that e-mail is not a unique field so if you don't ensure uniqueness of e-mail addresses this won't work, you could change it a little to overcome this though..

    Have a look at https://processwire.com/talk/topic/1838-login-using-e-mail-rather-than-username-and-general-login-issues/ where Ryan posts some more infos about this and possible solutions in case of duplicate e-mail addresses and https://processwire.com/talk/topic/1716-integrating-a-member-visitor-login-form/ for more on front-end login strategies