]> Raphaël G. Git Repositories - userbundle/blob - Controller/DefaultController.php
272f7bb19615efec101f9b50661e7a4b92cb8538
[userbundle] / Controller / DefaultController.php
1 <?php declare(strict_types=1);
2
3 /*
4 * This file is part of the Rapsys UserBundle package.
5 *
6 * (c) Raphaël Gertz <symfony@rapsys.eu>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Rapsys\UserBundle\Controller;
13
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;
36
37 use Rapsys\PackBundle\Util\SluggerUtil;
38 use Rapsys\UserBundle\RapsysUserBundle;
39
40 class DefaultController extends AbstractController {
41 //Config array
42 protected $config;
43
44 //Translator instance
45 protected $translator;
46
47 /**
48 * Constructor
49 *
50 * @TODO: move all canonical and other view related stuff in an user AbstractController like in RapsysAir render feature !!!!
51 *
52 * @param ContainerInterface $container The containter instance
53 * @param RouterInterface $router The router instance
54 * @param TranslatorInterface $translator The translator instance
55 */
56 public function __construct(ContainerInterface $container, RouterInterface $router, TranslatorInterface $translator) {
57 //Retrieve config
58 $this->config = $container->getParameter(self::getAlias());
59
60 //Set the translator
61 $this->translator = $translator;
62
63 //Get request stack
64 $stack = $container->get('request_stack');
65
66 //Get current request
67 $request = $stack->getCurrentRequest();
68
69 //Get current locale
70 $currentLocale = $request->getLocale();
71
72 //Set locale
73 $this->config['context']['locale'] = str_replace('_', '-', $currentLocale);
74
75 //Set translate array
76 $translates = [];
77
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) {
82 //Set tmp
83 $tmp = null;
84 //Iterate on keys
85 foreach(array_reverse(explode('.', $translate)) as $curkey) {
86 $tmp = array_combine([$curkey], [$tmp]);
87 }
88 //Append tree
89 $translates = array_replace_recursive($translates, $tmp);
90 }
91 }
92
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']);
99 }
100
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']);
109
110 //Process every routes
111 foreach($current['route'] as $route => $key) {
112 //With confirm route
113 if ($route == 'confirm') {
114 //Skip route as it requires some parameters
115 continue;
116 }
117
118 //Set value
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
124 );
125
126 //Multi level key
127 if (strpos($key, '.') !== false) {
128 //Set tmp
129 $tmp = $value;
130
131 //Iterate on key
132 foreach(array_reverse(explode('.', $key)) as $curkey) {
133 $tmp = array_combine([$curkey], [$tmp]);
134 }
135
136 //Set value
137 $this->config[$tag][$view]['context'] = array_replace_recursive($this->config[$tag][$view]['context'], $tmp);
138 //Single level key
139 } else {
140 //Set value
141 $this->config[$tag][$view]['context'][$key] = $value;
142 }
143 }
144
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) {
149 //Set keys
150 $keys = explode('.', $translate);
151
152 //Set tmp
153 $tmp = $this->config[$tag][$view]['context'];
154
155 //Iterate on keys
156 foreach($keys as $curkey) {
157 //Without child key
158 if (!isset($tmp[$curkey])) {
159 //Skip to next key
160 continue(2);
161 }
162
163 //Get child key
164 $tmp = $tmp[$curkey];
165 }
166
167 //Translate tmp value
168 $tmp = $translator->trans($tmp);
169
170 //Iterate on keys
171 foreach(array_reverse($keys) as $curkey) {
172 //Set parent key
173 $tmp = array_combine([$curkey], [$tmp]);
174 }
175
176 //Set value
177 $this->config[$tag][$view]['context'] = array_replace_recursive($this->config[$tag][$view]['context'], $tmp);
178 }
179 }
180
181 //With view context
182 if ($view == 'view') {
183 //Get context path
184 $pathInfo = $router->getContext()->getPathInfo();
185
186 //Iterate on locales excluding current one
187 foreach($this->config['locales'] as $locale) {
188 //Set titles
189 $titles = [];
190
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);
194 }
195
196 //Retrieve route matching path
197 $route = $router->match($pathInfo);
198
199 //Get route name
200 $name = $route['_route'];
201
202 //Unset route name
203 unset($route['_route']);
204
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);
209 } else {
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)
216 ];
217 }
218
219 //Add shorter locale
220 if (empty($this->config[$tag][$view]['context']['alternates'][$slocale = substr($locale, 0, 2)])) {
221 //Add shorter locale
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)
227 ];
228 }
229 }
230 }
231 }
232 }
233 }
234 }
235 }
236
237 /**
238 * Confirm account from mail link
239 *
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
249 */
250 public function confirm(Request $request, Registry $doctrine, UserPasswordEncoderInterface $encoder, EntityManagerInterface $manager, SluggerUtil $slugger, MailerInterface $mailer, $mail, $hash): Response {
251 //With invalid hash
252 if ($hash != $slugger->hash($mail)) {
253 //Throw bad request
254 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash]));
255 }
256
257 //Get mail
258 $mail = $slugger->unshort($smail = $mail);
259
260 //Without valid mail
261 if (filter_var($mail, FILTER_VALIDATE_EMAIL) === false) {
262 //Throw bad request
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]));
265 }
266
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]));
272
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']);
275 }
276
277 //Set active
278 $user->setActive(true);
279
280 //Set updated
281 $user->setUpdated(new \DateTime('now'));
282
283 //Persist user
284 $manager->persist($user);
285
286 //Send to database
287 $manager->flush();
288
289 //Add error message mail already exists
290 $this->addFlash('notice', $this->translator->trans('Your account has been activated'));
291
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']);
294 }
295
296 /**
297 * Edit account by shorted mail
298 *
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
307 */
308 public function edit(Request $request, Registry $doctrine, UserPasswordEncoderInterface $encoder, EntityManagerInterface $manager, SluggerUtil $slugger, $mail, $hash): Response {
309 //With invalid hash
310 if ($hash != $slugger->hash($mail)) {
311 //Throw bad request
312 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash]));
313 }
314
315 //Get mail
316 $mail = $slugger->unshort($smail = $mail);
317
318 //With existing subscriber
319 if (empty($user = $doctrine->getRepository($this->config['class']['user'])->findOneByMail($mail))) {
320 //Throw not found
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]));
323 }
324
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]));
330 }
331
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']),
336 //Set civility class
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']),
340 //Disable mail
341 'mail' => $this->isGranted('ROLE_ADMIN'),
342 //Disable password
343 'password' => false,
344 //Set method
345 'method' => 'POST'
346 ]);
347
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']),
352 //Set civility class
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']),
356 //Disable mail
357 'mail' => $this->isGranted('ROLE_ADMIN'),
358 //Disable password
359 'password' => false,
360 //Set method
361 'method' => 'POST'
362 ]);
363
364 //With admin role
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']),
370 //Disable mail
371 'mail' => false,
372 //Set method
373 'method' => 'POST'
374 ]);
375
376 //With post method
377 if ($request->isMethod('POST')) {
378 //Refill the fields in case the form is not valid.
379 $reset->handleRequest($request);
380
381 //With reset submitted and valid
382 if ($reset->isSubmitted() && $reset->isValid()) {
383 //Set data
384 $data = $reset->getData();
385
386 //Set password
387 $data->setPassword($encoder->encodePassword($data, $data->getPassword()));
388
389 //Set updated
390 $data->setUpdated(new \DateTime('now'));
391
392 //Queue snippet save
393 $manager->persist($data);
394
395 //Flush to get the ids
396 $manager->flush();
397
398 //Add notice
399 $this->addFlash('notice', $this->translator->trans('Account %mail% password updated', ['%mail%' => $mail = $data->getMail()]));
400
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']);
404 }
405 }
406
407 //Add reset view
408 $this->config['edit']['view']['context']['reset'] = $reset->createView();
409 //Without admin role
410 //XXX: prefer a reset on login to force user unspam action
411 } else {
412 //Add notice
413 $this->addFlash('notice', $this->translator->trans('To change your password login with your mail and any password then follow the procedure'));
414 }
415
416 //With post method
417 if ($request->isMethod('POST')) {
418 //Refill the fields in case the form is not valid.
419 $edit->handleRequest($request);
420
421 //With edit submitted and valid
422 if ($edit->isSubmitted() && $edit->isValid()) {
423 //Set data
424 $data = $edit->getData();
425
426 //Set updated
427 $data->setUpdated(new \DateTime('now'));
428
429 //Queue snippet save
430 $manager->persist($data);
431
432 //Flush to get the ids
433 $manager->flush();
434
435 //Add notice
436 $this->addFlash('notice', $this->translator->trans('Account %mail% updated', ['%mail%' => $mail = $data->getMail()]));
437
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']);
441 }
442 }
443
444 //Render view
445 return $this->render(
446 //Template
447 $this->config['edit']['view']['name'],
448 //Context
449 ['edit' => $edit->createView(), 'sent' => $request->query->get('sent', 0)]+$this->config['edit']['view']['context']
450 );
451 }
452
453 /**
454 * Login
455 *
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
463 */
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,
471 //Set method
472 'method' => 'POST'
473 ]);
474
475 //Init context
476 $context = [];
477
478 //With mail
479 if (!empty($mail) && !empty($hash)) {
480 //With invalid hash
481 if ($hash != $slugger->hash($mail)) {
482 //Throw bad request
483 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash]));
484 }
485
486 //Get mail
487 $mail = $slugger->unshort($smail = $mail);
488
489 //Without valid mail
490 if (filter_var($mail, FILTER_VALIDATE_EMAIL) === false) {
491 //Throw bad request
492 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'mail', '%value%' => $smail]));
493 }
494
495 //Prefilled mail
496 $login->get('mail')->setData($mail);
497 //Last username entered by the user
498 } elseif ($lastUsername = $authenticationUtils->getLastUsername()) {
499 $login->get('mail')->setData($lastUsername);
500 }
501
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());
506
507 //Add error message to mail field
508 $login->get('mail')->addError(new FormError($error));
509
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']),
514 //Without password
515 'password' => false,
516 //Set method
517 'method' => 'POST'
518 ]);
519
520 //Get recover mail entity
521 $recover->get('mail')
522 //Set mail from login form
523 ->setData($login->get('mail')->getData())
524 //Add recover error
525 ->addError(new FormError($this->translator->trans('Use this form to recover your account')));
526
527 //Add recover form to context
528 $context['recover'] = $recover->createView();
529 } else {
530 //Add notice
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'));
533 }
534
535 //Render view
536 return $this->render(
537 //Template
538 $this->config['login']['view']['name'],
539 //Context
540 ['login' => $login->createView()]+$context+$this->config['login']['view']['context']
541 );
542 }
543
544 /**
545 * Recover account
546 *
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
557 */
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']),
565 //Without password
566 'password' => false,
567 //Set method
568 'method' => 'POST'
569 ]);
570
571 if ($request->isMethod('POST')) {
572 //Refill the fields in case the form is not valid.
573 $form->handleRequest($request);
574
575 if ($form->isValid()) {
576 //Set data
577 $data = $form->getData();
578
579 //Find user by data mail
580 if ($user = $doctrine->getRepository($this->config['class']['user'])->findOneByMail($data['mail'])) {
581 //Set mail shortcut
582 $recoverMail =& $this->config['recover']['mail'];
583
584 //Set mail
585 $mail = $slugger->short($user->getMail());
586
587 //Set pass
588 $pass = $slugger->hash($user->getPassword());
589
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
600 [
601 'mail' => $mail,
602 'pass' => $pass,
603 'hash' => $slugger->hash($mail.$pass)
604 ]+$this->config['route'][$route]['context'],
605 UrlGeneratorInterface::ABSOLUTE_URL
606 );
607 }
608 }
609 }
610
611 //Set recipient_name
612 $recoverMail['context']['recipient_mail'] = $user->getMail();
613
614 //Set recipient_name
615 $recoverMail['context']['recipient_name'] = trim($user->getForename().' '.$user->getSurname().($user->getPseudonym()?' ('.$user->getPseudonym().')':''));
616
617 //Init subject context
618 $subjectContext = $slugger->flatten(array_replace_recursive($this->config['recover']['view']['context'], $recoverMail['context']), null, '.', '%', '%');
619
620 //Translate subject
621 $recoverMail['subject'] = ucfirst($this->translator->trans($recoverMail['subject'], $subjectContext));
622
623 //Create message
624 $message = (new TemplatedEmail())
625 //Set sender
626 ->from(new Address($this->config['contact']['mail'], $this->config['contact']['title']))
627 //Set recipient
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']))
630 //Set subject
631 ->subject($recoverMail['subject'])
632
633 //Set path to twig templates
634 ->htmlTemplate($recoverMail['html'])
635 ->textTemplate($recoverMail['text'])
636
637 //Set context
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']]));
641
642 //Try sending message
643 //XXX: mail delivery may silently fail
644 try {
645 //Send message
646 $mailer->send($message);
647
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']))));
654 }
655 //Accout not found
656 } else {
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']])));
659 }
660 }
661 }
662
663 //Render view
664 return $this->render(
665 //Template
666 $this->config['recover']['view']['name'],
667 //Context
668 ['form' => $form->createView(), 'sent' => $request->query->get('sent', 0)]+$this->config['recover']['view']['context']
669 );
670 }
671
672 //With invalid hash
673 if ($hash != $slugger->hash($mail.$pass)) {
674 //Throw bad request
675 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash]));
676 }
677
678 //Get mail
679 $mail = $slugger->unshort($smail = $mail);
680
681 //Without valid mail
682 if (filter_var($mail, FILTER_VALIDATE_EMAIL) === false) {
683 //Throw bad request
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]));
686 }
687
688 //With existing subscriber
689 if (empty($user = $doctrine->getRepository($this->config['class']['user'])->findOneByMail($mail))) {
690 //Throw not found
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]));
693 }
694
695 //With unmatched pass
696 if ($pass != $slugger->hash($user->getPassword())) {
697 //Throw not found
698 //XXX: prevent use of outdated recover link
699 throw $this->createNotFoundException($this->translator->trans('Outdated recover link'));
700 }
701
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']),
706 //Without mail
707 'mail' => false,
708 //Set method
709 'method' => 'POST'
710 ]);
711
712 if ($request->isMethod('POST')) {
713 //Refill the fields in case the form is not valid.
714 $form->handleRequest($request);
715
716 if ($form->isValid()) {
717 //Set data
718 $data = $form->getData();
719
720 //Set encoded password
721 $encoded = $encoder->encodePassword($user, $user->getPassword());
722
723 //Update pass
724 $pass = $slugger->hash($encoded);
725
726 //Set user password
727 $user->setPassword($encoded);
728
729 //Set updated
730 $user->setUpdated(new \DateTime('now'));
731
732 //Persist user
733 $manager->persist($user);
734
735 //Send to database
736 $manager->flush();
737
738 //Add notice
739 $this->addFlash('notice', $this->translator->trans('Account %mail% password updated', ['%mail%' => $mail]));
740
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']);
743 }
744 }
745
746 //Render view
747 return $this->render(
748 //Template
749 $this->config['recover']['view']['name'],
750 //Context
751 ['form' => $form->createView(), 'sent' => $request->query->get('sent', 0)]+$this->config['recover']['view']['context']
752 );
753 }
754
755 /**
756 * Register an account
757 *
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
769 */
770 public function register(Request $request, Registry $doctrine, UserPasswordEncoderInterface $encoder, EntityManagerInterface $manager, SluggerUtil $slugger, MailerInterface $mailer, LoggerInterface $logger, $mail, $field, $hash): Response {
771 //Init reflection
772 $reflection = new \ReflectionClass($this->config['class']['user']);
773
774 //Create new user
775 $user = $reflection->newInstance();
776
777 //With mail and field
778 if (!empty($field) && !empty($hash)) {
779 //With invalid hash
780 if ($hash != $slugger->hash($mail.$field)) {
781 //Throw bad request
782 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash]));
783 }
784
785 //With mail
786 if (!empty($mail)) {
787 //Get mail
788 $mail = $slugger->unshort($smail = $mail);
789
790 //Without valid mail
791 if (filter_var($mail, FILTER_VALIDATE_EMAIL) === false) {
792 //Throw bad request
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]));
795 }
796
797 //Set mail
798 $user->setMail($mail);
799 //Without mail
800 } else {
801 //Set smail
802 $smail = $mail;
803 }
804
805 //Try
806 try {
807 //Unshort then unserialize field
808 $field = $slugger->unserialize($sfield = $field);
809 //Catch type error
810 } catch (\Error|\Exception $e) {
811 //Throw bad request
812 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'field', '%value%' => $field]), $e);
813 }
814
815 //With non array field
816 if (!is_array($field)) {
817 //Throw bad request
818 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'field', '%value%' => $field]));
819 }
820 //Without field and hash
821 } else {
822 //Set smail
823 $smail = $mail;
824
825 //Set smail
826 $sfield = $sfield;
827
828 //Reset field
829 $field = [];
830 }
831
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']),
836 //Set civility class
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']),
840 //With mail
841 'mail' => true,
842 //Set method
843 'method' => 'POST'
844 ]);
845
846 if ($request->isMethod('POST')) {
847 //Refill the fields in case the form is not valid.
848 $form->handleRequest($request);
849
850 if ($form->isValid()) {
851 //Set data
852 $data = $form->getData();
853
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]));
858
859 //Redirect to user view
860 return $this->redirectToRoute(
861 $this->config['route']['edit']['name'],
862 [
863 'mail' => $smail = $slugger->short($mail),
864 'hash' => $slugger->hash($smail)
865 ]+$this->config['route']['edit']['context']
866 );
867 }
868
869 //Set mail shortcut
870 $registerMail =& $this->config['register']['mail'];
871
872 //Extract names and pseudonym from mail
873 $names = explode(' ', $pseudonym = ucwords(trim(preg_replace('/[^a-zA-Z]+/', ' ', current(explode('@', $data->getMail()))))));
874
875 //Set pseudonym
876 $user->setPseudonym($user->getPseudonym()??$pseudonym);
877
878 //Set forename
879 $user->setForename($user->getForename()??$names[0]);
880
881 //Set surname
882 $user->setSurname($user->getSurname()??$names[1]??$names[0]);
883
884 //Set password
885 $user->setPassword($encoder->encodePassword($user, $user->getPassword()??$data->getMail()));
886
887 //Set created
888 $user->setCreated(new \DateTime('now'));
889
890 //Set updated
891 $user->setUpdated(new \DateTime('now'));
892
893 //Persist user
894 $manager->persist($user);
895
896 //Iterate on default group
897 foreach($this->config['default']['group'] as $i => $groupTitle) {
898 //Fetch group
899 if (($group = $doctrine->getRepository($this->config['class']['group'])->findOneByTitle($groupTitle))) {
900 //Set default group
901 //XXX: see vendor/symfony/security-core/Role/Role.php
902 $user->addGroup($group);
903 //Group not found
904 } else {
905 //Throw exception
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));
908 }
909 }
910
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
921 [
922 'mail' => $smail = $slugger->short($data->getMail()),
923 'hash' => $slugger->hash($smail)
924 ]+$this->config['route'][$route]['context'],
925 UrlGeneratorInterface::ABSOLUTE_URL
926 );
927 }
928 }
929 }
930
931 //XXX: DEBUG: remove me
932 //die($registerMail['context']['confirm_url']);
933
934 //Log new user infos
935 //XXX: useless ???
936 $logger->emergency(
937 $this->translator->trans(
938 'newuser:mail=%mail%|locale=%locale%|confirm=%confirm%',
939 [
940 '%mail%' => $data->getMail(),
941 '%locale%' => $request->getLocale(),
942 '%confirm%' => $registerMail['context'][$this->config['register']['route']['confirm']]
943 ]
944 )
945 );
946
947 //Set recipient_name
948 $registerMail['context']['recipient_mail'] = $data->getMail();
949
950 //Set recipient name
951 $registerMail['context']['recipient_name'] = '';
952
953 //Set recipient name
954 $registerMail['context']['recipient_name'] = implode(' ', [$data->getForename(), $data->getSurname(), $data->getPseudonym()?'('.$data->getPseudonym().')':'']);
955
956 //Init subject context
957 $subjectContext = $slugger->flatten(array_replace_recursive($this->config['register']['view']['context'], $registerMail['context']), null, '.', '%', '%');
958
959 //Translate subject
960 $registerMail['subject'] = ucfirst($this->translator->trans($registerMail['subject'], $subjectContext));
961
962 //Create message
963 $message = (new TemplatedEmail())
964 //Set sender
965 ->from(new Address($this->config['contact']['mail'], $this->config['contact']['title']))
966 //Set recipient
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']))
969 //Set subject
970 ->subject($registerMail['subject'])
971
972 //Set path to twig templates
973 ->htmlTemplate($registerMail['html'])
974 ->textTemplate($registerMail['text'])
975
976 //Set context
977 ->context(['subject' => $registerMail['subject']]+$registerMail['context']);
978
979 //Try saving in database
980 try {
981 //Send to database
982 $manager->flush();
983
984 //Add error message mail already exists
985 $this->addFlash('notice', $this->translator->trans('Your account has been created'));
986
987 //Try sending message
988 //XXX: mail delivery may silently fail
989 try {
990 //Send message
991 $mailer->send($message);
992
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()])));
999 }
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]));
1004 }
1005 }
1006 }
1007
1008 //Render view
1009 return $this->render(
1010 //Template
1011 $this->config['register']['view']['name'],
1012 //Context
1013 ['form' => $form->createView(), 'sent' => $request->query->get('sent', 0)]+$this->config['register']['view']['context']
1014 );
1015 }
1016
1017 /**
1018 * {@inheritdoc}
1019 */
1020 public function getAlias(): string {
1021 return RapsysUserBundle::getAlias();
1022 }
1023 }