]> Raphaël G. Git Repositories - userbundle/blob - Controller/DefaultController.php
Fix variable name
[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\Generator\UrlGeneratorInterface;
28 use Symfony\Component\Routing\RouterInterface;
29 use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
30 use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
31 use Symfony\Component\Translation\TranslatorInterface;
32
33 use Rapsys\PackBundle\Util\SluggerUtil;
34 use Rapsys\UserBundle\RapsysUserBundle;
35
36 class DefaultController extends AbstractController {
37 //Config array
38 protected $config;
39
40 //Translator instance
41 protected $translator;
42
43 /**
44 * Constructor
45 *
46 * @TODO: move all canonical and other view related stuff in an user AbstractController like in RapsysAir render feature !!!!
47 *
48 * @param ContainerInterface $container The containter instance
49 * @param RouterInterface $router The router instance
50 * @param TranslatorInterface $translator The translator instance
51 */
52 public function __construct(ContainerInterface $container, RouterInterface $router, TranslatorInterface $translator) {
53 //Retrieve config
54 $this->config = $container->getParameter(self::getAlias());
55
56 //Set the translator
57 $this->translator = $translator;
58
59 //Get request stack
60 $stack = $container->get('request_stack');
61
62 //Get current request
63 $request = $stack->getCurrentRequest();
64
65 //Get current locale
66 $currentLocale = $request->getLocale();
67
68 //Set locale
69 $this->config['context']['locale'] = str_replace('_', '-', $currentLocale);
70
71 //Set translate array
72 $translates = [];
73
74 //Look for keys to translate
75 if (!empty($this->config['translate'])) {
76 //Iterate on keys to translate
77 foreach($this->config['translate'] as $translate) {
78 //Set tmp
79 $tmp = null;
80 //Iterate on keys
81 foreach(array_reverse(explode('.', $translate)) as $curkey) {
82 $tmp = array_combine([$curkey], [$tmp]);
83 }
84 //Append tree
85 $translates = array_replace_recursive($translates, $tmp);
86 }
87 }
88
89 //Inject every requested route in view and mail context
90 foreach($this->config as $tag => $current) {
91 //Look for entry with title subkey
92 if (!empty($current['title'])) {
93 //Translate title value
94 $this->config[$tag]['title'] = $translator->trans($current['title']);
95 }
96
97 //Look for entry with route subkey
98 if (!empty($current['route'])) {
99 //Generate url for both view and mail
100 foreach(['view', 'mail'] as $view) {
101 //Check that context key is usable
102 if (isset($current[$view]['context']) && is_array($current[$view]['context'])) {
103 //Merge with global context
104 $this->config[$tag][$view]['context'] = array_replace_recursive($this->config['context'], $this->config[$tag][$view]['context']);
105
106 //Process every routes
107 foreach($current['route'] as $route => $key) {
108 //With confirm route
109 if ($route == 'confirm') {
110 //Skip route as it requires some parameters
111 continue;
112 }
113
114 //Set value
115 $value = $router->generate(
116 $this->config['route'][$route]['name'],
117 $this->config['route'][$route]['context'],
118 //Generate absolute url for mails
119 $view=='mail'?UrlGeneratorInterface::ABSOLUTE_URL:UrlGeneratorInterface::ABSOLUTE_PATH
120 );
121
122 //Multi level key
123 if (strpos($key, '.') !== false) {
124 //Set tmp
125 $tmp = $value;
126
127 //Iterate on key
128 foreach(array_reverse(explode('.', $key)) as $curkey) {
129 $tmp = array_combine([$curkey], [$tmp]);
130 }
131
132 //Set value
133 $this->config[$tag][$view]['context'] = array_replace_recursive($this->config[$tag][$view]['context'], $tmp);
134 //Single level key
135 } else {
136 //Set value
137 $this->config[$tag][$view]['context'][$key] = $value;
138 }
139 }
140
141 //Look for successful intersections
142 if (!empty(array_intersect_key($translates, $this->config[$tag][$view]['context']))) {
143 //Iterate on keys to translate
144 foreach($this->config['translate'] as $translate) {
145 //Set keys
146 $keys = explode('.', $translate);
147
148 //Set tmp
149 $tmp = $this->config[$tag][$view]['context'];
150
151 //Iterate on keys
152 foreach($keys as $curkey) {
153 //Without child key
154 if (!isset($tmp[$curkey])) {
155 //Skip to next key
156 continue(2);
157 }
158
159 //Get child key
160 $tmp = $tmp[$curkey];
161 }
162
163 //Translate tmp value
164 $tmp = $translator->trans($tmp);
165
166 //Iterate on keys
167 foreach(array_reverse($keys) as $curkey) {
168 //Set parent key
169 $tmp = array_combine([$curkey], [$tmp]);
170 }
171
172 //Set value
173 $this->config[$tag][$view]['context'] = array_replace_recursive($this->config[$tag][$view]['context'], $tmp);
174 }
175 }
176
177 //With view context
178 if ($view == 'view') {
179 //Get context path
180 $pathInfo = $router->getContext()->getPathInfo();
181
182 //Iterate on locales excluding current one
183 foreach($this->config['locales'] as $locale) {
184 //Set titles
185 $titles = [];
186
187 //Iterate on other locales
188 foreach(array_diff($this->config['locales'], [$locale]) as $other) {
189 $titles[$other] = $translator->trans($this->config['languages'][$locale], [], null, $other);
190 }
191
192 //Retrieve route matching path
193 $route = $router->match($pathInfo);
194
195 //Get route name
196 $name = $route['_route'];
197
198 //Unset route name
199 unset($route['_route']);
200
201 //With current locale
202 if ($locale == $currentLocale) {
203 //Set locale locales context
204 $this->config[$tag][$view]['context']['canonical'] = $router->generate($name, ['_locale' => $locale]+$route, UrlGeneratorInterface::ABSOLUTE_URL);
205 } else {
206 //Set locale locales context
207 $this->config[$tag][$view]['context']['alternates'][$locale] = [
208 'absolute' => $router->generate($name, ['_locale' => $locale]+$route, UrlGeneratorInterface::ABSOLUTE_URL),
209 'relative' => $router->generate($name, ['_locale' => $locale]+$route),
210 'title' => implode('/', $titles),
211 'translated' => $translator->trans($this->config['languages'][$locale], [], null, $locale)
212 ];
213 }
214
215 //Add shorter locale
216 if (empty($this->config[$tag][$view]['context']['alternates'][$slocale = substr($locale, 0, 2)])) {
217 //Add shorter locale
218 $this->config[$tag][$view]['context']['alternates'][$slocale] = [
219 'absolute' => $router->generate($name, ['_locale' => $locale]+$route, UrlGeneratorInterface::ABSOLUTE_URL),
220 'relative' => $router->generate($name, ['_locale' => $locale]+$route),
221 'title' => implode('/', $titles),
222 'translated' => $translator->trans($this->config['languages'][$locale], [], null, $locale)
223 ];
224 }
225 }
226 }
227 }
228 }
229 }
230 }
231 }
232
233 /**
234 * Confirm account from mail link
235 *
236 * @param Request $request The request
237 * @param Registry $manager The doctrine registry
238 * @param UserPasswordEncoderInterface $encoder The password encoder
239 * @param EntityManagerInterface $manager The doctrine entity manager
240 * @param SluggerUtil $slugger The slugger
241 * @param MailerInterface $mailer The mailer
242 * @param string $mail The shorted mail address
243 * @param string $hash The hashed password
244 * @return Response The response
245 */
246 public function confirm(Request $request, Registry $doctrine, UserPasswordEncoderInterface $encoder, EntityManagerInterface $manager, SluggerUtil $slugger, MailerInterface $mailer, $mail, $hash): Response {
247 //With invalid hash
248 if ($hash != $slugger->hash($mail)) {
249 //Throw bad request
250 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash]));
251 }
252
253 //Get mail
254 $mail = $slugger->unshort($smail = $mail);
255
256 //Without valid mail
257 if (filter_var($mail, FILTER_VALIDATE_EMAIL) === false) {
258 //Throw bad request
259 //XXX: prevent slugger reverse engineering by not displaying decoded mail
260 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'mail', '%value%' => $smail]));
261 }
262
263 //Without existing registrant
264 if (!($user = $doctrine->getRepository($this->config['class']['user'])->findOneByMail($mail))) {
265 //Add error message mail already exists
266 //XXX: prevent slugger reverse engineering by not displaying decoded mail
267 $this->addFlash('error', $this->translator->trans('Account %mail% do not exists', ['%mail%' => $smail]));
268
269 //Redirect to register view
270 return $this->redirectToRoute($this->config['route']['register']['name'], ['mail' => $smail, 'field' => $sfield = $slugger->serialize([]), 'hash' => $slugger->hash($smail.$sfield)]+$this->config['route']['register']['context']);
271 }
272
273 //Set active
274 $user->setActive(true);
275
276 //Persist user
277 $manager->persist($user);
278
279 //Send to database
280 $manager->flush();
281
282 //Add error message mail already exists
283 $this->addFlash('notice', $this->translator->trans('Your account has been activated'));
284
285 //Redirect to user view
286 return $this->redirectToRoute($this->config['route']['edit']['name'], ['mail' => $smail, 'hash' => $slugger->hash($smail)]+$this->config['route']['edit']['context']);
287 }
288
289 /**
290 * Edit account by shorted mail
291 *
292 * @param Request $request The request
293 * @param Registry $manager The doctrine registry
294 * @param UserPasswordEncoderInterface $encoder The password encoder
295 * @param EntityManagerInterface $manager The doctrine entity manager
296 * @param SluggerUtil $slugger The slugger
297 * @param string $mail The shorted mail address
298 * @param string $hash The hashed password
299 * @return Response The response
300 */
301 public function edit(Request $request, Registry $doctrine, UserPasswordEncoderInterface $encoder, EntityManagerInterface $manager, SluggerUtil $slugger, $mail, $hash): Response {
302 //With invalid hash
303 if ($hash != $slugger->hash($mail)) {
304 //Throw bad request
305 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash]));
306 }
307
308 //Get mail
309 $mail = $slugger->unshort($smail = $mail);
310
311 //With existing subscriber
312 if (empty($user = $doctrine->getRepository($this->config['class']['user'])->findOneByMail($mail))) {
313 //Throw not found
314 //XXX: prevent slugger reverse engineering by not displaying decoded mail
315 throw $this->createNotFoundException($this->translator->trans('Unable to find account %mail%', ['%mail%' => $smail]));
316 }
317
318 //Prevent access when not admin, user is not guest and not currently logged user
319 if (!$this->isGranted('ROLE_ADMIN') && $user != $this->getUser() || !$this->isGranted('IS_AUTHENTICATED_FULLY')) {
320 //Throw access denied
321 //XXX: prevent slugger reverse engineering by not displaying decoded mail
322 throw $this->createAccessDeniedException($this->translator->trans('Unable to access user: %mail%', ['%mail%' => $smail]));
323 }
324
325 //Create the RegisterType form and give the proper parameters
326 $editForm = $this->createForm($this->config['register']['view']['form'], $user, [
327 //Set action to register route name and context
328 'action' => $this->generateUrl($this->config['route']['edit']['name'], ['mail' => $smail, 'hash' => $slugger->hash($smail)]+$this->config['route']['edit']['context']),
329 //Set civility class
330 'civility_class' => $this->config['class']['civility'],
331 //Set civility default
332 'civility_default' => $doctrine->getRepository($this->config['class']['civility'])->findOneByTitle($this->config['default']['civility']),
333 //Disable mail
334 'mail' => $this->isGranted('ROLE_ADMIN'),
335 //Disable password
336 'password' => false,
337 //Set method
338 'method' => 'POST'
339 ]);
340
341 //Create the RegisterType form and give the proper parameters
342 $edit = $this->createForm($this->config['edit']['view']['edit'], $user, [
343 //Set action to register route name and context
344 'action' => $this->generateUrl($this->config['route']['edit']['name'], ['mail' => $smail, 'hash' => $slugger->hash($smail)]+$this->config['route']['edit']['context']),
345 //Set civility class
346 'civility_class' => $this->config['class']['civility'],
347 //Set civility default
348 'civility_default' => $doctrine->getRepository($this->config['class']['civility'])->findOneByTitle($this->config['default']['civility']),
349 //Disable mail
350 'mail' => $this->isGranted('ROLE_ADMIN'),
351 //Disable password
352 'password' => false,
353 //Set method
354 'method' => 'POST'
355 ]);
356
357 //With admin role
358 if ($this->isGranted('ROLE_ADMIN')) {
359 //Create the LoginType form and give the proper parameters
360 $reset = $this->createForm($this->config['edit']['view']['reset'], $user, [
361 //Set action to register route name and context
362 'action' => $this->generateUrl($this->config['route']['edit']['name'], ['mail' => $smail, 'hash' => $slugger->hash($smail)]+$this->config['route']['edit']['context']),
363 //Disable mail
364 'mail' => false,
365 //Set method
366 'method' => 'POST'
367 ]);
368
369 //With post method
370 if ($request->isMethod('POST')) {
371 //Refill the fields in case the form is not valid.
372 $reset->handleRequest($request);
373
374 //With reset submitted and valid
375 if ($reset->isSubmitted() && $reset->isValid()) {
376 //Set data
377 $data = $reset->getData();
378
379 //Set password
380 $data->setPassword($encoder->encodePassword($data, $data->getPassword()));
381
382 //Queue snippet save
383 $manager->persist($data);
384
385 //Flush to get the ids
386 $manager->flush();
387
388 //Add notice
389 $this->addFlash('notice', $this->translator->trans('Account %mail% password updated', ['%mail%' => $mail = $data->getMail()]));
390
391 //Redirect to cleanup the form
392 return $this->redirectToRoute($this->config['route']['edit']['name'], ['mail' => $smail = $slugger->short($mail), 'hash' => $slugger->hash($smail)]+$this->config['route']['edit']['context']);
393 }
394 }
395
396 //Add reset view
397 $this->config['edit']['view']['context']['reset'] = $reset->createView();
398 //Without admin role
399 //XXX: prefer a reset on login to force user unspam action
400 } else {
401 //Add notice
402 $this->addFlash('notice', $this->translator->trans('To change your password login with your mail and any password then follow the procedure'));
403 }
404
405 //With post method
406 if ($request->isMethod('POST')) {
407 //Refill the fields in case the form is not valid.
408 $edit->handleRequest($request);
409
410 //With edit submitted and valid
411 if ($edit->isSubmitted() && $edit->isValid()) {
412 //Set data
413 $data = $edit->getData();
414
415 //Queue snippet save
416 $manager->persist($data);
417
418 //Flush to get the ids
419 $manager->flush();
420
421 //Add notice
422 $this->addFlash('notice', $this->translator->trans('Account %mail% updated', ['%mail%' => $mail = $data->getMail()]));
423
424 //Redirect to cleanup the form
425 return $this->redirectToRoute($this->config['route']['edit']['name'], ['mail' => $smail = $slugger->short($mail), 'hash' => $slugger->hash($smail)]+$this->config['route']['edit']['context']);
426 }
427 }
428
429 //Render view
430 return $this->render(
431 //Template
432 $this->config['edit']['view']['name'],
433 //Context
434 ['edit' => $edit->createView(), 'sent' => $request->query->get('sent', 0)]+$this->config['edit']['view']['context']
435 );
436 }
437
438 /**
439 * Login
440 *
441 * @param Request $request The request
442 * @param AuthenticationUtils $authenticationUtils The authentication utils
443 * @param RouterInterface $router The router instance
444 * @param SluggerUtil $slugger The slugger
445 * @param string $mail The shorted mail address
446 * @param string $hash The hashed password
447 * @return Response The response
448 */
449 public function login(Request $request, AuthenticationUtils $authenticationUtils, RouterInterface $router, SluggerUtil $slugger, $mail, $hash): Response {
450 //Create the LoginType form and give the proper parameters
451 $login = $this->createForm($this->config['login']['view']['form'], null, [
452 //Set action to login route name and context
453 'action' => $this->generateUrl($this->config['route']['login']['name'], $this->config['route']['login']['context']),
454 //Disable repeated password
455 'password_repeated' => false,
456 //Set method
457 'method' => 'POST'
458 ]);
459
460 //Init context
461 $context = [];
462
463 //With mail
464 if (!empty($mail) && !empty($hash)) {
465 //With invalid hash
466 if ($hash != $slugger->hash($mail)) {
467 //Throw bad request
468 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash]));
469 }
470
471 //Get mail
472 $mail = $slugger->unshort($smail = $mail);
473
474 //Without valid mail
475 if (filter_var($mail, FILTER_VALIDATE_EMAIL) === false) {
476 //Throw bad request
477 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'mail', '%value%' => $smail]));
478 }
479
480 //Prefilled mail
481 $login->get('mail')->setData($mail);
482 //Last username entered by the user
483 } elseif ($lastUsername = $authenticationUtils->getLastUsername()) {
484 $login->get('mail')->setData($lastUsername);
485 }
486
487 //Get the login error if there is one
488 if ($error = $authenticationUtils->getLastAuthenticationError()) {
489 //Get translated error
490 $error = $this->translator->trans($error->getMessageKey());
491
492 //Add error message to mail field
493 $login->get('mail')->addError(new FormError($error));
494
495 //Create the LoginType form and give the proper parameters
496 $recover = $this->createForm($this->config['recover']['view']['form'], null, [
497 //Set action to recover route name and context
498 'action' => $this->generateUrl($this->config['route']['recover']['name'], $this->config['route']['recover']['context']),
499 //Without password
500 'password' => false,
501 //Set method
502 'method' => 'POST'
503 ]);
504
505 //Get recover mail entity
506 $recover->get('mail')
507 //Set mail from login form
508 ->setData($login->get('mail')->getData())
509 //Add recover error
510 ->addError(new FormError($this->translator->trans('Use this form to recover your account')));
511
512 //Add recover form to context
513 $context['recover'] = $recover->createView();
514 } else {
515 //Add notice
516 $this->addFlash('notice', $this->translator->trans('To change your password login with your mail and any password then follow the procedure'));
517 }
518
519 //Render view
520 return $this->render(
521 //Template
522 $this->config['login']['view']['name'],
523 //Context
524 ['login' => $login->createView()]+$context+$this->config['login']['view']['context']
525 );
526 }
527
528 /**
529 * Recover account
530 *
531 * @param Request $request The request
532 * @param Registry $manager The doctrine registry
533 * @param UserPasswordEncoderInterface $encoder The password encoder
534 * @param EntityManagerInterface $manager The doctrine entity manager
535 * @param SluggerUtil $slugger The slugger
536 * @param MailerInterface $mailer The mailer
537 * @param string $mail The shorted mail address
538 * @param string $pass The shorted password
539 * @param string $hash The hashed password
540 * @return Response The response
541 */
542 public function recover(Request $request, Registry $doctrine, UserPasswordEncoderInterface $encoder, EntityManagerInterface $manager, SluggerUtil $slugger, MailerInterface $mailer, $mail, $pass, $hash): Response {
543 //Without mail, pass and hash
544 if (empty($mail) && empty($pass) && empty($hash)) {
545 //Create the LoginType form and give the proper parameters
546 $form = $this->createForm($this->config['recover']['view']['form'], null, [
547 //Set action to recover route name and context
548 'action' => $this->generateUrl($this->config['route']['recover']['name'], $this->config['route']['recover']['context']),
549 //Without password
550 'password' => false,
551 //Set method
552 'method' => 'POST'
553 ]);
554
555 if ($request->isMethod('POST')) {
556 //Refill the fields in case the form is not valid.
557 $form->handleRequest($request);
558
559 if ($form->isValid()) {
560 //Set data
561 $data = $form->getData();
562
563 //Find user by data mail
564 if ($user = $doctrine->getRepository($this->config['class']['user'])->findOneByMail($data['mail'])) {
565 //Set mail shortcut
566 $recoverMail =& $this->config['recover']['mail'];
567
568 //Set mail
569 $mail = $slugger->short($user->getMail());
570
571 //Set pass
572 $pass = $slugger->hash($user->getPassword());
573
574 //Generate each route route
575 foreach($this->config['recover']['route'] as $route => $tag) {
576 //Only process defined routes
577 if (!empty($this->config['route'][$route])) {
578 //Process for recover mail url
579 if ($route == 'recover') {
580 //Set the url in context
581 $recoverMail['context'][$tag] = $this->get('router')->generate(
582 $this->config['route'][$route]['name'],
583 //Prepend recover context with tag
584 [
585 'mail' => $mail,
586 'pass' => $pass,
587 'hash' => $slugger->hash($mail.$pass)
588 ]+$this->config['route'][$route]['context'],
589 UrlGeneratorInterface::ABSOLUTE_URL
590 );
591 }
592 }
593 }
594
595 //Set recipient_name
596 $recoverMail['context']['recipient_mail'] = $user->getMail();
597
598 //Set recipient_name
599 $recoverMail['context']['recipient_name'] = trim($user->getForename().' '.$user->getSurname().($user->getPseudonym()?' ('.$user->getPseudonym().')':''));
600
601 //Init subject context
602 $subjectContext = $slugger->flatten(array_replace_recursive($this->config['recover']['view']['context'], $recoverMail['context']), null, '.', '%', '%');
603
604 //Translate subject
605 $recoverMail['subject'] = ucfirst($this->translator->trans($recoverMail['subject'], $subjectContext));
606
607 //Create message
608 $message = (new TemplatedEmail())
609 //Set sender
610 ->from(new Address($this->config['contact']['mail'], $this->config['contact']['title']))
611 //Set recipient
612 //XXX: remove the debug set in vendor/symfony/mime/Address.php +46
613 ->to(new Address($recoverMail['context']['recipient_mail'], $recoverMail['context']['recipient_name']))
614 //Set subject
615 ->subject($recoverMail['subject'])
616
617 //Set path to twig templates
618 ->htmlTemplate($recoverMail['html'])
619 ->textTemplate($recoverMail['text'])
620
621 //Set context
622 //XXX: require recursive merge to avoid loosing subkeys
623 //['subject' => $recoverMail['subject']]+$recoverMail['context']+$this->config['recover']['view']['context']
624 ->context(array_replace_recursive($this->config['recover']['view']['context'], $recoverMail['context'], ['subject' => $recoverMail['subject']]));
625
626 //Try sending message
627 //XXX: mail delivery may silently fail
628 try {
629 //Send message
630 $mailer->send($message);
631
632 //Redirect on the same route with sent=1 to cleanup form
633 return $this->redirectToRoute($request->get('_route'), ['sent' => 1]+$request->get('_route_params'));
634 //Catch obvious transport exception
635 } catch(TransportExceptionInterface $e) {
636 //Add error message mail unreachable
637 $form->get('mail')->addError(new FormError($this->translator->trans('Account found but unable to contact: %mail%', array('%mail%' => $data['mail']))));
638 }
639 //Accout not found
640 } else {
641 //Add error message to mail field
642 $form->get('mail')->addError(new FormError($this->translator->trans('Unable to find account %mail%', ['%mail%' => $data['mail']])));
643 }
644 }
645 }
646
647 //Render view
648 return $this->render(
649 //Template
650 $this->config['recover']['view']['name'],
651 //Context
652 ['form' => $form->createView(), 'sent' => $request->query->get('sent', 0)]+$this->config['recover']['view']['context']
653 );
654 }
655
656 //With invalid hash
657 if ($hash != $slugger->hash($mail.$pass)) {
658 //Throw bad request
659 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash]));
660 }
661
662 //Get mail
663 $mail = $slugger->unshort($smail = $mail);
664
665 //Without valid mail
666 if (filter_var($mail, FILTER_VALIDATE_EMAIL) === false) {
667 //Throw bad request
668 //XXX: prevent slugger reverse engineering by not displaying decoded mail
669 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'mail', '%value%' => $smail]));
670 }
671
672 //With existing subscriber
673 if (empty($user = $doctrine->getRepository($this->config['class']['user'])->findOneByMail($mail))) {
674 //Throw not found
675 //XXX: prevent slugger reverse engineering by not displaying decoded mail
676 throw $this->createNotFoundException($this->translator->trans('Unable to find account %mail%', ['%mail%' => $smail]));
677 }
678
679 //With unmatched pass
680 if ($pass != $slugger->hash($user->getPassword())) {
681 //Throw not found
682 //XXX: prevent use of outdated recover link
683 throw $this->createNotFoundException($this->translator->trans('Outdated recover link'));
684 }
685
686 //Create the LoginType form and give the proper parameters
687 $form = $this->createForm($this->config['recover']['view']['form'], $user, [
688 //Set action to recover route name and context
689 'action' => $this->generateUrl($this->config['route']['recover']['name'], ['mail' => $smail, 'pass' => $pass, 'hash' => $hash]+$this->config['route']['recover']['context']),
690 //Without mail
691 'mail' => false,
692 //Set method
693 'method' => 'POST'
694 ]);
695
696 if ($request->isMethod('POST')) {
697 //Refill the fields in case the form is not valid.
698 $form->handleRequest($request);
699
700 if ($form->isValid()) {
701 //Set data
702 $data = $form->getData();
703
704 //Set encoded password
705 $encoded = $encoder->encodePassword($user, $user->getPassword());
706
707 //Update pass
708 $pass = $slugger->hash($encoded);
709
710 //Set user password
711 $user->setPassword($encoded);
712
713 //Persist user
714 $manager->persist($user);
715
716 //Send to database
717 $manager->flush();
718
719 //Add notice
720 $this->addFlash('notice', $this->translator->trans('Account %mail% password updated', ['%mail%' => $mail]));
721
722 //Redirect to user login
723 return $this->redirectToRoute($this->config['route']['login']['name'], ['mail' => $smail, 'hash' => $slugger->hash($smail)]+$this->config['route']['login']['context']);
724 }
725 }
726
727 //Render view
728 return $this->render(
729 //Template
730 $this->config['recover']['view']['name'],
731 //Context
732 ['form' => $form->createView(), 'sent' => $request->query->get('sent', 0)]+$this->config['recover']['view']['context']
733 );
734 }
735
736 /**
737 * Register an account
738 *
739 * @param Request $request The request
740 * @param Registry $manager The doctrine registry
741 * @param UserPasswordEncoderInterface $encoder The password encoder
742 * @param EntityManagerInterface $manager The doctrine entity manager
743 * @param SluggerUtil $slugger The slugger
744 * @param MailerInterface $mailer The mailer
745 * @param LoggerInterface $logger The logger
746 * @param string $mail The shorted mail address
747 * @param string $field The serialized then shorted form field array
748 * @param string $hash The hashed serialized field array
749 * @return Response The response
750 */
751 public function register(Request $request, Registry $doctrine, UserPasswordEncoderInterface $encoder, EntityManagerInterface $manager, SluggerUtil $slugger, MailerInterface $mailer, LoggerInterface $logger, $mail, $field, $hash): Response {
752 //Init reflection
753 $reflection = new \ReflectionClass($this->config['class']['user']);
754
755 //Create new user
756 $user = $reflection->newInstance();
757
758 //With mail and field
759 if (!empty($field) && !empty($hash)) {
760 //With invalid hash
761 if ($hash != $slugger->hash($mail.$field)) {
762 //Throw bad request
763 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash]));
764 }
765
766 //With mail
767 if (!empty($mail)) {
768 //Get mail
769 $mail = $slugger->unshort($smail = $mail);
770
771 //Without valid mail
772 if (filter_var($mail, FILTER_VALIDATE_EMAIL) === false) {
773 //Throw bad request
774 //XXX: prevent slugger reverse engineering by not displaying decoded mail
775 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'mail', '%value%' => $smail]));
776 }
777
778 //Set mail
779 $user->setMail($mail);
780
781 //With existing registrant
782 if ($existing = $doctrine->getRepository($this->config['class']['user'])->findOneByMail($mail)) {
783 //With disabled existing
784 if ($existing->isDisabled()) {
785 //Render view
786 return $this->render(
787 //Template
788 $this->config['register']['view']['name'],
789 //Context
790 ['title' => $this->translator->trans('Access denied'), 'disabled' => 1]+$this->config['register']['view']['context'],
791 //Set 403
792 new Response('', 403)
793 );
794 //With unactivated existing
795 } elseif (!$existing->isActivated()) {
796 //Set mail shortcut
797 //TODO: change for activate ???
798 $activateMail =& $this->config['register']['mail'];
799
800 //Generate each route route
801 foreach($this->config['register']['route'] as $route => $tag) {
802 //Only process defined routes
803 if (!empty($this->config['route'][$route])) {
804 //Process for confirm url
805 if ($route == 'confirm') {
806 //Set the url in context
807 $activateMail['context'][$tag] = $this->get('router')->generate(
808 $this->config['route'][$route]['name'],
809 //Prepend subscribe context with tag
810 [
811 'mail' => $smail = $slugger->short($existing->getMail()),
812 'hash' => $slugger->hash($smail)
813 ]+$this->config['route'][$route]['context'],
814 UrlGeneratorInterface::ABSOLUTE_URL
815 );
816 }
817 }
818 }
819
820 //Set recipient_name
821 $activateMail['context']['recipient_mail'] = $existing->getMail();
822
823 //Set recipient name
824 $activateMail['context']['recipient_name'] = implode(' ', [$existing->getForename(), $existing->getSurname(), $existing->getPseudonym()?'('.$existing->getPseudonym().')':'']);
825
826 //Init subject context
827 $subjectContext = $slugger->flatten(array_replace_recursive($this->config['register']['view']['context'], $activateMail['context']), null, '.', '%', '%');
828
829 //Translate subject
830 $activateMail['subject'] = ucfirst($this->translator->trans($activateMail['subject'], $subjectContext));
831
832 //Create message
833 $message = (new TemplatedEmail())
834 //Set sender
835 ->from(new Address($this->config['contact']['mail'], $this->config['contact']['title']))
836 //Set recipient
837 //XXX: remove the debug set in vendor/symfony/mime/Address.php +46
838 ->to(new Address($activateMail['context']['recipient_mail'], $activateMail['context']['recipient_name']))
839 //Set subject
840 ->subject($activateMail['subject'])
841
842 //Set path to twig templates
843 ->htmlTemplate($activateMail['html'])
844 ->textTemplate($activateMail['text'])
845
846 //Set context
847 ->context(['subject' => $activateMail['subject']]+$activateMail['context']);
848
849 //Try sending message
850 //XXX: mail delivery may silently fail
851 try {
852 //Send message
853 $mailer->send($message);
854 //Catch obvious transport exception
855 } catch(TransportExceptionInterface $e) {
856 //Add error message mail unreachable
857 $this->addFlash('error', $this->translator->trans('Account %mail% tried activate but unable to contact', ['%mail%' => $existing->getMail()]));
858 }
859
860 //Get route params
861 $routeParams = $request->get('_route_params');
862
863 //Remove mail, field and hash from route params
864 unset($routeParams['mail'], $routeParams['field'], $routeParams['hash']);
865
866 //Redirect on the same route with sent=1 to cleanup form
867 return $this->redirectToRoute($request->get('_route'), ['sent' => 1]+$routeParams);
868 }
869
870 //Add error message mail already exists
871 $this->addFlash('warning', $this->translator->trans('Account %mail% already exists', ['%mail%' => $existing->getMail()]));
872
873 //Redirect to user view
874 return $this->redirectToRoute(
875 $this->config['route']['edit']['name'],
876 [
877 'mail' => $smail = $slugger->short($existing->getMail()),
878 'hash' => $slugger->hash($smail)
879 ]+$this->config['route']['edit']['context']
880 );
881 }
882 //Without mail
883 } else {
884 //Set smail
885 $smail = $mail;
886 }
887
888 //Try
889 try {
890 //Unshort then unserialize field
891 $field = $slugger->unserialize($sfield = $field);
892 //Catch type error
893 } catch (\Error|\Exception $e) {
894 //Throw bad request
895 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'field', '%value%' => $field]), $e);
896 }
897
898 //With non array field
899 if (!is_array($field)) {
900 //Throw bad request
901 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'field', '%value%' => $field]));
902 }
903 //Without field and hash
904 } else {
905 //Set smail
906 $smail = $mail;
907
908 //Set smail
909 $sfield = $field;
910
911 //Reset field
912 $field = [];
913 }
914
915 //Create the RegisterType form and give the proper parameters
916 $form = $this->createForm($this->config['register']['view']['form'], $user, $field+[
917 //Set action to register route name and context
918 'action' => $this->generateUrl($this->config['route']['register']['name'], ['mail' => $smail, 'field' => $sfield, 'hash' => $hash]+$this->config['route']['register']['context']),
919 //Set civility class
920 'civility_class' => $this->config['class']['civility'],
921 //Set civility default
922 'civility_default' => $doctrine->getRepository($this->config['class']['civility'])->findOneByTitle($this->config['default']['civility']),
923 //With mail
924 'mail' => true,
925 //Set method
926 'method' => 'POST'
927 ]);
928
929 if ($request->isMethod('POST')) {
930 //Refill the fields in case the form is not valid.
931 $form->handleRequest($request);
932
933 if ($form->isValid()) {
934 //Set data
935 $data = $form->getData();
936
937 //With existing registrant
938 if ($doctrine->getRepository($this->config['class']['user'])->findOneByMail($mail = $data->getMail())) {
939 //Add error message mail already exists
940 $this->addFlash('warning', $this->translator->trans('Account %mail% already exists', ['%mail%' => $mail]));
941
942 //Redirect to user view
943 return $this->redirectToRoute(
944 $this->config['route']['edit']['name'],
945 [
946 'mail' => $smail = $slugger->short($mail),
947 'hash' => $slugger->hash($smail)
948 ]+$this->config['route']['edit']['context']
949 );
950 }
951
952 //Set mail shortcut
953 $registerMail =& $this->config['register']['mail'];
954
955 //Extract names and pseudonym from mail
956 $names = explode(' ', $pseudonym = ucwords(trim(preg_replace('/[^a-zA-Z]+/', ' ', current(explode('@', $data->getMail()))))));
957
958 //Set pseudonym
959 $user->setPseudonym($user->getPseudonym()??$pseudonym);
960
961 //Set forename
962 $user->setForename($user->getForename()??$names[0]);
963
964 //Set surname
965 $user->setSurname($user->getSurname()??$names[1]??$names[0]);
966
967 //Set password
968 $user->setPassword($encoder->encodePassword($user, $user->getPassword()??$data->getMail()));
969
970 //Set created
971 $user->setCreated(new \DateTime('now'));
972
973 //Set updated
974 $user->setUpdated(new \DateTime('now'));
975
976 //Persist user
977 $manager->persist($user);
978
979 //Iterate on default group
980 foreach($this->config['default']['group'] as $i => $groupTitle) {
981 //Fetch group
982 if (($group = $doctrine->getRepository($this->config['class']['group'])->findOneByTitle($groupTitle))) {
983 //Set default group
984 //XXX: see vendor/symfony/security-core/Role/Role.php
985 $user->addGroup($group);
986 //Group not found
987 } else {
988 //Throw exception
989 //XXX: consider missing group as fatal
990 throw new \Exception(sprintf('Group from rapsys_user.default.group[%d] not found by title: %s', $i, $groupTitle));
991 }
992 }
993
994 //Generate each route route
995 foreach($this->config['register']['route'] as $route => $tag) {
996 //Only process defined routes
997 if (!empty($this->config['route'][$route])) {
998 //Process for confirm url
999 if ($route == 'confirm') {
1000 //Set the url in context
1001 $registerMail['context'][$tag] = $this->get('router')->generate(
1002 $this->config['route'][$route]['name'],
1003 //Prepend subscribe context with tag
1004 [
1005 'mail' => $smail = $slugger->short($data->getMail()),
1006 'hash' => $slugger->hash($smail)
1007 ]+$this->config['route'][$route]['context'],
1008 UrlGeneratorInterface::ABSOLUTE_URL
1009 );
1010 }
1011 }
1012 }
1013
1014 //XXX: DEBUG: remove me
1015 //die($registerMail['context']['confirm_url']);
1016
1017 //Log new user infos
1018 //XXX: useless ???
1019 $logger->emergency(
1020 $this->translator->trans(
1021 'newuser:mail=%mail%|locale=%locale%|confirm=%confirm%',
1022 [
1023 '%mail%' => $data->getMail(),
1024 '%locale%' => $request->getLocale(),
1025 '%confirm%' => $registerMail['context'][$this->config['register']['route']['confirm']]
1026 ]
1027 )
1028 );
1029
1030 //Set recipient_name
1031 $registerMail['context']['recipient_mail'] = $data->getMail();
1032
1033 //Set recipient name
1034 $registerMail['context']['recipient_name'] = '';
1035
1036 //Set recipient name
1037 $registerMail['context']['recipient_name'] = implode(' ', [$data->getForename(), $data->getSurname(), $data->getPseudonym()?'('.$data->getPseudonym().')':'']);
1038
1039 //Init subject context
1040 $subjectContext = $slugger->flatten(array_replace_recursive($this->config['register']['view']['context'], $registerMail['context']), null, '.', '%', '%');
1041
1042 //Translate subject
1043 $registerMail['subject'] = ucfirst($this->translator->trans($registerMail['subject'], $subjectContext));
1044
1045 //Create message
1046 $message = (new TemplatedEmail())
1047 //Set sender
1048 ->from(new Address($this->config['contact']['mail'], $this->config['contact']['title']))
1049 //Set recipient
1050 //XXX: remove the debug set in vendor/symfony/mime/Address.php +46
1051 ->to(new Address($registerMail['context']['recipient_mail'], $registerMail['context']['recipient_name']))
1052 //Set subject
1053 ->subject($registerMail['subject'])
1054
1055 //Set path to twig templates
1056 ->htmlTemplate($registerMail['html'])
1057 ->textTemplate($registerMail['text'])
1058
1059 //Set context
1060 ->context(['subject' => $registerMail['subject']]+$registerMail['context']);
1061
1062 //Try saving in database
1063 try {
1064 //Send to database
1065 $manager->flush();
1066
1067 //Add error message mail already exists
1068 $this->addFlash('notice', $this->translator->trans('Your account has been created'));
1069
1070 //Try sending message
1071 //XXX: mail delivery may silently fail
1072 try {
1073 //Send message
1074 $mailer->send($message);
1075
1076 //Redirect on the same route with sent=1 to cleanup form
1077 return $this->redirectToRoute($request->get('_route'), ['sent' => 1]+$request->get('_route_params'));
1078 //Catch obvious transport exception
1079 } catch(TransportExceptionInterface $e) {
1080 //Add error message mail unreachable
1081 $form->get('mail')->addError(new FormError($this->translator->trans('Account %mail% tried subscribe but unable to contact', ['%mail%' => $data->getMail()])));
1082 }
1083 //Catch double subscription
1084 } catch (\Doctrine\DBAL\Exception\UniqueConstraintViolationException $e) {
1085 //Add error message mail already exists
1086 $this->addFlash('error', $this->translator->trans('Account %mail% already exists', ['%mail%' => $mail]));
1087 }
1088 }
1089 }
1090
1091 //Render view
1092 return $this->render(
1093 //Template
1094 $this->config['register']['view']['name'],
1095 //Context
1096 ['form' => $form->createView(), 'sent' => $request->query->get('sent', 0)]+$this->config['register']['view']['context']
1097 );
1098 }
1099
1100 /**
1101 * {@inheritdoc}
1102 */
1103 public function getAlias(): string {
1104 return RapsysUserBundle::getAlias();
1105 }
1106 }