src/Security/Accesos/LoginAuthenticator.php line 66

Open in your IDE?
  1. <?php
  2. namespace App\Security\Accesos;
  3. use App\Entity\Accesos\Usuario;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use Symfony\Component\HttpFoundation\RedirectResponse;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  9. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  10. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  11. use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
  12. use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
  13. use Symfony\Component\Security\Core\Security;
  14. use Symfony\Component\Security\Core\User\UserInterface;
  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. use App\Entity\Accesos\Log;
  22. class LoginAuthenticator extends AbstractFormLoginAuthenticator implements PasswordAuthenticatedInterface {
  23.     use TargetPathTrait;
  24.     public const LOGIN_ROUTE 'app_login';
  25.     private $entityManager;
  26.     private $urlGenerator;
  27.     private $csrfTokenManager;
  28.     private $passwordEncoder;
  29.     public function __construct(EntityManagerInterface $entityManagerUrlGeneratorInterface $urlGeneratorCsrfTokenManagerInterface $csrfTokenManagerUserPasswordEncoderInterface $passwordEncoder) {
  30.         $this->entityManager $entityManager;
  31.         $this->urlGenerator $urlGenerator;
  32.         $this->csrfTokenManager $csrfTokenManager;
  33.         $this->passwordEncoder $passwordEncoder;
  34.     }
  35.     public function supports(Request $request): bool {
  36.         return self::LOGIN_ROUTE === $request->attributes->get('_route') && $request->isMethod('POST');
  37.     }
  38.     public function getCredentials(Request $request) {
  39.         $credentials = [
  40.             'email' => $request->request->get('email'),
  41.             'password' => $request->request->get('password'),
  42.             'csrf_token' => $request->request->get('_csrf_token'),
  43.         ];
  44.         $request->getSession()->set(
  45.                 Security::LAST_USERNAME,
  46.                 $credentials['email']
  47.         );
  48.         return $credentials;
  49.     }
  50.     public function getUser($credentialsUserProviderInterface $userProvider): ?Usuario {
  51.         $token = new CsrfToken('authenticate'$credentials['csrf_token']);
  52.         if (!$this->csrfTokenManager->isTokenValid($token)) {
  53.             throw new InvalidCsrfTokenException();
  54.         }
  55.         $user $this->entityManager->getRepository(Usuario::class)->findOneBy(['email' => $credentials['email']]);
  56.         if (!$user) {
  57.             // fail authentication with a custom error
  58.             throw new CustomUserMessageAuthenticationException('emailError.');
  59.         } else {
  60.             if (!$user->getHabilitado()) {
  61.                 throw new CustomUserMessageAuthenticationException('usuarioError.');
  62.             }
  63.         }
  64.         return $user;
  65.     }
  66.     public function checkCredentials($credentialsUserInterface $user): bool {
  67.         return $this->passwordEncoder->isPasswordValid($user$credentials['password']);
  68.     }
  69.     /**
  70.      * Used to upgrade (rehash) the user's password automatically over time.
  71.      */
  72.     public function getPassword($credentials): ?string {
  73.         return $credentials['password'];
  74.     }
  75.     public function onAuthenticationSuccess(Request $requestTokenInterface $token$providerKey): ?Response {
  76.         $this->addUsuarioAlLog($request);
  77.         if ($targetPath $this->getTargetPath($request->getSession(), $providerKey)) {
  78.             return new RedirectResponse($targetPath);
  79.         }
  80.         $usuario $this->entityManager->getRepository(Usuario::class)->findOneBy(['email' => $request->get('email')]);
  81.         if (in_array('ROLE_EXTERNO'$usuario->getRoles(), true)) {
  82.             return new RedirectResponse($this->urlGenerator->generate('app_comun_proyecto_index'));
  83.         }
  84.         return new RedirectResponse($this->urlGenerator->generate('app_default'));
  85.         //  throw new \Exception('TODO: provide a valid redirect inside '.__FILE__);
  86.     }
  87.     protected function getLoginUrl(): string {
  88.         return $this->urlGenerator->generate(self::LOGIN_ROUTE);
  89.     }
  90.     protected function addUsuarioAlLog(Request $request) {
  91.         $user $this->entityManager->getRepository(Usuario::class)->findOneBy(['email' => $request->get('email')]);
  92.         $log = new Log();
  93.         $log->setNombre($user->getNombre());
  94.         $log->setEmail($user->getEmail());
  95.         $log->setFecha(date_create('now'));
  96.         $this->entityManager->persist($log);
  97.         $this->entityManager->flush();
  98.     }
  99. }