1 <?php
declare(strict_types
=1);
4 * This file is part of the Rapsys UserBundle package.
6 * (c) Raphaël Gertz <symfony@rapsys.eu>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Rapsys\UserBundle\Controller
;
14 use Doctrine\Bundle\DoctrineBundle\Registry
;
15 use Doctrine\ORM\EntityManagerInterface
;
16 use Psr\Log\LoggerInterface
;
17 use Symfony\Bridge\Twig\Mime\TemplatedEmail
;
18 use Symfony\Bundle\FrameworkBundle\Controller\AbstractController
;
19 use Symfony\Component\DependencyInjection\ContainerInterface
;
20 use Symfony\Component\Form\FormError
;
21 use Symfony\Component\HttpFoundation\Request
;
22 use Symfony\Component\HttpFoundation\Response
;
23 use Symfony\Component\HttpKernel\Exception\BadRequestHttpException
;
24 use Symfony\Component\Mailer\Exception\TransportExceptionInterface
;
25 use Symfony\Component\Mailer\MailerInterface
;
26 use Symfony\Component\Mime\Address
;
27 use Symfony\Component\Routing\Exception\MethodNotAllowedException
;
28 use Symfony\Component\Routing\Exception\ResourceNotFoundException
;
29 use Symfony\Component\Routing\Generator\UrlGeneratorInterface
;
30 use Symfony\Component\Routing\RequestContext
;
31 use Symfony\Component\Routing\RouterInterface
;
32 use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken
;
33 use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface
;
34 use Symfony\Component\Security\Http\Authentication\AuthenticationUtils
;
35 use Symfony\Component\Translation\TranslatorInterface
;
37 use Rapsys\PackBundle\Util\SluggerUtil
;
38 use Rapsys\UserBundle\RapsysUserBundle
;
40 class DefaultController
extends AbstractController
{
45 protected $translator;
50 * @TODO: move all canonical and other view related stuff in an user AbstractController like in RapsysAir render feature !!!!
52 * @param ContainerInterface $container The containter instance
53 * @param RouterInterface $router The router instance
54 * @param TranslatorInterface $translator The translator instance
56 public function __construct(ContainerInterface
$container, RouterInterface
$router, TranslatorInterface
$translator) {
58 $this->config
= $container->getParameter(self
::getAlias());
61 $this->translator
= $translator;
64 $stack = $container->get('request_stack');
67 $request = $stack->getCurrentRequest();
70 $currentLocale = $request->getLocale();
73 $this->config
['context']['locale'] = str_replace('_', '-', $currentLocale);
78 //Look for keys to translate
79 if (!empty($this->config
['translate'])) {
80 //Iterate on keys to translate
81 foreach($this->config
['translate'] as $translate) {
85 foreach(array_reverse(explode('.', $translate)) as $curkey) {
86 $tmp = array_combine([$curkey], [$tmp]);
89 $translates = array_replace_recursive($translates, $tmp);
93 //Inject every requested route in view and mail context
94 foreach($this->config
as $tag => $current) {
95 //Look for entry with title subkey
96 if (!empty($current['title'])) {
97 //Translate title value
98 $this->config
[$tag]['title'] = $translator->trans($current['title']);
101 //Look for entry with route subkey
102 if (!empty($current['route'])) {
103 //Generate url for both view and mail
104 foreach(['view', 'mail'] as $view) {
105 //Check that context key is usable
106 if (isset($current[$view]['context']) && is_array($current[$view]['context'])) {
107 //Merge with global context
108 $this->config
[$tag][$view]['context'] = array_replace_recursive($this->config
['context'], $this->config
[$tag][$view]['context']);
110 //Process every routes
111 foreach($current['route'] as $route => $key) {
113 if ($route == 'confirm') {
114 //Skip route as it requires some parameters
119 $value = $router->generate(
120 $this->config
['route'][$route]['name'],
121 $this->config
['route'][$route]['context'],
122 //Generate absolute url for mails
123 $view=='mail'?UrlGeneratorInterface
::ABSOLUTE_URL
:UrlGeneratorInterface
::ABSOLUTE_PATH
127 if (strpos($key, '.') !== false) {
132 foreach(array_reverse(explode('.', $key)) as $curkey) {
133 $tmp = array_combine([$curkey], [$tmp]);
137 $this->config
[$tag][$view]['context'] = array_replace_recursive($this->config
[$tag][$view]['context'], $tmp);
141 $this->config
[$tag][$view]['context'][$key] = $value;
145 //Look for successful intersections
146 if (!empty(array_intersect_key($translates, $this->config
[$tag][$view]['context']))) {
147 //Iterate on keys to translate
148 foreach($this->config
['translate'] as $translate) {
150 $keys = explode('.', $translate);
153 $tmp = $this->config
[$tag][$view]['context'];
156 foreach($keys as $curkey) {
158 if (!isset($tmp[$curkey])) {
164 $tmp = $tmp[$curkey];
167 //Translate tmp value
168 $tmp = $translator->trans($tmp);
171 foreach(array_reverse($keys) as $curkey) {
173 $tmp = array_combine([$curkey], [$tmp]);
177 $this->config
[$tag][$view]['context'] = array_replace_recursive($this->config
[$tag][$view]['context'], $tmp);
182 if ($view == 'view') {
184 $pathInfo = $router->getContext()->getPathInfo();
186 //Iterate on locales excluding current one
187 foreach($this->config
['locales'] as $locale) {
191 //Iterate on other locales
192 foreach(array_diff($this->config
['locales'], [$locale]) as $other) {
193 $titles[$other] = $translator->trans($this->config
['languages'][$locale], [], null, $other);
196 //Retrieve route matching path
197 $route = $router->match($pathInfo);
200 $name = $route['_route'];
203 unset($route['_route']);
205 //With current locale
206 if ($locale == $currentLocale) {
207 //Set locale locales context
208 $this->config
[$tag][$view]['context']['canonical'] = $router->generate($name, ['_locale' => $locale]+
$route, UrlGeneratorInterface
::ABSOLUTE_URL
);
210 //Set locale locales context
211 $this->config
[$tag][$view]['context']['alternates'][$locale] = [
212 'absolute' => $router->generate($name, ['_locale' => $locale]+
$route, UrlGeneratorInterface
::ABSOLUTE_URL
),
213 'relative' => $router->generate($name, ['_locale' => $locale]+
$route),
214 'title' => implode('/', $titles),
215 'translated' => $translator->trans($this->config
['languages'][$locale], [], null, $locale)
220 if (empty($this->config
[$tag][$view]['context']['alternates'][$slocale = substr($locale, 0, 2)])) {
222 $this->config
[$tag][$view]['context']['alternates'][$slocale] = [
223 'absolute' => $router->generate($name, ['_locale' => $locale]+
$route, UrlGeneratorInterface
::ABSOLUTE_URL
),
224 'relative' => $router->generate($name, ['_locale' => $locale]+
$route),
225 'title' => implode('/', $titles),
226 'translated' => $translator->trans($this->config
['languages'][$locale], [], null, $locale)
238 * Confirm account from mail link
240 * @param Request $request The request
241 * @param Registry $manager The doctrine registry
242 * @param UserPasswordEncoderInterface $encoder The password encoder
243 * @param EntityManagerInterface $manager The doctrine entity manager
244 * @param SluggerUtil $slugger The slugger
245 * @param MailerInterface $mailer The mailer
246 * @param string $mail The shorted mail address
247 * @param string $hash The hashed password
248 * @return Response The response
250 public function confirm(Request
$request, Registry
$doctrine, UserPasswordEncoderInterface
$encoder, EntityManagerInterface
$manager, SluggerUtil
$slugger, MailerInterface
$mailer, $mail, $hash): Response
{
252 if ($hash != $slugger->hash($mail)) {
254 throw new BadRequestHttpException($this->translator
->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash]));
258 $mail = $slugger->unshort($smail = $mail);
261 if (filter_var($mail, FILTER_VALIDATE_EMAIL
) === false) {
263 //XXX: prevent slugger reverse engineering by not displaying decoded mail
264 throw new BadRequestHttpException($this->translator
->trans('Invalid %field% field: %value%', ['%field%' => 'mail', '%value%' => $smail]));
267 //Without existing registrant
268 if (!($user = $doctrine->getRepository($this->config
['class']['user'])->findOneByMail($mail))) {
269 //Add error message mail already exists
270 //XXX: prevent slugger reverse engineering by not displaying decoded mail
271 $this->addFlash('error', $this->translator
->trans('Account %mail% do not exists', ['%mail%' => $smail]));
273 //Redirect to register view
274 return $this->redirectToRoute($this->config
['route']['register']['name'], ['mail' => $smail, 'field' => $sfield = $slugger->serialize([]), 'hash' => $slugger->hash($smail.$sfield)]+
$this->config
['route']['register']['context']);
278 $user->setActive(true);
281 $user->setUpdated(new \
DateTime('now'));
284 $manager->persist($user);
289 //Add error message mail already exists
290 $this->addFlash('notice', $this->translator
->trans('Your account has been activated'));
292 //Redirect to user view
293 return $this->redirectToRoute($this->config
['route']['edit']['name'], ['mail' => $smail, 'hash' => $slugger->hash($smail)]+
$this->config
['route']['edit']['context']);
297 * Edit account by shorted mail
299 * @param Request $request The request
300 * @param Registry $manager The doctrine registry
301 * @param UserPasswordEncoderInterface $encoder The password encoder
302 * @param EntityManagerInterface $manager The doctrine entity manager
303 * @param SluggerUtil $slugger The slugger
304 * @param string $mail The shorted mail address
305 * @param string $hash The hashed password
306 * @return Response The response
308 public function edit(Request
$request, Registry
$doctrine, UserPasswordEncoderInterface
$encoder, EntityManagerInterface
$manager, SluggerUtil
$slugger, $mail, $hash): Response
{
310 if ($hash != $slugger->hash($mail)) {
312 throw new BadRequestHttpException($this->translator
->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash]));
316 $mail = $slugger->unshort($smail = $mail);
318 //With existing subscriber
319 if (empty($user = $doctrine->getRepository($this->config
['class']['user'])->findOneByMail($mail))) {
321 //XXX: prevent slugger reverse engineering by not displaying decoded mail
322 throw $this->createNotFoundException($this->translator
->trans('Unable to find account %mail%', ['%mail%' => $smail]));
325 //Prevent access when not admin, user is not guest and not currently logged user
326 if (!$this->isGranted('ROLE_ADMIN') && $user != $this->getUser() || !$this->isGranted('IS_AUTHENTICATED_FULLY')) {
327 //Throw access denied
328 //XXX: prevent slugger reverse engineering by not displaying decoded mail
329 throw $this->createAccessDeniedException($this->translator
->trans('Unable to access user: %mail%', ['%mail%' => $smail]));
332 //Create the RegisterType form and give the proper parameters
333 $editForm = $this->createForm($this->config
['register']['view']['form'], $user, [
334 //Set action to register route name and context
335 'action' => $this->generateUrl($this->config
['route']['edit']['name'], ['mail' => $smail, 'hash' => $slugger->hash($smail)]+
$this->config
['route']['edit']['context']),
337 'civility_class' => $this->config
['class']['civility'],
338 //Set civility default
339 'civility_default' => $doctrine->getRepository($this->config
['class']['civility'])->findOneByTitle($this->config
['default']['civility']),
341 'mail' => $this->isGranted('ROLE_ADMIN'),
348 //Create the RegisterType form and give the proper parameters
349 $edit = $this->createForm($this->config
['edit']['view']['edit'], $user, [
350 //Set action to register route name and context
351 'action' => $this->generateUrl($this->config
['route']['edit']['name'], ['mail' => $smail, 'hash' => $slugger->hash($smail)]+
$this->config
['route']['edit']['context']),
353 'civility_class' => $this->config
['class']['civility'],
354 //Set civility default
355 'civility_default' => $doctrine->getRepository($this->config
['class']['civility'])->findOneByTitle($this->config
['default']['civility']),
357 'mail' => $this->isGranted('ROLE_ADMIN'),
365 if ($this->isGranted('ROLE_ADMIN')) {
366 //Create the LoginType form and give the proper parameters
367 $reset = $this->createForm($this->config
['edit']['view']['reset'], $user, [
368 //Set action to register route name and context
369 'action' => $this->generateUrl($this->config
['route']['edit']['name'], ['mail' => $smail, 'hash' => $slugger->hash($smail)]+
$this->config
['route']['edit']['context']),
377 if ($request->isMethod('POST')) {
378 //Refill the fields in case the form is not valid.
379 $reset->handleRequest($request);
381 //With reset submitted and valid
382 if ($reset->isSubmitted() && $reset->isValid()) {
384 $data = $reset->getData();
387 $data->setPassword($encoder->encodePassword($data, $data->getPassword()));
390 $data->setUpdated(new \
DateTime('now'));
393 $manager->persist($data);
395 //Flush to get the ids
399 $this->addFlash('notice', $this->translator
->trans('Account %mail% password updated', ['%mail%' => $mail = $data->getMail()]));
401 //Redirect to cleanup the form
402 //TODO: extract referer ??? or useless ???
403 return $this->redirectToRoute($this->config
['route']['edit']['name'], ['mail' => $smail = $slugger->short($mail), 'hash' => $slugger->hash($smail)]+
$this->config
['route']['edit']['context']);
408 $this->config
['edit']['view']['context']['reset'] = $reset->createView();
410 //XXX: prefer a reset on login to force user unspam action
413 $this->addFlash('notice', $this->translator
->trans('To change your password login with your mail and any password then follow the procedure'));
417 if ($request->isMethod('POST')) {
418 //Refill the fields in case the form is not valid.
419 $edit->handleRequest($request);
421 //With edit submitted and valid
422 if ($edit->isSubmitted() && $edit->isValid()) {
424 $data = $edit->getData();
427 $data->setUpdated(new \
DateTime('now'));
430 $manager->persist($data);
432 //Flush to get the ids
436 $this->addFlash('notice', $this->translator
->trans('Account %mail% updated', ['%mail%' => $mail = $data->getMail()]));
438 //Redirect to cleanup the form
439 //TODO: extract referer ??? or useless ???
440 return $this->redirectToRoute($this->config
['route']['edit']['name'], ['mail' => $smail = $slugger->short($mail), 'hash' => $slugger->hash($smail)]+
$this->config
['route']['edit']['context']);
445 return $this->render(
447 $this->config
['edit']['view']['name'],
449 ['edit' => $edit->createView(), 'sent' => $request->query
->get('sent', 0)]+
$this->config
['edit']['view']['context']
456 * @param Request $request The request
457 * @param AuthenticationUtils $authenticationUtils The authentication utils
458 * @param RouterInterface $router The router instance
459 * @param SluggerUtil $slugger The slugger
460 * @param string $mail The shorted mail address
461 * @param string $hash The hashed password
462 * @return Response The response
464 public function login(Request
$request, AuthenticationUtils
$authenticationUtils, RouterInterface
$router, SluggerUtil
$slugger, $mail, $hash): Response
{
465 //Create the LoginType form and give the proper parameters
466 $login = $this->createForm($this->config
['login']['view']['form'], null, [
467 //Set action to login route name and context
468 'action' => $this->generateUrl($this->config
['route']['login']['name'], $this->config
['route']['login']['context']),
469 //Disable repeated password
470 'password_repeated' => false,
479 if (!empty($mail) && !empty($hash)) {
481 if ($hash != $slugger->hash($mail)) {
483 throw new BadRequestHttpException($this->translator
->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash]));
487 $mail = $slugger->unshort($smail = $mail);
490 if (filter_var($mail, FILTER_VALIDATE_EMAIL
) === false) {
492 throw new BadRequestHttpException($this->translator
->trans('Invalid %field% field: %value%', ['%field%' => 'mail', '%value%' => $smail]));
496 $login->get('mail')->setData($mail);
497 //Last username entered by the user
498 } elseif ($lastUsername = $authenticationUtils->getLastUsername()) {
499 $login->get('mail')->setData($lastUsername);
502 //Get the login error if there is one
503 if ($error = $authenticationUtils->getLastAuthenticationError()) {
504 //Get translated error
505 $error = $this->translator
->trans($error->getMessageKey());
507 //Add error message to mail field
508 $login->get('mail')->addError(new FormError($error));
510 //Create the LoginType form and give the proper parameters
511 $recover = $this->createForm($this->config
['recover']['view']['form'], null, [
512 //Set action to recover route name and context
513 'action' => $this->generateUrl($this->config
['route']['recover']['name'], $this->config
['route']['recover']['context']),
520 //Get recover mail entity
521 $recover->get('mail')
522 //Set mail from login form
523 ->setData($login->get('mail')->getData())
525 ->addError(new FormError($this->translator
->trans('Use this form to recover your account')));
527 //Add recover form to context
528 $context['recover'] = $recover->createView();
531 //TODO: drop it if referer route is recover ?
532 $this->addFlash('notice', $this->translator
->trans('To change your password login with your mail and any password then follow the procedure'));
536 return $this->render(
538 $this->config
['login']['view']['name'],
540 ['login' => $login->createView()]+
$context+
$this->config
['login']['view']['context']
547 * @param Request $request The request
548 * @param Registry $manager The doctrine registry
549 * @param UserPasswordEncoderInterface $encoder The password encoder
550 * @param EntityManagerInterface $manager The doctrine entity manager
551 * @param SluggerUtil $slugger The slugger
552 * @param MailerInterface $mailer The mailer
553 * @param string $mail The shorted mail address
554 * @param string $pass The shorted password
555 * @param string $hash The hashed password
556 * @return Response The response
558 public function recover(Request
$request, Registry
$doctrine, UserPasswordEncoderInterface
$encoder, EntityManagerInterface
$manager, SluggerUtil
$slugger, MailerInterface
$mailer, $mail, $pass, $hash): Response
{
559 //Without mail, pass and hash
560 if (empty($mail) && empty($pass) && empty($hash)) {
561 //Create the LoginType form and give the proper parameters
562 $form = $this->createForm($this->config
['recover']['view']['form'], null, [
563 //Set action to recover route name and context
564 'action' => $this->generateUrl($this->config
['route']['recover']['name'], $this->config
['route']['recover']['context']),
571 if ($request->isMethod('POST')) {
572 //Refill the fields in case the form is not valid.
573 $form->handleRequest($request);
575 if ($form->isValid()) {
577 $data = $form->getData();
579 //Find user by data mail
580 if ($user = $doctrine->getRepository($this->config
['class']['user'])->findOneByMail($data['mail'])) {
582 $recoverMail =& $this->config
['recover']['mail'];
585 $mail = $slugger->short($user->getMail());
588 $pass = $slugger->hash($user->getPassword());
590 //Generate each route route
591 foreach($this->config
['recover']['route'] as $route => $tag) {
592 //Only process defined routes
593 if (!empty($this->config
['route'][$route])) {
594 //Process for recover mail url
595 if ($route == 'recover') {
596 //Set the url in context
597 $recoverMail['context'][$tag] = $this->get('router')->generate(
598 $this->config
['route'][$route]['name'],
599 //Prepend recover context with tag
603 'hash' => $slugger->hash($mail.$pass)
604 ]+
$this->config
['route'][$route]['context'],
605 UrlGeneratorInterface
::ABSOLUTE_URL
612 $recoverMail['context']['recipient_mail'] = $user->getMail();
615 $recoverMail['context']['recipient_name'] = trim($user->getForename().' '.$user->getSurname().($user->getPseudonym()?' ('.$user->getPseudonym().')':''));
617 //Init subject context
618 $subjectContext = $slugger->flatten(array_replace_recursive($this->config
['recover']['view']['context'], $recoverMail['context']), null, '.', '%', '%');
621 $recoverMail['subject'] = ucfirst($this->translator
->trans($recoverMail['subject'], $subjectContext));
624 $message = (new TemplatedEmail())
626 ->from(new Address($this->config
['contact']['mail'], $this->config
['contact']['title']))
628 //XXX: remove the debug set in vendor/symfony/mime/Address.php +46
629 ->to(new Address($recoverMail['context']['recipient_mail'], $recoverMail['context']['recipient_name']))
631 ->subject($recoverMail['subject'])
633 //Set path to twig templates
634 ->htmlTemplate($recoverMail['html'])
635 ->textTemplate($recoverMail['text'])
638 //XXX: require recursive merge to avoid loosing subkeys
639 //['subject' => $recoverMail['subject']]+$recoverMail['context']+$this->config['recover']['view']['context']
640 ->context(array_replace_recursive($this->config
['recover']['view']['context'], $recoverMail['context'], ['subject' => $recoverMail['subject']]));
642 //Try sending message
643 //XXX: mail delivery may silently fail
646 $mailer->send($message);
648 //Redirect on the same route with sent=1 to cleanup form
649 return $this->redirectToRoute($request->get('_route'), ['sent' => 1]+
$request->get('_route_params'));
650 //Catch obvious transport exception
651 } catch(TransportExceptionInterface
$e) {
652 //Add error message mail unreachable
653 $form->get('mail')->addError(new FormError($this->translator
->trans('Account found but unable to contact: %mail%', array('%mail%' => $data['mail']))));
657 //Add error message to mail field
658 $form->get('mail')->addError(new FormError($this->translator
->trans('Unable to find account %mail%', ['%mail%' => $data['mail']])));
664 return $this->render(
666 $this->config
['recover']['view']['name'],
668 ['form' => $form->createView(), 'sent' => $request->query
->get('sent', 0)]+
$this->config
['recover']['view']['context']
673 if ($hash != $slugger->hash($mail.$pass)) {
675 throw new BadRequestHttpException($this->translator
->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash]));
679 $mail = $slugger->unshort($smail = $mail);
682 if (filter_var($mail, FILTER_VALIDATE_EMAIL
) === false) {
684 //XXX: prevent slugger reverse engineering by not displaying decoded mail
685 throw new BadRequestHttpException($this->translator
->trans('Invalid %field% field: %value%', ['%field%' => 'mail', '%value%' => $smail]));
688 //With existing subscriber
689 if (empty($user = $doctrine->getRepository($this->config
['class']['user'])->findOneByMail($mail))) {
691 //XXX: prevent slugger reverse engineering by not displaying decoded mail
692 throw $this->createNotFoundException($this->translator
->trans('Unable to find account %mail%', ['%mail%' => $smail]));
695 //With unmatched pass
696 if ($pass != $slugger->hash($user->getPassword())) {
698 //XXX: prevent use of outdated recover link
699 throw $this->createNotFoundException($this->translator
->trans('Outdated recover link'));
702 //Create the LoginType form and give the proper parameters
703 $form = $this->createForm($this->config
['recover']['view']['form'], $user, [
704 //Set action to recover route name and context
705 'action' => $this->generateUrl($this->config
['route']['recover']['name'], ['mail' => $smail, 'pass' => $pass, 'hash' => $hash]+
$this->config
['route']['recover']['context']),
712 if ($request->isMethod('POST')) {
713 //Refill the fields in case the form is not valid.
714 $form->handleRequest($request);
716 if ($form->isValid()) {
718 $data = $form->getData();
720 //Set encoded password
721 $encoded = $encoder->encodePassword($user, $user->getPassword());
724 $pass = $slugger->hash($encoded);
727 $user->setPassword($encoded);
730 $user->setUpdated(new \
DateTime('now'));
733 $manager->persist($user);
739 $this->addFlash('notice', $this->translator
->trans('Account %mail% password updated', ['%mail%' => $mail]));
741 //Redirect to user login
742 return $this->redirectToRoute($this->config
['route']['login']['name'], ['mail' => $smail, 'hash' => $slugger->hash($smail)]+
$this->config
['route']['login']['context']);
747 return $this->render(
749 $this->config
['recover']['view']['name'],
751 ['form' => $form->createView(), 'sent' => $request->query
->get('sent', 0)]+
$this->config
['recover']['view']['context']
756 * Register an account
758 * @param Request $request The request
759 * @param Registry $manager The doctrine registry
760 * @param UserPasswordEncoderInterface $encoder The password encoder
761 * @param EntityManagerInterface $manager The doctrine entity manager
762 * @param SluggerUtil $slugger The slugger
763 * @param MailerInterface $mailer The mailer
764 * @param LoggerInterface $logger The logger
765 * @param string $mail The shorted mail address
766 * @param string $field The serialized then shorted form field array
767 * @param string $hash The hashed serialized field array
768 * @return Response The response
770 public function register(Request
$request, Registry
$doctrine, UserPasswordEncoderInterface
$encoder, EntityManagerInterface
$manager, SluggerUtil
$slugger, MailerInterface
$mailer, LoggerInterface
$logger, $mail, $field, $hash): Response
{
772 $reflection = new \
ReflectionClass($this->config
['class']['user']);
775 $user = $reflection->newInstance();
777 //With mail and field
778 if (!empty($field) && !empty($hash)) {
780 if ($hash != $slugger->hash($mail.$field)) {
782 throw new BadRequestHttpException($this->translator
->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash]));
788 $mail = $slugger->unshort($smail = $mail);
791 if (filter_var($mail, FILTER_VALIDATE_EMAIL
) === false) {
793 //XXX: prevent slugger reverse engineering by not displaying decoded mail
794 throw new BadRequestHttpException($this->translator
->trans('Invalid %field% field: %value%', ['%field%' => 'mail', '%value%' => $smail]));
798 $user->setMail($mail);
807 //Unshort then unserialize field
808 $field = $slugger->unserialize($sfield = $field);
810 } catch (\Error
|\Exception
$e) {
812 throw new BadRequestHttpException($this->translator
->trans('Invalid %field% field: %value%', ['%field%' => 'field', '%value%' => $field]), $e);
815 //With non array field
816 if (!is_array($field)) {
818 throw new BadRequestHttpException($this->translator
->trans('Invalid %field% field: %value%', ['%field%' => 'field', '%value%' => $field]));
820 //Without field and hash
832 //Create the RegisterType form and give the proper parameters
833 $form = $this->createForm($this->config
['register']['view']['form'], $user, $field+
[
834 //Set action to register route name and context
835 'action' => $this->generateUrl($this->config
['route']['register']['name'], ['mail' => $smail, 'field' => $sfield, 'hash' => $hash]+
$this->config
['route']['register']['context']),
837 'civility_class' => $this->config
['class']['civility'],
838 //Set civility default
839 'civility_default' => $doctrine->getRepository($this->config
['class']['civility'])->findOneByTitle($this->config
['default']['civility']),
846 if ($request->isMethod('POST')) {
847 //Refill the fields in case the form is not valid.
848 $form->handleRequest($request);
850 if ($form->isValid()) {
852 $data = $form->getData();
854 //With existing registrant
855 if ($doctrine->getRepository($this->config
['class']['user'])->findOneByMail($mail = $data->getMail())) {
856 //Add error message mail already exists
857 $this->addFlash('warning', $this->translator
->trans('Account %mail% already exists', ['%mail%' => $mail]));
859 //Redirect to user view
860 return $this->redirectToRoute(
861 $this->config
['route']['edit']['name'],
863 'mail' => $smail = $slugger->short($mail),
864 'hash' => $slugger->hash($smail)
865 ]+
$this->config
['route']['edit']['context']
870 $registerMail =& $this->config
['register']['mail'];
872 //Extract names and pseudonym from mail
873 $names = explode(' ', $pseudonym = ucwords(trim(preg_replace('/[^a-zA-Z]+/', ' ', current(explode('@', $data->getMail()))))));
876 $user->setPseudonym($user->getPseudonym()??$pseudonym);
879 $user->setForename($user->getForename()??$names[0]);
882 $user->setSurname($user->getSurname()??$names[1]??$names[0]);
885 $user->setPassword($encoder->encodePassword($user, $user->getPassword()??$data->getMail()));
888 $user->setCreated(new \
DateTime('now'));
891 $user->setUpdated(new \
DateTime('now'));
894 $manager->persist($user);
896 //Iterate on default group
897 foreach($this->config
['default']['group'] as $i => $groupTitle) {
899 if (($group = $doctrine->getRepository($this->config
['class']['group'])->findOneByTitle($groupTitle))) {
901 //XXX: see vendor/symfony/security-core/Role/Role.php
902 $user->addGroup($group);
906 //XXX: consider missing group as fatal
907 throw new \
Exception(sprintf('Group from rapsys_user.default.group[%d] not found by title: %s', $i, $groupTitle));
911 //Generate each route route
912 foreach($this->config
['register']['route'] as $route => $tag) {
913 //Only process defined routes
914 if (!empty($this->config
['route'][$route])) {
915 //Process for confirm url
916 if ($route == 'confirm') {
917 //Set the url in context
918 $registerMail['context'][$tag] = $this->get('router')->generate(
919 $this->config
['route'][$route]['name'],
920 //Prepend subscribe context with tag
922 'mail' => $smail = $slugger->short($data->getMail()),
923 'hash' => $slugger->hash($smail)
924 ]+
$this->config
['route'][$route]['context'],
925 UrlGeneratorInterface
::ABSOLUTE_URL
931 //XXX: DEBUG: remove me
932 //die($registerMail['context']['confirm_url']);
937 $this->translator
->trans(
938 'newuser:mail=%mail%|locale=%locale%|confirm=%confirm%',
940 '%mail%' => $data->getMail(),
941 '%locale%' => $request->getLocale(),
942 '%confirm%' => $registerMail['context'][$this->config
['register']['route']['confirm']]
948 $registerMail['context']['recipient_mail'] = $data->getMail();
951 $registerMail['context']['recipient_name'] = '';
954 $registerMail['context']['recipient_name'] = implode(' ', [$data->getForename(), $data->getSurname(), $data->getPseudonym()?'('.$data->getPseudonym().')':'']);
956 //Init subject context
957 $subjectContext = $slugger->flatten(array_replace_recursive($this->config
['register']['view']['context'], $registerMail['context']), null, '.', '%', '%');
960 $registerMail['subject'] = ucfirst($this->translator
->trans($registerMail['subject'], $subjectContext));
963 $message = (new TemplatedEmail())
965 ->from(new Address($this->config
['contact']['mail'], $this->config
['contact']['title']))
967 //XXX: remove the debug set in vendor/symfony/mime/Address.php +46
968 ->to(new Address($registerMail['context']['recipient_mail'], $registerMail['context']['recipient_name']))
970 ->subject($registerMail['subject'])
972 //Set path to twig templates
973 ->htmlTemplate($registerMail['html'])
974 ->textTemplate($registerMail['text'])
977 ->context(['subject' => $registerMail['subject']]+
$registerMail['context']);
979 //Try saving in database
984 //Add error message mail already exists
985 $this->addFlash('notice', $this->translator
->trans('Your account has been created'));
987 //Try sending message
988 //XXX: mail delivery may silently fail
991 $mailer->send($message);
993 //Redirect on the same route with sent=1 to cleanup form
994 return $this->redirectToRoute($request->get('_route'), ['sent' => 1]+
$request->get('_route_params'));
995 //Catch obvious transport exception
996 } catch(TransportExceptionInterface
$e) {
997 //Add error message mail unreachable
998 $form->get('mail')->addError(new FormError($this->translator
->trans('Account %mail% tried subscribe but unable to contact', ['%mail%' => $data->getMail()])));
1000 //Catch double subscription
1001 } catch (\Doctrine\DBAL\Exception\UniqueConstraintViolationException
$e) {
1002 //Add error message mail already exists
1003 $this->addFlash('error', $this->translator
->trans('Account %mail% already exists', ['%mail%' => $mail]));
1009 return $this->render(
1011 $this->config
['register']['view']['name'],
1013 ['form' => $form->createView(), 'sent' => $request->query
->get('sent', 0)]+
$this->config
['register']['view']['context']
1020 public function getAlias(): string {
1021 return RapsysUserBundle
::getAlias();