1 <?php
declare(strict_types
=1);
4 * This file is part of the Rapsys UserBundle package.
6 * (c) Raphaël Gertz <symfony@rapsys.eu>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Rapsys\UserBundle\Controller
;
14 use Doctrine\DBAL\Exception\UniqueConstraintViolationException
;
16 use Symfony\Bridge\Twig\Mime\TemplatedEmail
;
17 use Symfony\Component\Form\FormError
;
18 use Symfony\Component\HttpFoundation\Request
;
19 use Symfony\Component\HttpFoundation\Response
;
20 use Symfony\Component\HttpKernel\Exception\BadRequestHttpException
;
21 use Symfony\Component\HttpKernel\Exception\GoneHttpException
;
22 use Symfony\Component\Mailer\Exception\TransportExceptionInterface
;
23 use Symfony\Component\Mime\Address
;
24 use Symfony\Component\Routing\Generator\UrlGeneratorInterface
;
25 use Symfony\Component\Security\Http\Authentication\AuthenticationUtils
;
30 class UserController
extends AbstractController
{
34 * @param Request $request The request
35 * @return Response The response
37 public function index(Request
$request): Response
{
39 if (!$this->checker
->isGranted('ROLE_'.strtoupper($this->config
['default']['admin']))) {
41 throw $this->createAccessDeniedException($this->translator
->trans('Unable to list users', [], $this->alias
));
45 $this->context
['count'] = $this->doctrine
->getRepository($this->config
['class']['user'])->findCountAsInt();
47 //With not enough users
48 if ($this->context
['count'] - $this->page
* $this->limit
< 0) {
50 throw $this->createNotFoundException($this->translator
->trans('Unable to find users', [], $this->alias
));
54 $this->context
['groups'] = $this->doctrine
->getRepository($this->config
['class']['user'])->findIndexByGroupId($this->page
, $this->limit
);
59 $this->config
['index']['view']['name'],
61 $this->context+
$this->config
['index']['view']['context']
66 * Confirm account from mail link
68 * @param Request $request The request
69 * @param string $hash The hashed password
70 * @param string $mail The shorted mail address
71 * @return Response The response
73 public function confirm(Request
$request, string $hash, string $mail): Response
{
75 if ($hash != $this->slugger
->hash($mail)) {
77 throw new BadRequestHttpException($this->translator
->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash], $this->alias
));
81 $mail = $this->slugger
->unshort($smail = $mail);
84 if (filter_var($mail, FILTER_VALIDATE_EMAIL
) === false) {
86 //XXX: prevent slugger reverse engineering by not displaying decoded mail
87 throw new BadRequestHttpException($this->translator
->trans('Invalid %field% field: %value%', ['%field%' => 'mail', '%value%' => $smail], $this->alias
));
90 //Without existing registrant
91 if (!($user = $this->doctrine
->getRepository($this->config
['class']['user'])->findOneByMail($mail))) {
92 //Add error message mail already exists
93 //XXX: prevent slugger reverse engineering by not displaying decoded mail
94 $this->addFlash('error', $this->translator
->trans('The account do not exists', [], $this->alias
));
96 //Redirect to register view
97 return $this->redirectToRoute($this->config
['route']['register']['name'], $this->config
['route']['register']['context']);
101 $user->setActive(true);
104 $this->manager
->persist($user);
107 $this->manager
->flush();
109 //Add error message mail already exists
110 $this->addFlash('notice', $this->translator
->trans('Your account has been activated', [], $this->alias
));
112 //Redirect to user view
113 return $this->redirectToRoute($this->config
['route']['edit']['name'], ['mail' => $smail, 'hash' => $this->slugger
->hash($smail)]+
$this->config
['route']['edit']['context']);
117 * Edit account by shorted mail
119 * @param Request $request The request
120 * @param string $hash The hashed password
121 * @param string $mail The shorted mail address
122 * @return Response The response
124 public function edit(Request
$request, string $hash, string $mail): Response
{
126 if ($hash != $this->slugger
->hash($mail)) {
128 throw new BadRequestHttpException($this->translator
->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash], $this->alias
));
132 $mail = $this->slugger
->unshort($smail = $mail);
134 //With existing subscriber
135 if (empty($user = $this->doctrine
->getRepository($this->config
['class']['user'])->findOneByMail($mail))) {
137 //XXX: prevent slugger reverse engineering by not displaying decoded mail
138 throw $this->createNotFoundException($this->translator
->trans('Unable to find account', [], $this->alias
));
141 //Prevent access when not admin, user is not guest and not currently logged user
142 if (!$this->checker
->isGranted('ROLE_'.strtoupper($this->config
['default']['admin'])) && $user != $this->security
->getUser() || !$this->checker
->isGranted('IS_AUTHENTICATED_FULLY')) {
143 //Throw access denied
144 //XXX: prevent slugger reverse engineering by not displaying decoded mail
145 throw $this->createAccessDeniedException($this->translator
->trans('Unable to access user', [], $this->alias
));
148 //Create the EditType form and give the proper parameters
149 $edit = $this->factory
->create($this->config
['edit']['view']['edit'], $user, [
150 //Set action to edit route name and context
151 'action' => $this->generateUrl($this->config
['route']['edit']['name'], ['mail' => $smail, 'hash' => $this->slugger
->hash($smail)]+
$this->config
['route']['edit']['context']),
153 'civility_class' => $this->config
['class']['civility'],
154 //Set civility default
155 'civility_default' => $this->doctrine
->getRepository($this->config
['class']['civility'])->findOneByTitle($this->config
['default']['civility']),
157 'mail' => $this->checker
->isGranted('ROLE_'.strtoupper($this->config
['default']['admin'])),
163 'translation_domain' => $this->alias
164 ]+
($this->checker
->isGranted('ROLE_'.strtoupper($this->config
['default']['admin']))?$this->config
['edit']['admin']:$this->config
['edit']['field']));
167 if ($this->checker
->isGranted('ROLE_'.strtoupper($this->config
['default']['admin']))) {
168 //Create the EditType form and give the proper parameters
169 $reset = $this->factory
->create($this->config
['edit']['view']['reset'], $user, [
170 //Set action to edit route name and context
171 'action' => $this->generateUrl($this->config
['route']['edit']['name'], ['mail' => $smail, 'hash' => $this->slugger
->hash($smail)]+
$this->config
['route']['edit']['context']),
175 'translation_domain' => $this->alias
179 if ($request->isMethod('POST')) {
180 //Refill the fields in case the form is not valid.
181 $reset->handleRequest($request);
183 //With reset submitted and valid
184 if ($reset->isSubmitted() && $reset->isValid()) {
186 $data = $reset->getData();
189 $data->setPassword($this->hasher
->hashPassword($data, $data->getPassword()));
192 $this->manager
->persist($data);
194 //Flush to get the ids
195 $this->manager
->flush();
198 $this->addFlash('notice', $this->translator
->trans('Account password updated', [], $this->alias
));
200 //Redirect to cleanup the form
201 return $this->redirectToRoute($this->config
['route']['edit']['name'], ['mail' => $smail = $this->slugger
->short($mail), 'hash' => $this->slugger
->hash($smail)]+
$this->config
['route']['edit']['context']);
206 $this->config
['edit']['view']['context']['reset'] = $reset->createView();
210 if ($request->isMethod('POST')) {
211 //Refill the fields in case the form is not valid.
212 $edit->handleRequest($request);
214 //With edit submitted and valid
215 if ($edit->isSubmitted() && $edit->isValid()) {
217 $data = $edit->getData();
220 $this->manager
->persist($data);
222 //Try saving in database
224 //Flush to get the ids
225 $this->manager
->flush();
228 $this->addFlash('notice', $this->translator
->trans('Account updated', [], $this->alias
));
230 //Redirect to cleanup the form
231 return $this->redirectToRoute($this->config
['route']['edit']['name'], ['mail' => $smail = $this->slugger
->short($mail), 'hash' => $this->slugger
->hash($smail)]+
$this->config
['route']['edit']['context']);
232 //Catch double slug or mail
233 } catch (UniqueConstraintViolationException
$e) {
234 //Add error message mail already exists
235 $this->addFlash('error', $this->translator
->trans('The account already exists', [], $this->alias
));
239 //XXX: prefer a reset on login to force user unspam action
240 } elseif (!$this->checker
->isGranted('ROLE_'.strtoupper($this->config
['default']['admin']))) {
242 $this->addFlash('notice', $this->translator
->trans('To change your password login with your mail and any password then follow the procedure', [], $this->alias
));
246 return $this->render(
248 $this->config
['edit']['view']['name'],
250 ['register' => $edit->createView()]+
$this->config
['edit']['view']['context']
257 * @param Request $request The request
258 * @param AuthenticationUtils $authenticationUtils The authentication utils
259 * @param ?string $hash The hashed password
260 * @param ?string $mail The shorted mail address
261 * @return Response The response
263 public function login(Request
$request, AuthenticationUtils
$authenticationUtils, ?string $hash, ?string $mail): Response
{
264 //Create the LoginType form and give the proper parameters
265 $login = $this->factory
->create($this->config
['login']['view']['form'], null, [
266 //Set action to login route name and context
267 'action' => $this->generateUrl($this->config
['route']['login']['name'], $this->config
['route']['login']['context']),
271 'translation_domain' => $this->alias
278 if (!empty($mail) && !empty($hash)) {
280 if ($hash != $this->slugger
->hash($mail)) {
282 throw new BadRequestHttpException($this->translator
->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash], $this->alias
));
286 $mail = $this->slugger
->unshort($smail = $mail);
289 if (filter_var($mail, FILTER_VALIDATE_EMAIL
) === false) {
291 throw new BadRequestHttpException($this->translator
->trans('Invalid %field% field: %value%', ['%field%' => 'mail', '%value%' => $smail], $this->alias
));
295 $login->get('mail')->setData($mail);
296 //Last username entered by the user
297 } elseif ($lastUsername = $authenticationUtils->getLastUsername()) {
298 $login->get('mail')->setData($lastUsername);
301 //Get the login error if there is one
302 if ($error = $authenticationUtils->getLastAuthenticationError()) {
303 //Get translated error
304 $error = $this->translator
->trans($error->getMessageKey(), [], $this->alias
);
306 //Add error message to mail field
307 $login->get('mail')->addError(new FormError($error));
309 //Create the RecoverType form and give the proper parameters
310 $recover = $this->factory
->create($this->config
['recover']['view']['form'], null, [
311 //Set action to recover route name and context
312 'action' => $this->generateUrl($this->config
['route']['recover']['name'], $this->config
['route']['recover']['context']),
318 'translation_domain' => $this->alias
321 //Get recover mail entity
322 $recover->get('mail')
323 //Set mail from login form
324 ->setData($login->get('mail')->getData())
326 ->addError(new FormError($this->translator
->trans('Use this form to recover your account', [], $this->alias
)));
328 //Add recover form to context
329 $context['recover'] = $recover->createView();
332 $this->addFlash('notice', $this->translator
->trans('To change your password login with your mail and any password then follow the procedure', [], $this->alias
));
336 return $this->render(
338 $this->config
['login']['view']['name'],
340 ['login' => $login->createView(), 'disabled' => $request->query
->get('disabled', 0)]+
$context+
$this->config
['login']['view']['context']
347 * @param Request $request The request
348 * @param ?string $hash The hashed password
349 * @param ?string $pass The shorted password
350 * @param ?string $mail The shorted mail address
351 * @return Response The response
353 public function recover(Request
$request, ?string $hash, ?string $pass, ?string $mail): Response
{
360 //With mail, pass and hash
361 if (!empty($mail) && !empty($pass) && !empty($hash)) {
363 if ($hash != $this->slugger
->hash($mail.$pass)) {
365 throw new BadRequestHttpException($this->translator
->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash], $this->alias
));
369 $mail = $this->slugger
->unshort($smail = $mail);
372 if (filter_var($mail, FILTER_VALIDATE_EMAIL
) === false) {
374 //XXX: prevent slugger reverse engineering by not displaying decoded mail
375 throw new BadRequestHttpException($this->translator
->trans('Invalid %field% field: %value%', ['%field%' => 'mail', '%value%' => $smail], $this->alias
));
378 //With existing subscriber
379 if (empty($user = $this->doctrine
->getRepository($this->config
['class']['user'])->findOneByMail($mail))) {
381 //XXX: prevent slugger reverse engineering by not displaying decoded mail
382 throw $this->createNotFoundException($this->translator
->trans('Unable to find account', [], $this->alias
));
385 //With unmatched pass
386 if ($pass != $this->slugger
->hash($user->getPassword())) {
388 //XXX: prevent use of outdated recover link
389 throw new GoneHttpException($this->translator
->trans('Outdated recover link', [], $this->alias
));
393 $context = ['mail' => $smail, 'pass' => $pass, 'hash' => $hash];
396 //Create the LoginType form and give the proper parameters
397 $form = $this->factory
->create($this->config
['recover']['view']['form'], $user, [
398 //Set action to recover route name and context
399 'action' => $this->generateUrl($this->config
['route']['recover']['name'], $context+
$this->config
['route']['recover']['context']),
400 //With user disable mail
401 'mail' => ($user === null),
402 //With user enable password
403 'password' => ($user !== null),
407 'translation_domain' => $this->alias
411 if ($request->isMethod('POST')) {
412 //Refill the fields in case the form is not valid.
413 $form->handleRequest($request);
415 //With form submitted and valid
416 if ($form->isSubmitted() && $form->isValid()) {
418 $data = $form->getData();
421 if ($user !== null) {
422 //Set hashed password
423 $hashed = $this->hasher
->hashPassword($user, $user->getPassword());
426 $pass = $this->slugger
->hash($hashed);
429 $user->setPassword($hashed);
432 $this->manager
->persist($user);
435 $this->manager
->flush();
438 $this->addFlash('notice', $this->translator
->trans('Account password updated', [], $this->alias
));
440 //Redirect to user login
441 return $this->redirectToRoute($this->config
['route']['login']['name'], ['mail' => $smail, 'hash' => $this->slugger
->hash($smail)]+
$this->config
['route']['login']['context']);
442 //Find user by data mail
443 } elseif ($user = $this->doctrine
->getRepository($this->config
['class']['user'])->findOneByMail($data['mail'])) {
446 'recipient_mail' => $user->getMail(),
447 'recipient_name' => $user->getRecipientName()
448 ] +
array_replace_recursive(
449 $this->config
['context'],
450 $this->config
['recover']['view']['context'],
451 $this->config
['recover']['mail']['context']
454 //Generate each route route
455 foreach($this->config
['recover']['route'] as $route => $tag) {
456 //Only process defined routes
457 if (!empty($this->config
['route'][$route])) {
458 //Process for recover mail url
459 if ($route == 'recover') {
460 //Set the url in context
461 $context[$tag] = $this->router
->generate(
462 $this->config
['route'][$route]['name'],
463 //Prepend recover context with tag
465 'mail' => $smail = $this->slugger
->short($context['recipient_mail']),
466 'pass' => $spass = $this->slugger
->hash($pass = $user->getPassword()),
467 'hash' => $this->slugger
->hash($smail.$spass)
468 ]+
$this->config
['route'][$route]['context'],
469 UrlGeneratorInterface
::ABSOLUTE_URL
476 $context['subject'] = $subject = ucfirst(
477 $this->translator
->trans(
478 $this->config
['recover']['mail']['subject'],
479 $this->slugger
->flatten($context, null, '.', '%', '%'),
485 $message = (new TemplatedEmail())
487 ->from(new Address($this->config
['contact']['address'], $this->translator
->trans($this->config
['contact']['name'], [], $this->alias
)))
489 //XXX: remove the debug set in vendor/symfony/mime/Address.php +46
490 ->to(new Address($context['recipient_mail'], $context['recipient_name']))
492 ->subject($context['subject'])
494 //Set path to twig templates
495 ->htmlTemplate($this->config
['recover']['mail']['html'])
496 ->textTemplate($this->config
['recover']['mail']['text'])
502 $this->addFlash('notice', $this->translator
->trans('Account recovered', [], $this->alias
));
504 //Try sending message
505 //XXX: mail delivery may silently fail
508 $this->mailer
->send($message);
511 $this->addFlash('notice', $this->translator
->trans('Your recovery mail has been sent, to retrieve your account follow the recuperate link inside', [], $this->alias
));
514 $this->addFlash('warning', $this->translator
->trans('If you did not receive a recovery mail, check your Spam or Junk mail folder', [], $this->alias
));
516 //Redirect on home route to cleanup form
517 return $this->redirectToRoute($this->config
['route']['home']['name'], $this->config
['route']['home']['context']);
518 //Catch obvious transport exception
519 } catch(TransportExceptionInterface
$e) {
520 //Add error message mail unreachable
521 $form->get('mail')->addError(new FormError($this->translator
->trans('Unable to reach account', [], $this->alias
)));
528 return $this->render(
530 $this->config
['recover']['view']['name'],
532 ['recover' => $form->createView()]+
$this->config
['recover']['view']['context']
537 * Register an account
539 * @param Request $request The request
540 * @return Response The response
542 public function register(Request
$request): Response
{
544 if (!empty($_POST['register']['mail'])) {
546 $this->logger
->emergency(
547 //Translated register informations
548 $this->translator
->trans(
549 'register: mail=%mail% locale=%locale% confirm=%confirm% ip=%ip%',
551 '%mail%' => $postMail = $_POST['register']['mail'],
552 '%locale%' => $request->getLocale(),
553 '%confirm%' => $this->router
->generate(
554 $this->config
['route']['confirm']['name'],
555 //Prepend subscribe context with tag
557 'mail' => $postSmail = $this->slugger
->short($postMail),
558 'hash' => $this->slugger
->hash($postSmail)
559 ]+
$this->config
['route']['confirm']['context'],
560 UrlGeneratorInterface
::ABSOLUTE_URL
562 '%ip%' => $request->getClientIp()
575 $reflection = new \
ReflectionClass($this->config
['class']['user']);
578 $user = $reflection->newInstance('', '');
580 //Create the RegisterType form and give the proper parameters
581 $form = $this->factory
->create($this->config
['register']['view']['form'], $user, [
582 //Set action to register route name and context
583 'action' => $this->generateUrl($this->config
['route']['register']['name'], $this->config
['route']['register']['context']),
587 'civility_class' => $this->config
['class']['civility'],
588 //Set civility default
589 'civility_default' => $this->doctrine
->getRepository($this->config
['class']['civility'])->findOneByTitle($this->config
['default']['civility']),
593 'translation_domain' => $this->alias
594 ]+
($this->checker
->isGranted('ROLE_'.strtoupper($this->config
['default']['admin']))?$this->config
['register']['admin']:$this->config
['register']['field']));
597 if ($request->isMethod('POST')) {
598 //Refill the fields in case the form is not valid.
599 $form->handleRequest($request);
601 //With form submitted and valid
602 if ($form->isSubmitted() && $form->isValid()) {
604 $data = $form->getData();
607 $user->setPassword($this->hasher
->hashPassword($user, $user->getPassword()));
610 $this->manager
->persist($user);
612 //Iterate on default group
613 foreach($this->config
['default']['group'] as $i => $groupTitle) {
615 if (($group = $this->doctrine
->getRepository($this->config
['class']['group'])->findOneByTitle($groupTitle))) {
617 //XXX: see vendor/symfony/security-core/Role/Role.php
618 $user->addGroup($group);
622 //XXX: consider missing group as fatal
623 throw new \
Exception(sprintf('Group %s listed in %s.default.group[%d] not found by title', $groupTitle, $this->alias
, $i));
629 'recipient_mail' => $user->getMail(),
630 'recipient_name' => $user->getRecipientName()
631 ] +
array_replace_recursive(
632 $this->config
['context'],
633 $this->config
['register']['view']['context'],
634 $this->config
['register']['mail']['context']
637 //Generate each route route
638 foreach($this->config
['register']['route'] as $route => $tag) {
639 //Only process defined routes
640 if (!empty($this->config
['route'][$route])) {
641 //Process for confirm mail url
642 if ($route == 'confirm') {
643 //Set the url in context
644 $context[$tag] = $this->router
->generate(
645 $this->config
['route'][$route]['name'],
646 //Prepend register context with tag
648 'mail' => $smail = $this->slugger
->short($context['recipient_mail']),
649 'hash' => $this->slugger
->hash($smail)
650 ]+
$this->config
['route'][$route]['context'],
651 UrlGeneratorInterface
::ABSOLUTE_URL
658 $context['subject'] = $subject = ucfirst(
659 $this->translator
->trans(
660 $this->config
['register']['mail']['subject'],
661 $this->slugger
->flatten($context, null, '.', '%', '%'),
667 $message = (new TemplatedEmail())
669 ->from(new Address($this->config
['contact']['address'], $this->translator
->trans($this->config
['contact']['name'], [], $this->alias
)))
671 //XXX: remove the debug set in vendor/symfony/mime/Address.php +46
672 ->to(new Address($context['recipient_mail'], $context['recipient_name']))
674 ->subject($context['subject'])
676 //Set path to twig templates
677 ->htmlTemplate($this->config
['register']['mail']['html'])
678 ->textTemplate($this->config
['register']['mail']['text'])
683 //Try saving in database
686 $this->manager
->flush();
689 $this->addFlash('notice', $this->translator
->trans('Account created', [], $this->alias
));
691 //Try sending message
692 //XXX: mail delivery may silently fail
695 $this->mailer
->send($message);
697 //Add verification notice
698 $this->addFlash('notice', $this->translator
->trans('Your verification mail has been sent, to activate your account you must follow the confirmation link inside', [], $this->alias
));
701 $this->addFlash('warning', $this->translator
->trans('If you did not receive a verification mail, check your Spam or Junk mail folders', [], $this->alias
));
703 //Redirect on home route to cleanup form
704 return $this->redirectToRoute($this->config
['route']['home']['name'], $this->config
['route']['home']['context']);
705 //Catch obvious transport exception
706 } catch(TransportExceptionInterface
$e) {
707 //Add error message mail unreachable
708 $form->get('mail')->addError(new FormError($this->translator
->trans('Unable to reach account', [], $this->alias
)));
710 //Catch double subscription
711 } catch (UniqueConstraintViolationException
$e) {
712 //Add error message mail already exists
713 $this->addFlash('error', $this->translator
->trans('The account already exists', [], $this->alias
));
719 return $this->render(
721 $this->config
['register']['view']['name'],
723 ['register' => $form->createView()]+
$this->config
['register']['view']['context']