Unverified Commit 7fe02bfe authored by Sebastian Castro's avatar Sebastian Castro
Browse files

Fixs user registration after refactor

parent 86079773
gogo_user_register:
path: /register/
defaults: { _controller: App\Controller\RegistrationController::registerAction }
fos_user:
resource: "@FOSUserBundle/Resources/config/routing/all.xml"
sonata_user_admin_security:
resource: '@SonataUserBundle/Resources/config/routing/admin_security.xml'
prefix: /admin
......
......@@ -73,6 +73,15 @@ services:
$instanceName: '%instance_name%'
$fromEmail: '%from_email%'
# Overide FOS Registration Controller
App\Controller\RegistrationController:
tags: ['controller.service_arguments']
arguments:
- "@event_dispatcher"
- "@fos_user.registration.form.factory"
- "@fos_user.user_manager"
- "@security.token_storage"
App\Application\Sonata\UserBundle\Form\Type\RegistrationFormType:
arguments: [ "%fos_user.model.user.class%" ]
tags:
......
<?php
/*
* This file is part of the Sonata Project package.
*
* (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Application\Sonata\UserBundle\Controller;
use App\Application\Sonata\UserBundle\Form\Handler\RegistrationFormHandler;
use App\Application\Sonata\UserBundle\Form\Type\RegistrationFormType;
use App\Document\User;
use Doctrine\ODM\MongoDB\DocumentManager;
use FOS\UserBundle\Doctrine\UserManager;
use FOS\UserBundle\Model\UserInterface;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Exception\AccountStatusException;
/**
* This class is inspired from the FOS RegistrationController.
*
* @author Hugo Briand <briand@ekino.com>
*/
class RegistrationFOSUser1Controller extends Controller
{
/**
* @return RedirectResponse|Response
*/
public function registerAction(Request $request = null, SessionInterface $session, DocumentManager $dm,
RegistrationFormHandler $formHandler)
{
$config = $dm->getRepository('App\Document\Configuration')->findConfiguration();
if (!$config->getUser()->getEnableRegistration()) {
$session->getFlashBag()->add('error', "Désolé, vous n'êtes pas autorisé à créer un compte.");
return $this->redirectToRoute('gogo_directory');
}
$user = $this->getUser();
if ($user instanceof UserInterface) {
$session->getFlashBag()->set('sonata_user_error', 'sonata_user_already_authenticated');
return $this->redirect($this->generateUrl('sonata_user_profile_show'));
}
$form = $this->get('form.factory')->create(RegistrationFormType::class, new User());
$confirmationEnabled = $config->getUser()->getSendConfirmationEmail();
$process = $formHandler->process($form, $confirmationEnabled);
if ($process) {
$user = $form->getData();
$authUser = false;
if ($confirmationEnabled) {
$this->get('session')->set('fos_user_send_confirmation_email/email', $user->getEmail());
$url = $this->generateUrl('fos_user_registration_check_email');
} else {
$authUser = true;
$route = $this->get('session')->get('sonata_basket_delivery_redirect');
if (null !== $route) {
$this->get('session')->remove('sonata_basket_delivery_redirect');
$url = $this->generateUrl($route);
} else {
$url = $this->get('session')->get('sonata_user_redirect_url');
}
}
if (!$url) {
$url = $this->generateUrl('sonata_user_profile_show');
}
$this->setFlash('fos_user_success', 'registration.flash.user_created');
$response = $this->redirect($url);
if ($authUser) {
$this->authenticateUser($user, $response);
}
return $response;
}
// NEXT_MAJOR: Inject $request in the method signature instead.
if ($this->has('request_stack')) {
$request = $this->get('request_stack')->getCurrentRequest();
} else {
$request = $this->get('request_stack')->getCurrentRequest();
}
$this->get('session')->set('sonata_user_redirect_url', $request->headers->get('referer'));
return $this->render('FOSUserBundle:Registration:register.html.'.$this->getEngine(), [
'form' => $form->createView(),
]);
}
/**
* Tell the user to check his email provider.
*
* @return Response
*
* @throws NotFoundHttpException
*/
public function checkEmailAction(UserManager $userManager)
{
$email = $this->get('session')->get('fos_user_send_confirmation_email/email');
$this->get('session')->remove('fos_user_send_confirmation_email/email');
$user = $userManager->findUserByEmail($email);
if (null === $user) {
throw new NotFoundHttpException(sprintf('The user with email "%s" does not exist', $email));
}
return $this->render('FOSUserBundle:Registration:checkEmail.html.'.$this->getEngine(), [
'user' => $user,
]);
}
/**
* Receive the confirmation token from user email provider, login the user.
*
* @param string $token
*
* @return RedirectResponse
*
* @throws NotFoundHttpException
*/
public function confirmAction($token, UserManager $userManager)
{
$user = $userManager->findUserByConfirmationToken($token);
if (null === $user) {
throw new NotFoundHttpException(sprintf('The user with confirmation token "%s" does not exist', $token));
}
$user->setConfirmationToken(null);
$user->setEnabled(true);
$user->setLastLogin(new \DateTime());
$userManager->updateUser($user);
if ($redirectRoute = $this->getParameter('sonata.user.register.confirm.redirect_route')) {
$response = $this->redirect($this->generateUrl(
$redirectRoute,
$this->getParameter('sonata.user.register.confirm.redirect_route_params')
));
} else {
$response = $this->redirect($this->generateUrl('fos_user_registration_confirmed'));
}
$this->authenticateUser($user, $response);
return $response;
}
/**
* Tell the user his account is now confirmed.
*
* @return Response
*
* @throws AccessDeniedException
*/
public function confirmedAction()
{
$user = $this->getUser();
if (!is_object($user) || !$user instanceof UserInterface) {
throw new AccessDeniedException('This user does not have access to this section.');
}
return $this->render('FOSUserBundle:Registration:confirmed.html.'.$this->getEngine(), [
'user' => $user,
]);
}
/**
* Authenticate a user with Symfony Security.
*/
protected function authenticateUser(UserInterface $user, Response $response)
{
try {
$this->get('fos_user.security.login_manager')->loginUser(
$this->getParameter('fos_user.firewall_name'),
$user,
$response
);
} catch (AccountStatusException $ex) {
// We simply do not authenticate users which do not pass the user
// checker (not enabled, expired, etc.).
}
}
/**
* @param string $action
* @param string $value
*/
protected function setFlash($action, $value)
{
$this->get('session')->getFlashBag()->set($action, $value);
}
/**
* @return string
*/
protected function getEngine()
{
return $this->getParameter('fos_user.template.engine');
}
}
<?php
/*
* This file is part of the FOSUserBundle package.
*
* (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Application\Sonata\UserBundle\Form\Handler;
use App\Document\Coordinates;
use FOS\UserBundle\Mailer\MailerInterface;
use FOS\UserBundle\Model\UserInterface;
use FOS\UserBundle\Model\UserManagerInterface;
use FOS\UserBundle\Util\TokenGeneratorInterface;
use Geocoder\ProviderAggregator;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\RequestStack;
class RegistrationFormHandler
{
protected $form;
public function __construct(RequestStack $requestStack, UserManagerInterface $userManager,
MailerInterface $mailer, TokenGeneratorInterface $tokenGenerator,
ProviderAggregator $geocoder)
{
$this->request = $request_stack->getCurrentRequest();
$this->userManager = $userManager;
$this->mailer = $mailer;
$this->tokenGenerator = $tokenGenerator;
$this->geocoder = $geocoder;
}
/**
* @param bool $confirmation
*/
public function process($form, $confirmation = false)
{
$user = $this->createUser();
$this->form = $form;
$form->setData($user);
if ('POST' === $this->request->getMethod()) {
$form->handleRequest($this->request);
$user = $form->getData();
$usersSameEmail = $this->userManager->findUserByEmail($user->getEmail());
$alreadyUsedEmail = null === $usersSameEmail ? false : count($usersSameEmail) > 1;
$userSameName = $this->userManager->findUserByUsername($user->getUsername());
$alreadyUsedUserName = null === $userSameName ? false : count($userSameName);
$locoationSetToReceiveNewsletter = $user->getNewsletterFrequency() > 0 && !$user->getLocation();
$geocodeError = false;
if ($user->getLocation()) {
try {
$geocoded = $this->geocoder->using('google_maps')->geocode($user->getLocation())
->first()->getCoordinates();
$user->setGeo(new Coordinates($geocoded->getLatitude(), $geocoded->getLongitude()));
} catch (\Exception $error) {
$geocodeError = true;
}
}
if ($form->isSubmitted() && $form->isValid() && !$alreadyUsedEmail && !$alreadyUsedUserName && !$locoationSetToReceiveNewsletter && !$geocodeError) {
$this->onSuccess($user, $confirmation);
return true;
} else {
if ($alreadyUsedEmail) {
$form->get('email')->addError(new FormError('Cet email est déjà utilisé'));
}
if ($alreadyUsedUserName) {
$form->get('username')->addError(new FormError("Ce nom d'utilisateur est déjà pris !"));
}
if ($locoationSetToReceiveNewsletter) {
$form->get('location')->addError(new FormError('Si vous voulez recevoir les nouveaux ajouts, vous devez renseigner une adresse'));
}
if ($geocodeError) {
$form->get('location')->addError(new FormError('Impossible de localiser cette adresse'));
}
}
}
return false;
}
/**
* @param bool $confirmation
*/
protected function onSuccess(UserInterface $user, $confirmation)
{
if ($confirmation) {
$user->setEnabled(false);
if (null === $user->getConfirmationToken()) {
$user->setConfirmationToken($this->tokenGenerator->generateToken());
}
$this->mailer->sendConfirmationEmailMessage($user);
} else {
$user->setEnabled(true);
}
$this->userManager->updateUser($user);
}
/**
* @return UserInterface
*/
protected function createUser()
{
return $this->userManager->createUser();
}
}
<?php
namespace App\Controller;
use FOS\UserBundle\Controller\RegistrationController as FosController;
use FOS\UserBundle\Event\FilterUserResponseEvent;
use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\Event\GetResponseUserEvent;
use FOS\UserBundle\Form\Factory\FactoryInterface;
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Model\UserManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Doctrine\ODM\MongoDB\DocumentManager;
use Symfony\Component\Form\FormError;
use Geocoder\ProviderAggregator;
use App\Document\Coordinates;
class RegistrationController extends FosController
{
private $eventDispatcher;
private $formFactory;
private $userManager;
private $tokenStorage;
public function __construct($eventDispatcher, $formFactory, $userManager, $tokenStorage, \Swift_Mailer $mailer,
DocumentManager $dm, ProviderAggregator $geocoder)
{
$this->eventDispatcher = $eventDispatcher;
$this->formFactory = $formFactory;
$this->userManager = $userManager;
$this->tokenStorage = $tokenStorage;
$this->mailer = $mailer;
$this->dm = $dm;
$this->geocoder = $geocoder->using('google_maps');
}
/**
* @param Request $request
*
* @return Response
*/
public function registerAction(Request $request)
{
$config = $this->dm->getRepository('App\Document\Configuration')->findConfiguration();
if (!$config->getUser()->getEnableRegistration()) {
$session->getFlashBag()->add('error', "Désolé, vous n'êtes pas autorisé à créer un compte.");
return $this->redirectToRoute('gogo_directory');
}
$user = $this->userManager->createUser();
$event = new GetResponseUserEvent($user, $request);
$this->eventDispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);
if (null !== $event->getResponse()) {
return $event->getResponse();
}
$form = $this->formFactory->createForm();
$form->setData($user);
$form->handleRequest($request);
$confirmationEnabled = $config->getUser()->getSendConfirmationEmail();
if ($form->isSubmitted()) {
dump("form submitted");
$user = $form->getData();
// CUSTOM VALIDATIONS
$locationSetToReceiveNewsletter = $user->getNewsletterFrequency() > 0 && !$user->getLocation();
$geocodeError = false;
if ($user->getLocation()) {
try {
$geocoded = $this->geocoder->geocode($user->getLocation())
->first()->getCoordinates();
$user->setGeo(new Coordinates($geocoded->getLatitude(), $geocoded->getLongitude()));
} catch (\Exception $error) {
dump($error);
$geocodeError = true;
}
}
// CHECK FORM IS VALID
if ($form->isValid() && !$locationSetToReceiveNewsletter && !$geocodeError) {
if ($confirmationEnabled) {
// SEND CONFIRM EMAIL
// the registration_success event is intercepted by FOS EmailConfirmationListener
$event = new FormEvent($form, $request);
$this->eventDispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);
$response = $event->getResponse();
}
else {
// DIRECTLY LOG THE USER
$user->setEnabled(true);
$url = $this->generateUrl('fos_user_registration_confirmed');
$response = new RedirectResponse($url);
}
$this->userManager->updateUser($user);
$this->eventDispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED, new FilterUserResponseEvent($user, $request, $response));
return $response;
} else {
// VALIDATION ERROR
if ($locationSetToReceiveNewsletter) {
$form->get('location')->addError(new FormError('Si vous voulez recevoir les nouveaux ajouts, vous devez renseigner une adresse'));
}
if ($geocodeError) {
$form->get('location')->addError(new FormError('Impossible de localiser cette adresse'));
}
$this->eventDispatcher->dispatch(FOSUserEvents::REGISTRATION_FAILURE, $event);
}
}
// if ($formHandler->process($form, $confirmationEnabled);) {
// $user = $form->getData();
// if ($confirmationEnabled) {
// $this->get('session')->set('fos_user_send_confirmation_email/email', $user->getEmail());
// $url = $this->generateUrl('fos_user_registration_check_email');
// } else {
// $route = $this->get('session')->get('sonata_basket_delivery_redirect');
// if (null !== $route) {
// $this->get('session')->remove('sonata_basket_delivery_redirect');
// $url = $this->generateUrl($route);
// } else {
// $url = $this->get('session')->get('sonata_user_redirect_url');
// }
// }
// if (!$url) {
// $url = $this->generateUrl('sonata_user_profile_show');
// }
// $this->setFlash('fos_user_success', 'registration.flash.user_created');
// $response = $this->redirect($url);
// if (!$confirmationEnabled) {
// $this->authenticateUser($user, $response);
// }
// return $response;
// }
// if ($form->isSubmitted()) {
// if ($form->isValid()) {
// }
// $event = new FormEvent($form, $request);
// $this->eventDispatcher->dispatch(FOSUserEvents::REGISTRATION_FAILURE, $event);
// if (null !== $response = $event->getResponse()) {
// return $response;
// }
// }
return $this->render('@FOSUser/Registration/register.html.twig', array(
'form' => $form->createView(),
));
}
// /**
// * @return RedirectResponse|Response
// */
// public function registerAction(Request $request = null, SessionInterface $session, DocumentManager $dm,
// RegistrationFormHandler $formHandler)
// {
// $user = $this->getUser();
// if ($user instanceof UserInterface) {
// $session->getFlashBag()->set('sonata_user_error', 'sonata_user_already_authenticated');
// return $this->redirect($this->generateUrl('sonata_user_profile_show'));
// }
// $form = $this->get('form.factory')->create(RegistrationFormType::class, new User());
// dump($confirmationEnabled, $config->getUser());
// $process = $formHandler->process($form, $confirmationEnabled);
// if ($process) {
// $user = $form->getData();
// if ($confirmationEnabled) {
// $this->get('session')->set('fos_user_send_confirmation_email/email', $user->getEmail());
// $url = $this->generateUrl('fos_user_registration_check_email');
// } else {
// $route = $this->get('session')->get('sonata_basket_delivery_redirect');
// if (null !== $route) {
// $this->get('session')->remove('sonata_basket_delivery_redirect');
// $url = $this->generateUrl($route);
// } else {
// $url = $this->get('session')->get('sonata_user_redirect_url');
// }
// }
// if (!$url) {
// $url = $this->generateUrl('sonata_user_profile_show');
// }
// $this->setFlash('fos_user_success', 'registration.flash.user_created');
// $response = $this->redirect($url);
// if (!$confirmationEnabled) {
// $this->authenticateUser($user, $response);
// }
// return $response;
// }