]> Raphaël G. Git Repositories - userbundle/blob - Controller/DefaultController.php
c6ac4be6927d5e6025fcd9d6e8e6eaee775ac76f
[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 return $this->redirectToRoute($this->config['route']['edit']['name'], ['mail' => $smail = $slugger->short($mail), 'hash' => $slugger->hash($smail)]+$this->config['route']['edit']['context']);
403 }
404 }
405
406 //Add reset view
407 $this->config['edit']['view']['context']['reset'] = $reset->createView();
408 //Without admin role
409 //XXX: prefer a reset on login to force user unspam action
410 } else {
411 //Add notice
412 $this->addFlash('notice', $this->translator->trans('To change your password login with your mail and any password then follow the procedure'));
413 }
414
415 //With post method
416 if ($request->isMethod('POST')) {
417 //Refill the fields in case the form is not valid.
418 $edit->handleRequest($request);
419
420 //With edit submitted and valid
421 if ($edit->isSubmitted() && $edit->isValid()) {
422 //Set data
423 $data = $edit->getData();
424
425 //Set updated
426 $data->setUpdated(new \DateTime('now'));
427
428 //Queue snippet save
429 $manager->persist($data);
430
431 //Flush to get the ids
432 $manager->flush();
433
434 //Add notice
435 $this->addFlash('notice', $this->translator->trans('Account %mail% updated', ['%mail%' => $mail = $data->getMail()]));
436
437 //Redirect to cleanup the form
438 return $this->redirectToRoute($this->config['route']['edit']['name'], ['mail' => $smail = $slugger->short($mail), 'hash' => $slugger->hash($smail)]+$this->config['route']['edit']['context']);
439 }
440 }
441
442 //Render view
443 return $this->render(
444 //Template
445 $this->config['edit']['view']['name'],
446 //Context
447 ['edit' => $edit->createView(), 'sent' => $request->query->get('sent', 0)]+$this->config['edit']['view']['context']
448 );
449 }
450
451 /**
452 * Login
453 *
454 * @param Request $request The request
455 * @param AuthenticationUtils $authenticationUtils The authentication utils
456 * @param RouterInterface $router The router instance
457 * @param SluggerUtil $slugger The slugger
458 * @param string $mail The shorted mail address
459 * @param string $hash The hashed password
460 * @return Response The response
461 */
462 public function login(Request $request, AuthenticationUtils $authenticationUtils, RouterInterface $router, SluggerUtil $slugger, $mail, $hash): Response {
463 //Create the LoginType form and give the proper parameters
464 $login = $this->createForm($this->config['login']['view']['form'], null, [
465 //Set action to login route name and context
466 'action' => $this->generateUrl($this->config['route']['login']['name'], $this->config['route']['login']['context']),
467 //Disable repeated password
468 'password_repeated' => false,
469 //Set method
470 'method' => 'POST'
471 ]);
472
473 //Init context
474 $context = [];
475
476 //With mail
477 if (!empty($mail) && !empty($hash)) {
478 //With invalid hash
479 if ($hash != $slugger->hash($mail)) {
480 //Throw bad request
481 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash]));
482 }
483
484 //Get mail
485 $mail = $slugger->unshort($smail = $mail);
486
487 //Without valid mail
488 if (filter_var($mail, FILTER_VALIDATE_EMAIL) === false) {
489 //Throw bad request
490 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'mail', '%value%' => $smail]));
491 }
492
493 //Prefilled mail
494 $login->get('mail')->setData($mail);
495 //Last username entered by the user
496 } elseif ($lastUsername = $authenticationUtils->getLastUsername()) {
497 $login->get('mail')->setData($lastUsername);
498 }
499
500 //Get the login error if there is one
501 if ($error = $authenticationUtils->getLastAuthenticationError()) {
502 //Get translated error
503 $error = $this->translator->trans($error->getMessageKey());
504
505 //Add error message to mail field
506 $login->get('mail')->addError(new FormError($error));
507
508 //Create the LoginType form and give the proper parameters
509 $recover = $this->createForm($this->config['recover']['view']['form'], null, [
510 //Set action to recover route name and context
511 'action' => $this->generateUrl($this->config['route']['recover']['name'], $this->config['route']['recover']['context']),
512 //Without password
513 'password' => false,
514 //Set method
515 'method' => 'POST'
516 ]);
517
518 //Get recover mail entity
519 $recover->get('mail')
520 //Set mail from login form
521 ->setData($login->get('mail')->getData())
522 //Add recover error
523 ->addError(new FormError($this->translator->trans('Use this form to recover your account')));
524
525 //Add recover form to context
526 $context['recover'] = $recover->createView();
527 } else {
528 //Add notice
529 $this->addFlash('notice', $this->translator->trans('To change your password login with your mail and any password then follow the procedure'));
530 }
531
532 //Render view
533 return $this->render(
534 //Template
535 $this->config['login']['view']['name'],
536 //Context
537 ['login' => $login->createView()]+$context+$this->config['login']['view']['context']
538 );
539 }
540
541 /**
542 * Recover account
543 *
544 * @param Request $request The request
545 * @param Registry $manager The doctrine registry
546 * @param UserPasswordEncoderInterface $encoder The password encoder
547 * @param EntityManagerInterface $manager The doctrine entity manager
548 * @param SluggerUtil $slugger The slugger
549 * @param MailerInterface $mailer The mailer
550 * @param string $mail The shorted mail address
551 * @param string $pass The shorted password
552 * @param string $hash The hashed password
553 * @return Response The response
554 */
555 public function recover(Request $request, Registry $doctrine, UserPasswordEncoderInterface $encoder, EntityManagerInterface $manager, SluggerUtil $slugger, MailerInterface $mailer, $mail, $pass, $hash): Response {
556 //Without mail, pass and hash
557 if (empty($mail) && empty($pass) && empty($hash)) {
558 //Create the LoginType form and give the proper parameters
559 $form = $this->createForm($this->config['recover']['view']['form'], null, [
560 //Set action to recover route name and context
561 'action' => $this->generateUrl($this->config['route']['recover']['name'], $this->config['route']['recover']['context']),
562 //Without password
563 'password' => false,
564 //Set method
565 'method' => 'POST'
566 ]);
567
568 if ($request->isMethod('POST')) {
569 //Refill the fields in case the form is not valid.
570 $form->handleRequest($request);
571
572 if ($form->isValid()) {
573 //Set data
574 $data = $form->getData();
575
576 //Find user by data mail
577 if ($user = $doctrine->getRepository($this->config['class']['user'])->findOneByMail($data['mail'])) {
578 //Set mail shortcut
579 $recoverMail =& $this->config['recover']['mail'];
580
581 //Set mail
582 $mail = $slugger->short($user->getMail());
583
584 //Set pass
585 $pass = $slugger->hash($user->getPassword());
586
587 //Generate each route route
588 foreach($this->config['recover']['route'] as $route => $tag) {
589 //Only process defined routes
590 if (!empty($this->config['route'][$route])) {
591 //Process for recover mail url
592 if ($route == 'recover') {
593 //Set the url in context
594 $recoverMail['context'][$tag] = $this->get('router')->generate(
595 $this->config['route'][$route]['name'],
596 //Prepend recover context with tag
597 [
598 'mail' => $mail,
599 'pass' => $pass,
600 'hash' => $slugger->hash($mail.$pass)
601 ]+$this->config['route'][$route]['context'],
602 UrlGeneratorInterface::ABSOLUTE_URL
603 );
604 }
605 }
606 }
607
608 //Set recipient_name
609 $recoverMail['context']['recipient_mail'] = $user->getMail();
610
611 //Set recipient_name
612 $recoverMail['context']['recipient_name'] = trim($user->getForename().' '.$user->getSurname().($user->getPseudonym()?' ('.$user->getPseudonym().')':''));
613
614 //Init subject context
615 $subjectContext = $slugger->flatten(array_replace_recursive($this->config['recover']['view']['context'], $recoverMail['context']), null, '.', '%', '%');
616
617 //Translate subject
618 $recoverMail['subject'] = ucfirst($this->translator->trans($recoverMail['subject'], $subjectContext));
619
620 //Create message
621 $message = (new TemplatedEmail())
622 //Set sender
623 ->from(new Address($this->config['contact']['mail'], $this->config['contact']['title']))
624 //Set recipient
625 //XXX: remove the debug set in vendor/symfony/mime/Address.php +46
626 ->to(new Address($recoverMail['context']['recipient_mail'], $recoverMail['context']['recipient_name']))
627 //Set subject
628 ->subject($recoverMail['subject'])
629
630 //Set path to twig templates
631 ->htmlTemplate($recoverMail['html'])
632 ->textTemplate($recoverMail['text'])
633
634 //Set context
635 //XXX: require recursive merge to avoid loosing subkeys
636 //['subject' => $recoverMail['subject']]+$recoverMail['context']+$this->config['recover']['view']['context']
637 ->context(array_replace_recursive($this->config['recover']['view']['context'], $recoverMail['context'], ['subject' => $recoverMail['subject']]));
638
639 //Try sending message
640 //XXX: mail delivery may silently fail
641 try {
642 //Send message
643 $mailer->send($message);
644
645 //Redirect on the same route with sent=1 to cleanup form
646 return $this->redirectToRoute($request->get('_route'), ['sent' => 1]+$request->get('_route_params'));
647 //Catch obvious transport exception
648 } catch(TransportExceptionInterface $e) {
649 //Add error message mail unreachable
650 $form->get('mail')->addError(new FormError($this->translator->trans('Account found but unable to contact: %mail%', array('%mail%' => $data['mail']))));
651 }
652 //Accout not found
653 } else {
654 //Add error message to mail field
655 $form->get('mail')->addError(new FormError($this->translator->trans('Unable to find account %mail%', ['%mail%' => $data['mail']])));
656 }
657 }
658 }
659
660 //Render view
661 return $this->render(
662 //Template
663 $this->config['recover']['view']['name'],
664 //Context
665 ['form' => $form->createView(), 'sent' => $request->query->get('sent', 0)]+$this->config['recover']['view']['context']
666 );
667 }
668
669 //With invalid hash
670 if ($hash != $slugger->hash($mail.$pass)) {
671 //Throw bad request
672 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash]));
673 }
674
675 //Get mail
676 $mail = $slugger->unshort($smail = $mail);
677
678 //Without valid mail
679 if (filter_var($mail, FILTER_VALIDATE_EMAIL) === false) {
680 //Throw bad request
681 //XXX: prevent slugger reverse engineering by not displaying decoded mail
682 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'mail', '%value%' => $smail]));
683 }
684
685 //With existing subscriber
686 if (empty($user = $doctrine->getRepository($this->config['class']['user'])->findOneByMail($mail))) {
687 //Throw not found
688 //XXX: prevent slugger reverse engineering by not displaying decoded mail
689 throw $this->createNotFoundException($this->translator->trans('Unable to find account %mail%', ['%mail%' => $smail]));
690 }
691
692 //With unmatched pass
693 if ($pass != $slugger->hash($user->getPassword())) {
694 //Throw not found
695 //XXX: prevent use of outdated recover link
696 throw $this->createNotFoundException($this->translator->trans('Outdated recover link'));
697 }
698
699 //Create the LoginType form and give the proper parameters
700 $form = $this->createForm($this->config['recover']['view']['form'], $user, [
701 //Set action to recover route name and context
702 'action' => $this->generateUrl($this->config['route']['recover']['name'], ['mail' => $smail, 'pass' => $pass, 'hash' => $hash]+$this->config['route']['recover']['context']),
703 //Without mail
704 'mail' => false,
705 //Set method
706 'method' => 'POST'
707 ]);
708
709 if ($request->isMethod('POST')) {
710 //Refill the fields in case the form is not valid.
711 $form->handleRequest($request);
712
713 if ($form->isValid()) {
714 //Set data
715 $data = $form->getData();
716
717 //Set encoded password
718 $encoded = $encoder->encodePassword($user, $user->getPassword());
719
720 //Update pass
721 $pass = $slugger->hash($encoded);
722
723 //Set user password
724 $user->setPassword($encoded);
725
726 //Set updated
727 $user->setUpdated(new \DateTime('now'));
728
729 //Persist user
730 $manager->persist($user);
731
732 //Send to database
733 $manager->flush();
734
735 //Add notice
736 $this->addFlash('notice', $this->translator->trans('Account %mail% password updated', ['%mail%' => $mail]));
737
738 //Redirect to user login
739 return $this->redirectToRoute($this->config['route']['login']['name'], ['mail' => $smail, 'hash' => $slugger->hash($smail)]+$this->config['route']['login']['context']);
740 }
741 }
742
743 //Render view
744 return $this->render(
745 //Template
746 $this->config['recover']['view']['name'],
747 //Context
748 ['form' => $form->createView(), 'sent' => $request->query->get('sent', 0)]+$this->config['recover']['view']['context']
749 );
750 }
751
752 /**
753 * Register an account
754 *
755 * @param Request $request The request
756 * @param Registry $manager The doctrine registry
757 * @param UserPasswordEncoderInterface $encoder The password encoder
758 * @param EntityManagerInterface $manager The doctrine entity manager
759 * @param SluggerUtil $slugger The slugger
760 * @param MailerInterface $mailer The mailer
761 * @param LoggerInterface $logger The logger
762 * @param string $mail The shorted mail address
763 * @param string $field The serialized then shorted form field array
764 * @param string $hash The hashed serialized field array
765 * @return Response The response
766 */
767 public function register(Request $request, Registry $doctrine, UserPasswordEncoderInterface $encoder, EntityManagerInterface $manager, SluggerUtil $slugger, MailerInterface $mailer, LoggerInterface $logger, $mail, $field, $hash): Response {
768 //Init reflection
769 $reflection = new \ReflectionClass($this->config['class']['user']);
770
771 //Create new user
772 $user = $reflection->newInstance();
773
774 //With mail and field
775 if (!empty($field) && !empty($hash)) {
776 //With invalid hash
777 if ($hash != $slugger->hash($mail.$field)) {
778 //Throw bad request
779 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash]));
780 }
781
782 //With mail
783 if (!empty($mail)) {
784 //Get mail
785 $mail = $slugger->unshort($smail = $mail);
786
787 //Without valid mail
788 if (filter_var($mail, FILTER_VALIDATE_EMAIL) === false) {
789 //Throw bad request
790 //XXX: prevent slugger reverse engineering by not displaying decoded mail
791 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'mail', '%value%' => $smail]));
792 }
793
794 //Set mail
795 $user->setMail($mail);
796 //Without mail
797 } else {
798 //Set smail
799 $smail = $mail;
800 }
801
802 //Try
803 try {
804 //Unshort then unserialize field
805 $field = $slugger->unserialize($sfield = $field);
806 //Catch type error
807 } catch (\Error|\Exception $e) {
808 //Throw bad request
809 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'field', '%value%' => $field]), $e);
810 }
811
812 //With non array field
813 if (!is_array($field)) {
814 //Throw bad request
815 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'field', '%value%' => $field]));
816 }
817 //Without field and hash
818 } else {
819 //Set smail
820 $smail = $mail;
821
822 //Set smail
823 $sfield = $sfield;
824
825 //Reset field
826 $field = [];
827 }
828
829 //Create the RegisterType form and give the proper parameters
830 $form = $this->createForm($this->config['register']['view']['form'], $user, $field+[
831 //Set action to register route name and context
832 'action' => $this->generateUrl($this->config['route']['register']['name'], ['mail' => $smail, 'field' => $sfield, 'hash' => $hash]+$this->config['route']['register']['context']),
833 //Set civility class
834 'civility_class' => $this->config['class']['civility'],
835 //Set civility default
836 'civility_default' => $doctrine->getRepository($this->config['class']['civility'])->findOneByTitle($this->config['default']['civility']),
837 //With mail
838 'mail' => true,
839 //Set method
840 'method' => 'POST'
841 ]);
842
843 if ($request->isMethod('POST')) {
844 //Refill the fields in case the form is not valid.
845 $form->handleRequest($request);
846
847 if ($form->isValid()) {
848 //Set data
849 $data = $form->getData();
850
851 //With existing registrant
852 if ($doctrine->getRepository($this->config['class']['user'])->findOneByMail($mail = $data->getMail())) {
853 //Add error message mail already exists
854 $this->addFlash('warning', $this->translator->trans('Account %mail% already exists', ['%mail%' => $mail]));
855
856 //Redirect to user view
857 return $this->redirectToRoute(
858 $this->config['route']['edit']['name'],
859 [
860 'mail' => $smail = $slugger->short($mail),
861 'hash' => $slugger->hash($smail)
862 ]+$this->config['route']['edit']['context']
863 );
864 }
865
866 //Set mail shortcut
867 $registerMail =& $this->config['register']['mail'];
868
869 //Extract names and pseudonym from mail
870 $names = explode(' ', $pseudonym = ucwords(trim(preg_replace('/[^a-zA-Z]+/', ' ', current(explode('@', $data->getMail()))))));
871
872 //Set pseudonym
873 $user->setPseudonym($user->getPseudonym()??$pseudonym);
874
875 //Set forename
876 $user->setForename($user->getForename()??$names[0]);
877
878 //Set surname
879 $user->setSurname($user->getSurname()??$names[1]??$names[0]);
880
881 //Set password
882 $user->setPassword($encoder->encodePassword($user, $user->getPassword()??$data->getMail()));
883
884 //Set created
885 $user->setCreated(new \DateTime('now'));
886
887 //Set updated
888 $user->setUpdated(new \DateTime('now'));
889
890 //Persist user
891 $manager->persist($user);
892
893 //Iterate on default group
894 foreach($this->config['default']['group'] as $i => $groupTitle) {
895 //Fetch group
896 if (($group = $doctrine->getRepository($this->config['class']['group'])->findOneByTitle($groupTitle))) {
897 //Set default group
898 //XXX: see vendor/symfony/security-core/Role/Role.php
899 $user->addGroup($group);
900 //Group not found
901 } else {
902 //Throw exception
903 //XXX: consider missing group as fatal
904 throw new \Exception(sprintf('Group from rapsys_user.default.group[%d] not found by title: %s', $i, $groupTitle));
905 }
906 }
907
908 //Generate each route route
909 foreach($this->config['register']['route'] as $route => $tag) {
910 //Only process defined routes
911 if (!empty($this->config['route'][$route])) {
912 //Process for confirm url
913 if ($route == 'confirm') {
914 //Set the url in context
915 $registerMail['context'][$tag] = $this->get('router')->generate(
916 $this->config['route'][$route]['name'],
917 //Prepend subscribe context with tag
918 [
919 'mail' => $smail = $slugger->short($data->getMail()),
920 'hash' => $slugger->hash($smail)
921 ]+$this->config['route'][$route]['context'],
922 UrlGeneratorInterface::ABSOLUTE_URL
923 );
924 }
925 }
926 }
927
928 //XXX: DEBUG: remove me
929 //die($registerMail['context']['confirm_url']);
930
931 //Log new user infos
932 //XXX: useless ???
933 $logger->emergency(
934 $this->translator->trans(
935 'newuser:mail=%mail%|locale=%locale%|confirm=%confirm%',
936 [
937 '%mail%' => $data->getMail(),
938 '%locale%' => $request->getLocale(),
939 '%confirm%' => $registerMail['context'][$this->config['register']['route']['confirm']]
940 ]
941 )
942 );
943
944 //Set recipient_name
945 $registerMail['context']['recipient_mail'] = $data->getMail();
946
947 //Set recipient name
948 $registerMail['context']['recipient_name'] = '';
949
950 //Set recipient name
951 $registerMail['context']['recipient_name'] = implode(' ', [$data->getForename(), $data->getSurname(), $data->getPseudonym()?'('.$data->getPseudonym().')':'']);
952
953 //Init subject context
954 $subjectContext = $slugger->flatten(array_replace_recursive($this->config['register']['view']['context'], $registerMail['context']), null, '.', '%', '%');
955
956 //Translate subject
957 $registerMail['subject'] = ucfirst($this->translator->trans($registerMail['subject'], $subjectContext));
958
959 //Create message
960 $message = (new TemplatedEmail())
961 //Set sender
962 ->from(new Address($this->config['contact']['mail'], $this->config['contact']['title']))
963 //Set recipient
964 //XXX: remove the debug set in vendor/symfony/mime/Address.php +46
965 ->to(new Address($registerMail['context']['recipient_mail'], $registerMail['context']['recipient_name']))
966 //Set subject
967 ->subject($registerMail['subject'])
968
969 //Set path to twig templates
970 ->htmlTemplate($registerMail['html'])
971 ->textTemplate($registerMail['text'])
972
973 //Set context
974 ->context(['subject' => $registerMail['subject']]+$registerMail['context']);
975
976 //Try saving in database
977 try {
978 //Send to database
979 $manager->flush();
980
981 //Add error message mail already exists
982 $this->addFlash('notice', $this->translator->trans('Your account has been created'));
983
984 //Try sending message
985 //XXX: mail delivery may silently fail
986 try {
987 //Send message
988 $mailer->send($message);
989
990 //Redirect on the same route with sent=1 to cleanup form
991 return $this->redirectToRoute($request->get('_route'), ['sent' => 1]+$request->get('_route_params'));
992 //Catch obvious transport exception
993 } catch(TransportExceptionInterface $e) {
994 //Add error message mail unreachable
995 $form->get('mail')->addError(new FormError($this->translator->trans('Account %mail% tried subscribe but unable to contact', ['%mail%' => $data->getMail()])));
996 }
997 //Catch double subscription
998 } catch (\Doctrine\DBAL\Exception\UniqueConstraintViolationException $e) {
999 //Add error message mail already exists
1000 $this->addFlash('error', $this->translator->trans('Account %mail% already exists', ['%mail%' => $mail]));
1001 }
1002 }
1003 }
1004
1005 //Render view
1006 return $this->render(
1007 //Template
1008 $this->config['register']['view']['name'],
1009 //Context
1010 ['form' => $form->createView(), 'sent' => $request->query->get('sent', 0)]+$this->config['register']['view']['context']
1011 );
1012 }
1013
1014 /**
1015 * {@inheritdoc}
1016 */
1017 public function getAlias(): string {
1018 return RapsysUserBundle::getAlias();
1019 }
1020 }