You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

141 lines
4.9KB

  1. <?php
  2. namespace Lc\SovBundle\Authenticator;
  3. use Lc\SovBundle\Model\User\UserInterface;
  4. use Lc\SovBundle\Doctrine\EntityManager;
  5. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  6. use Symfony\Component\HttpFoundation\RedirectResponse;
  7. use Symfony\Component\HttpFoundation\Request;
  8. use Symfony\Component\Security\Core\User\UserInterface as SfUserInterface;
  9. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  10. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  11. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  12. use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
  13. use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
  14. use Symfony\Component\Security\Core\Security;
  15. use Symfony\Component\Security\Core\User\UserProviderInterface;
  16. use Symfony\Component\Security\Csrf\CsrfToken;
  17. use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
  18. use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;
  19. use Symfony\Component\Security\Guard\PasswordAuthenticatedInterface;
  20. use Symfony\Component\Security\Http\Util\TargetPathTrait;
  21. class LoginFormAuthenticator extends AbstractFormLoginAuthenticator implements PasswordAuthenticatedInterface
  22. {
  23. use TargetPathTrait;
  24. public const LOGIN_ROUTE = 'sov_login';
  25. private $entityManager;
  26. private $urlGenerator;
  27. private $csrfTokenManager;
  28. private $passwordEncoder;
  29. protected $parameterBag;
  30. public function __construct(
  31. EntityManager $entityManager,
  32. UrlGeneratorInterface $urlGenerator,
  33. CsrfTokenManagerInterface $csrfTokenManager,
  34. UserPasswordEncoderInterface $passwordEncoder,
  35. ParameterBagInterface $parameterBag
  36. )
  37. {
  38. $this->entityManager = $entityManager;
  39. $this->urlGenerator = $urlGenerator;
  40. $this->csrfTokenManager = $csrfTokenManager;
  41. $this->passwordEncoder = $passwordEncoder;
  42. $this->parameterBag = $parameterBag;
  43. }
  44. public function supports(Request $request)
  45. {
  46. return self::LOGIN_ROUTE === $request->attributes->get('_route')
  47. && $request->isMethod('POST');
  48. }
  49. public function getCredentials(Request $request)
  50. {
  51. $credentials = [
  52. 'email' => $request->request->get('email'),
  53. 'password' => $request->request->get('password'),
  54. 'csrf_token' => $request->request->get('_csrf_token'),
  55. ];
  56. $request->getSession()->set(
  57. Security::LAST_USERNAME,
  58. $credentials['email']
  59. );
  60. return $credentials;
  61. }
  62. public function getUser($credentials, UserProviderInterface $userProvider)
  63. {
  64. $token = new CsrfToken('authenticate', $credentials['csrf_token']);
  65. if (!$this->csrfTokenManager->isTokenValid($token)) {
  66. throw new InvalidCsrfTokenException();
  67. }
  68. $user = $this->entityManager->getRepository(UserInterface::class)->findOneBy(
  69. ['email' => $credentials['email']]
  70. );
  71. if (!$user) {
  72. // fail authentication with a custom error
  73. throw new CustomUserMessageAuthenticationException('Email could not be found.');
  74. }
  75. return $user;
  76. }
  77. public function checkCredentials($credentials, SfUserInterface $user)
  78. {
  79. return $this->passwordEncoder->isPasswordValid($user, $credentials['password']);
  80. }
  81. /**
  82. * Used to upgrade (rehash) the user's password automatically over time.
  83. */
  84. public function getPassword($credentials): ?string
  85. {
  86. return $credentials['password'];
  87. }
  88. public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $providerKey)
  89. {
  90. $routeName = 'home';
  91. $email = $request->request->get('email');
  92. $loginRedirection = $this->parameterBag->get('lc_sov.login_redirection');
  93. $useReferer = $loginRedirection['redirect_referer'];
  94. $rolesRedirection = $loginRedirection['roles_redirection'];
  95. if (isset($useReferer) && $useReferer == true) {
  96. $url = $request->request->get('_target_path');
  97. } else {
  98. $user = $this->entityManager->getRepository(UserInterface::class)->findOneBy(['email' => $email]);
  99. if (!empty($user)) {
  100. $roles = $user->getRoles();
  101. foreach ($rolesRedirection as $roleRedirect) {
  102. if (array_search($roleRedirect['role'], $roles)) {
  103. $routeName = $roleRedirect['redirect'];
  104. }
  105. }
  106. }
  107. }
  108. if (isset($url) && !empty($url)) {
  109. return new RedirectResponse($url);
  110. } else {
  111. return new RedirectResponse($this->urlGenerator->generate($routeName));
  112. }
  113. }
  114. protected function getLoginUrl()
  115. {
  116. return $this->urlGenerator->generate(self::LOGIN_ROUTE);
  117. }
  118. }