userfrosting

Userfrosting: How to make user login automatically soon after registration


In our usecase, we need to login the user automatically soon after successful registration for enabling, rather forcing the user to:

  1. Change password.
  2. Upload a file.

How to achieve this programmatically, in AccountController's register method?

Ideally, it should be a seamless registration process that ends with the login state in the user dashboard.

Request valuable help / hint / pointers...

Thanks!


Solution

  • The best way to approach this is to take a cue from the password reset controller, which already does this (in this case, it automatically logs the user in after they've selected a new password).

    So, add this to the bottom of the register method in AccountController:

    // Log out any existing user, and create a new session
    if (!$this->_app->user->isGuest()) {
        $this->_app->logout(true);
        // Restart session
        $this->_app->startSession();
    }
    // Auto-login the user
    $this->_app->login($user);
    $ms = $this->_app->alerts;
    $ms->addMessageTranslated("success", "ACCOUNT_WELCOME", $this->_app->user->export());
    

    You will also need to modify the AJAX callback in register.twig to redirect the user to the home page, instead of the login page:

    window.location.replace(site['uri']['public']);
    

    The user will then be automatically redirected to the landing page for their primary group after being logged in.