eZ Platform Discussions

Login a user after registration

version2

#1

Hello,

on our project, we added a function to automatically log in the user just after his registration is successful. It was really quite complicated to get all the elements working together in place and there is no real documentation for that, so I thought maybe it would be a good idea to post a summary about it here.

Everything below is happening in our own UserRegisterController, adapted from the one in the repository-forms bundle from ezsystems, that we initially overrided to be able to manage authentication via ajax calls without reloading the page, as well as still manage the input errors on server side.

So as soon as our registration is successful in our controller, we load the user via the user service, by its login that just was one of the parameters of the form, and then we use the permission resolver to set him as current user.

$ezUser = $this->getRepository()->getUserService()->loadUserByLogin($formData[‘username’]);
$this->getRepository()->getPermissionResolver()->setCurrentUserReference($ezUser);

If you used the native login form type generated by eZ, your parameter should look more like this :

$formData[‘fieldsData’][‘user_account’][‘value’][‘email’]

Anyway, just doing this is not sufficient, we need to go through Symfony security & authentication or the user will not be really authenticated.

So we create a new user adapted for the security layer and build a token for it :

$user = new \eZ\Publish\Core\MVC\Symfony\Security\User($ezUser, [‘ROLE_USER’]);
$token = new \Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken($user, null,‘ezpublish_front’, $user->getRoles());

Note that we used the specific eZ User structure adapted to the security layer and had to explicitly describe the roles for the user, and also that we used as provider the ‘ezpublish_front’ default firewall as defined in the app/config/security.yml file.

We then store the token and update the session, as for a normal Symfony authentication :

$this->container->get(‘security.token_storage’)->setToken($token);
$this->get(‘session’)->set(’_security_ezpublish_front’, serialize($token));

Then we send back our response and the user is logged-in immediately.

I hope this can be useful to someone someday !