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 Rapsys\UserBundle\RapsysUserBundle
;
18 use Symfony\Bridge\Twig\Mime\TemplatedEmail
;
19 use Symfony\Component\Form\FormError
;
20 use Symfony\Component\HttpFoundation\Request
;
21 use Symfony\Component\HttpFoundation\Response
;
22 use Symfony\Component\HttpKernel\Exception\BadRequestHttpException
;
23 use Symfony\Component\Mailer\Exception\TransportExceptionInterface
;
24 use Symfony\Component\Mime\Address
;
25 use Symfony\Component\Routing\Generator\UrlGeneratorInterface
;
26 use Symfony\Component\Security\Http\Authentication\AuthenticationUtils
;
31 class UserController
extends AbstractController
{
35 * @param Request $request The request
36 * @return Response The response
38 public function index(Request
$request): Response
{
40 if (!$this->checker
->isGranted($this->config
['default']['admin'])) {
42 throw $this->createAccessDeniedException($this->translator
->trans('Unable to list users'));
46 $this->context
['count'] = $this->doctrine
->getRepository($this->config
['class']['user'])->findCountAsInt();
48 //With not enough users
49 if ($this->context
['count'] - $this->page
* $this->limit
< 0) {
51 throw $this->createNotFoundException($this->translator
->trans('Unable to find users'));
55 $this->context
['users'] = $this->doctrine
->getRepository($this->config
['class']['user'])->findAllAsArray($this->page
, $this->limit
);
60 $this->config
['index']['view']['name'],
62 $this->context+
$this->config
['index']['view']['context']
67 * Confirm account from mail link
69 * @param Request $request The request
70 * @param string $hash The hashed password
71 * @param string $mail The shorted mail address
72 * @return Response The response
74 public function confirm(Request
$request, string $hash, string $mail): Response
{
76 if ($hash != $this->slugger
->hash($mail)) {
78 throw new BadRequestHttpException($this->translator
->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash]));
82 $mail = $this->slugger
->unshort($smail = $mail);
85 if (filter_var($mail, FILTER_VALIDATE_EMAIL
) === false) {
87 //XXX: prevent slugger reverse engineering by not displaying decoded mail
88 throw new BadRequestHttpException($this->translator
->trans('Invalid %field% field: %value%', ['%field%' => 'mail', '%value%' => $smail]));
91 //Without existing registrant
92 if (!($user = $this->doctrine
->getRepository($this->config
['class']['user'])->findOneByMail($mail))) {
93 //Add error message mail already exists
94 //XXX: prevent slugger reverse engineering by not displaying decoded mail
95 $this->addFlash('error', $this->translator
->trans('Account do not exists'));
97 //Redirect to register view
98 return $this->redirectToRoute($this->config
['route']['register']['name'], $this->config
['route']['register']['context']);
102 $user->setActive(true);
105 $this->manager
->persist($user);
108 $this->manager
->flush();
110 //Add error message mail already exists
111 $this->addFlash('notice', $this->translator
->trans('Your account has been activated'));
113 //Redirect to user view
114 return $this->redirectToRoute($this->config
['route']['edit']['name'], ['mail' => $smail, 'hash' => $this->slugger
->hash($smail)]+
$this->config
['route']['edit']['context']);
118 * Edit account by shorted mail
120 * @param Request $request The request
121 * @param string $hash The hashed password
122 * @param string $mail The shorted mail address
123 * @return Response The response
125 public function edit(Request
$request, string $hash, string $mail): Response
{
127 if ($hash != $this->slugger
->hash($mail)) {
129 throw new BadRequestHttpException($this->translator
->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash]));
133 $mail = $this->slugger
->unshort($smail = $mail);
135 //With existing subscriber
136 if (empty($user = $this->doctrine
->getRepository($this->config
['class']['user'])->findOneByMail($mail))) {
138 //XXX: prevent slugger reverse engineering by not displaying decoded mail
139 throw $this->createNotFoundException($this->translator
->trans('Unable to find account'));
142 //Prevent access when not admin, user is not guest and not currently logged user
143 if (!$this->checker
->isGranted($this->config
['default']['admin']) && $user != $this->security
->getUser() || !$this->checker
->isGranted('IS_AUTHENTICATED_FULLY')) {
144 //Throw access denied
145 //XXX: prevent slugger reverse engineering by not displaying decoded mail
146 throw $this->createAccessDeniedException($this->translator
->trans('Unable to access user'));
149 //Create the EditType form and give the proper parameters
150 $edit = $this->factory
->create($this->config
['edit']['view']['edit'], $user, [
151 //Set action to edit route name and context
152 'action' => $this->generateUrl($this->config
['route']['edit']['name'], ['mail' => $smail, 'hash' => $this->slugger
->hash($smail)]+
$this->config
['route']['edit']['context']),
154 'civility_class' => $this->config
['class']['civility'],
155 //Set civility default
156 'civility_default' => $this->doctrine
->getRepository($this->config
['class']['civility'])->findOneByTitle($this->config
['default']['civility']),
159 ]+
($this->checker
->isGranted($this->config
['default']['admin'])?$this->config
['edit']['admin']:$this->config
['edit']['field']));
162 if ($this->checker
->isGranted($this->config
['default']['admin'])) {
163 //Create the EditType form and give the proper parameters
164 $reset = $this->factory
->create($this->config
['edit']['view']['reset'], $user, [
165 //Set action to edit route name and context
166 'action' => $this->generateUrl($this->config
['route']['edit']['name'], ['mail' => $smail, 'hash' => $this->slugger
->hash($smail)]+
$this->config
['route']['edit']['context']),
172 if ($request->isMethod('POST')) {
173 //Refill the fields in case the form is not valid.
174 $reset->handleRequest($request);
176 //With reset submitted and valid
177 if ($reset->isSubmitted() && $reset->isValid()) {
179 $data = $reset->getData();
182 $data->setPassword($this->hasher
->hashPassword($data, $data->getPassword()));
185 $this->manager
->persist($data);
187 //Flush to get the ids
188 $this->manager
->flush();
191 $this->addFlash('notice', $this->translator
->trans('Account password updated'));
193 //Redirect to cleanup the form
194 return $this->redirectToRoute($this->config
['route']['edit']['name'], ['mail' => $smail = $this->slugger
->short($mail), 'hash' => $this->slugger
->hash($smail)]+
$this->config
['route']['edit']['context']);
199 $this->config
['edit']['view']['context']['reset'] = $reset->createView();
203 if ($request->isMethod('POST')) {
204 //Refill the fields in case the form is not valid.
205 $edit->handleRequest($request);
207 //With edit submitted and valid
208 if ($edit->isSubmitted() && $edit->isValid()) {
210 $data = $edit->getData();
213 $this->manager
->persist($data);
215 //Try saving in database
217 //Flush to get the ids
218 $this->manager
->flush();
221 $this->addFlash('notice', $this->translator
->trans('Account updated'));
223 //Redirect to cleanup the form
224 return $this->redirectToRoute($this->config
['route']['edit']['name'], ['mail' => $smail = $this->slugger
->short($mail), 'hash' => $this->slugger
->hash($smail)]+
$this->config
['route']['edit']['context']);
225 //Catch double slug or mail
226 } catch (UniqueConstraintViolationException
$e) {
227 //Add error message mail already exists
228 $this->addFlash('error', $this->translator
->trans('Account already exists'));
232 //XXX: prefer a reset on login to force user unspam action
233 } elseif (!$this->checker
->isGranted($this->config
['default']['admin'])) {
235 $this->addFlash('notice', $this->translator
->trans('To change your password login with your mail and any password then follow the procedure'));
239 return $this->render(
241 $this->config
['edit']['view']['name'],
243 ['edit' => $edit->createView(), 'sent' => $request->query
->get('sent', 0)]+
$this->config
['edit']['view']['context']
250 * @param Request $request The request
251 * @param AuthenticationUtils $authenticationUtils The authentication utils
252 * @param ?string $hash The hashed password
253 * @param ?string $mail The shorted mail address
254 * @return Response The response
256 public function login(Request
$request, AuthenticationUtils
$authenticationUtils, ?string $hash, ?string $mail): Response
{
257 //Create the LoginType form and give the proper parameters
258 $login = $this->factory
->create($this->config
['login']['view']['form'], null, [
259 //Set action to login route name and context
260 'action' => $this->generateUrl($this->config
['route']['login']['name'], $this->config
['route']['login']['context']),
269 if (!empty($mail) && !empty($hash)) {
271 if ($hash != $this->slugger
->hash($mail)) {
273 throw new BadRequestHttpException($this->translator
->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash]));
277 $mail = $this->slugger
->unshort($smail = $mail);
280 if (filter_var($mail, FILTER_VALIDATE_EMAIL
) === false) {
282 throw new BadRequestHttpException($this->translator
->trans('Invalid %field% field: %value%', ['%field%' => 'mail', '%value%' => $smail]));
286 $login->get('mail')->setData($mail);
287 //Last username entered by the user
288 } elseif ($lastUsername = $authenticationUtils->getLastUsername()) {
289 $login->get('mail')->setData($lastUsername);
292 //Get the login error if there is one
293 if ($error = $authenticationUtils->getLastAuthenticationError()) {
294 //Get translated error
295 $error = $this->translator
->trans($error->getMessageKey());
297 //Add error message to mail field
298 $login->get('mail')->addError(new FormError($error));
300 //Create the RecoverType form and give the proper parameters
301 $recover = $this->factory
->create($this->config
['recover']['view']['form'], null, [
302 //Set action to recover route name and context
303 'action' => $this->generateUrl($this->config
['route']['recover']['name'], $this->config
['route']['recover']['context']),
310 //Get recover mail entity
311 $recover->get('mail')
312 //Set mail from login form
313 ->setData($login->get('mail')->getData())
315 ->addError(new FormError($this->translator
->trans('Use this form to recover your account')));
317 //Add recover form to context
318 $context['recover'] = $recover->createView();
321 $this->addFlash('notice', $this->translator
->trans('To change your password login with your mail and any password then follow the procedure'));
325 return $this->render(
327 $this->config
['login']['view']['name'],
329 ['login' => $login->createView(), 'disabled' => $request->query
->get('disabled', 0), 'sent' => $request->query
->get('sent', 0)]+
$context+
$this->config
['login']['view']['context']
336 * @param Request $request The request
337 * @param ?string $hash The hashed password
338 * @param ?string $pass The shorted password
339 * @param ?string $mail The shorted mail address
340 * @return Response The response
342 public function recover(Request
$request, ?string $hash, ?string $pass, ?string $mail): Response
{
349 //With mail, pass and hash
350 if (!empty($mail) && !empty($pass) && !empty($hash)) {
352 if ($hash != $this->slugger
->hash($mail.$pass)) {
354 throw new BadRequestHttpException($this->translator
->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash]));
358 $mail = $this->slugger
->unshort($smail = $mail);
361 if (filter_var($mail, FILTER_VALIDATE_EMAIL
) === false) {
363 //XXX: prevent slugger reverse engineering by not displaying decoded mail
364 throw new BadRequestHttpException($this->translator
->trans('Invalid %field% field: %value%', ['%field%' => 'mail', '%value%' => $smail]));
367 //With existing subscriber
368 if (empty($user = $this->doctrine
->getRepository($this->config
['class']['user'])->findOneByMail($mail))) {
370 //XXX: prevent slugger reverse engineering by not displaying decoded mail
371 throw $this->createNotFoundException($this->translator
->trans('Unable to find account'));
374 //With unmatched pass
375 if ($pass != $this->slugger
->hash($user->getPassword())) {
377 //XXX: prevent use of outdated recover link
378 throw $this->createNotFoundException($this->translator
->trans('Outdated recover link'));
382 $context = ['mail' => $smail, 'pass' => $pass, 'hash' => $hash];
385 //Create the LoginType form and give the proper parameters
386 $form = $this->factory
->create($this->config
['recover']['view']['form'], $user, [
387 //Set action to recover route name and context
388 'action' => $this->generateUrl($this->config
['route']['recover']['name'], $context+
$this->config
['route']['recover']['context']),
389 //With user disable mail
390 'mail' => ($user === null),
391 //With user enable password
392 'password' => ($user !== null),
398 if ($request->isMethod('POST')) {
399 //Refill the fields in case the form is not valid.
400 $form->handleRequest($request);
402 //With form submitted and valid
403 if ($form->isSubmitted() && $form->isValid()) {
405 $data = $form->getData();
408 if ($user !== null) {
409 //Set hashed password
410 $hashed = $this->hasher
->hashPassword($user, $user->getPassword());
413 $pass = $this->slugger
->hash($hashed);
416 $user->setPassword($hashed);
419 $this->manager
->persist($user);
422 $this->manager
->flush();
425 $this->addFlash('notice', $this->translator
->trans('Account password updated'));
427 //Redirect to user login
428 return $this->redirectToRoute($this->config
['route']['login']['name'], ['mail' => $smail, 'hash' => $this->slugger
->hash($smail)]+
$this->config
['route']['login']['context']);
429 //Find user by data mail
430 } elseif ($user = $this->doctrine
->getRepository($this->config
['class']['user'])->findOneByMail($data['mail'])) {
433 'recipient_mail' => $user->getMail(),
434 'recipient_name' => $user->getRecipientName()
435 ] +
array_replace_recursive(
436 $this->config
['context'],
437 $this->config
['recover']['view']['context'],
438 $this->config
['recover']['mail']['context']
441 //Generate each route route
442 foreach($this->config
['recover']['route'] as $route => $tag) {
443 //Only process defined routes
444 if (!empty($this->config
['route'][$route])) {
445 //Process for recover mail url
446 if ($route == 'recover') {
447 //Set the url in context
448 $context[$tag] = $this->router
->generate(
449 $this->config
['route'][$route]['name'],
450 //Prepend recover context with tag
452 'mail' => $smail = $this->slugger
->short($context['recipient_mail']),
453 'pass' => $spass = $this->slugger
->hash($pass = $user->getPassword()),
454 'hash' => $this->slugger
->hash($smail.$spass)
455 ]+
$this->config
['route'][$route]['context'],
456 UrlGeneratorInterface
::ABSOLUTE_URL
462 //Iterate on keys to translate
463 foreach($this->config
['translate'] as $translate) {
465 $keys = explode('.', $translate);
468 $current =& $context;
470 //Iterate on each subkey
472 //Skip unset translation keys
473 if (!isset($current[current($keys)])) {
477 //Set current to subkey
478 $current =& $current[current($keys)];
479 } while(next($keys));
482 $current = $this->translator
->trans($current);
489 $context['subject'] = $subject = ucfirst(
490 $this->translator
->trans(
491 $this->config
['recover']['mail']['subject'],
492 $this->slugger
->flatten($context, null, '.', '%', '%')
497 $message = (new TemplatedEmail())
499 ->from(new Address($this->config
['contact']['address'], $this->translator
->trans($this->config
['contact']['name'])))
501 //XXX: remove the debug set in vendor/symfony/mime/Address.php +46
502 ->to(new Address($context['recipient_mail'], $context['recipient_name']))
504 ->subject($context['subject'])
506 //Set path to twig templates
507 ->htmlTemplate($this->config
['recover']['mail']['html'])
508 ->textTemplate($this->config
['recover']['mail']['text'])
513 //Try sending message
514 //XXX: mail delivery may silently fail
517 $this->mailer
->send($message);
520 $this->addFlash('notice', $this->translator
->trans('Your recovery mail has been sent, to retrieve your account follow the recuperate link inside'));
523 $this->addFlash('warning', $this->translator
->trans('If you did not receive a recovery mail, check your Spam or Junk mail folder'));
525 //Redirect on the same route with sent=1 to cleanup form
526 return $this->redirectToRoute($request->get('_route'), ['sent' => 1]+
$request->get('_route_params'), 302);
527 //Catch obvious transport exception
528 } catch(TransportExceptionInterface
$e) {
529 //Add error message mail unreachable
530 $form->get('mail')->addError(new FormError($this->translator
->trans('Unable to reach account')));
537 return $this->render(
539 $this->config
['recover']['view']['name'],
541 ['recover' => $form->createView(), 'sent' => $request->query
->get('sent', 0)]+
$this->config
['recover']['view']['context']
546 * Register an account
548 * @param Request $request The request
549 * @return Response The response
551 public function register(Request
$request): Response
{
553 if (!empty($_POST['register']['mail'])) {
555 $this->logger
->emergency(
556 $this->translator
->trans(
557 'register: mail=%mail% locale=%locale% confirm=%confirm% ip=%ip%',
559 '%mail%' => $postMail = $_POST['register']['mail'],
560 '%locale%' => $request->getLocale(),
561 '%confirm%' => $this->router
->generate(
562 $this->config
['route']['confirm']['name'],
563 //Prepend subscribe context with tag
565 'mail' => $postSmail = $this->slugger
->short($postMail),
566 'hash' => $this->slugger
->hash($postSmail)
567 ]+
$this->config
['route']['confirm']['context'],
568 UrlGeneratorInterface
::ABSOLUTE_URL
570 '%ip%' => $request->getClientIp()
577 $reflection = new \
ReflectionClass($this->config
['class']['user']);
580 $user = $reflection->newInstance('', '');
582 //Create the RegisterType form and give the proper parameters
583 $form = $this->factory
->create($this->config
['register']['view']['form'], $user, [
584 //Set action to register route name and context
585 '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']),
592 ]+
($this->checker
->isGranted($this->config
['default']['admin'])?$this->config
['register']['admin']:$this->config
['register']['field']));
595 if ($request->isMethod('POST')) {
596 //Refill the fields in case the form is not valid.
597 $form->handleRequest($request);
599 //With form submitted and valid
600 if ($form->isSubmitted() && $form->isValid()) {
602 $data = $form->getData();
605 $user->setPassword($this->hasher
->hashPassword($user, $user->getPassword()));
608 $this->manager
->persist($user);
610 //Iterate on default group
611 foreach($this->config
['default']['group'] as $i => $groupTitle) {
613 if (($group = $this->doctrine
->getRepository($this->config
['class']['group'])->findOneByTitle($groupTitle))) {
615 //XXX: see vendor/symfony/security-core/Role/Role.php
616 $user->addGroup($group);
620 //XXX: consider missing group as fatal
621 throw new \
Exception(sprintf('Group %s listed in %s.default.group[%d] not found by title', $groupTitle, RapsysUserBundle
::getAlias(), $i));
627 'recipient_mail' => $user->getMail(),
628 'recipient_name' => $user->getRecipientName()
629 ] +
array_replace_recursive(
630 $this->config
['context'],
631 $this->config
['register']['view']['context'],
632 $this->config
['register']['mail']['context']
635 //Generate each route route
636 foreach($this->config
['register']['route'] as $route => $tag) {
637 //Only process defined routes
638 if (!empty($this->config
['route'][$route])) {
639 //Process for confirm mail url
640 if ($route == 'confirm') {
641 //Set the url in context
642 $context[$tag] = $this->router
->generate(
643 $this->config
['route'][$route]['name'],
644 //Prepend register context with tag
646 'mail' => $smail = $this->slugger
->short($context['recipient_mail']),
647 'hash' => $this->slugger
->hash($smail)
648 ]+
$this->config
['route'][$route]['context'],
649 UrlGeneratorInterface
::ABSOLUTE_URL
655 //Iterate on keys to translate
656 foreach($this->config
['translate'] as $translate) {
658 $keys = explode('.', $translate);
661 $current =& $context;
663 //Iterate on each subkey
665 //Skip unset translation keys
666 if (!isset($current[current($keys)])) {
670 //Set current to subkey
671 $current =& $current[current($keys)];
672 } while(next($keys));
675 $current = $this->translator
->trans($current);
682 $context['subject'] = $subject = ucfirst(
683 $this->translator
->trans(
684 $this->config
['register']['mail']['subject'],
685 $this->slugger
->flatten($context, null, '.', '%', '%')
690 $message = (new TemplatedEmail())
692 ->from(new Address($this->config
['contact']['address'], $this->translator
->trans($this->config
['contact']['name'])))
694 //XXX: remove the debug set in vendor/symfony/mime/Address.php +46
695 ->to(new Address($context['recipient_mail'], $context['recipient_name']))
697 ->subject($context['subject'])
699 //Set path to twig templates
700 ->htmlTemplate($this->config
['register']['mail']['html'])
701 ->textTemplate($this->config
['register']['mail']['text'])
706 //Try saving in database
709 $this->manager
->flush();
711 //Add error message mail already exists
712 $this->addFlash('notice', $this->translator
->trans('Account created'));
714 //Try sending message
715 //XXX: mail delivery may silently fail
718 $this->mailer
->send($message);
720 //Redirect on the same route with sent=1 to cleanup form
721 return $this->redirectToRoute($request->get('_route'), ['sent' => 1]+
$request->get('_route_params'));
722 //Catch obvious transport exception
723 } catch(TransportExceptionInterface
$e) {
724 //Add error message mail unreachable
725 $form->get('mail')->addError(new FormError($this->translator
->trans('Unable to reach account')));
727 //Catch double subscription
728 } catch (UniqueConstraintViolationException
$e) {
729 //Add error message mail already exists
730 $this->addFlash('error', $this->translator
->trans('Account already exists'));
736 return $this->render(
738 $this->config
['register']['view']['name'],
740 ['register' => $form->createView(), 'sent' => $request->query
->get('sent', 0)]+
$this->config
['register']['view']['context']