<?php
namespace App\Security;
use App\Entity\Log;
use App\Entity\User;
use App\Repository\UserRepository;
use App\Service\Utils\Constante\AbonnementConst;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Csrf\CsrfToken;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;
use Symfony\Component\Security\Http\Util\TargetPathTrait;
class LoginFormAuthenticator extends AbstractFormLoginAuthenticator
{
use TargetPathTrait;
private $entityManager;
private $urlGenerator;
private $csrfTokenManager;
private $passwordEncoder;
private UserRepository $userRepository;
public function __construct(EntityManagerInterface $entityManager, UserRepository $userRepository, UrlGeneratorInterface $urlGenerator, CsrfTokenManagerInterface $csrfTokenManager, UserPasswordEncoderInterface $passwordEncoder)
{
$this->entityManager = $entityManager;
$this->urlGenerator = $urlGenerator;
$this->csrfTokenManager = $csrfTokenManager;
$this->passwordEncoder = $passwordEncoder;
$this->userRepository = $userRepository;
}
public function supports(Request $request)
{
return 'app_login' === $request->attributes->get('_route')
&& $request->isMethod('POST');
}
public function getCredentials(Request $request)
{
$credentials = [
'email' => $request->request->get('email'),
'password' => $request->request->get('password'),
'csrf_token' => $request->request->get('_csrf_token'),
];
$request->getSession()->set(
Security::LAST_USERNAME,
$credentials['email']
);
return $credentials;
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
$token = new CsrfToken('authenticate', $credentials['csrf_token']);
if (!$this->csrfTokenManager->isTokenValid($token)) {
throw new InvalidCsrfTokenException();
}
$user = $this->userRepository->findOneBy(['email' => $credentials['email']]);
if (!$user || $user->getPassword() === null) {
// fail authentication with a custom error
throw new CustomUserMessageAuthenticationException('Email ou mot de passe non valide');
}
$now = new \DateTimeImmutable();
if(
$user->getCompany()->getStatus() === AbonnementConst::STATUS_SUSPENDED ||
($user->getCompany()->getExpiredAt() !== null && $user->getCompany()->getExpiredAt() <= $now)
){
throw new CustomUserMessageAuthenticationException('Votre compte a été suspendu. Contactez votre administrateur pour en savoir plus.');
}
return $user;
}
public function checkCredentials($credentials, UserInterface $user)
{
return $this->passwordEncoder->isPasswordValid($user, $credentials['password']);
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
/* @var $user User*/
$user = $token->getUser();
$lastLoginAt = $user->getLastLoginAt();
$this->setLastLoginAt($user);
if($lastLoginAt === null){
return new RedirectResponse($this->urlGenerator->generate('profil'));
}
if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) {
return new RedirectResponse($targetPath);
}
return new RedirectResponse($this->urlGenerator->generate('user_dashboard'));
}
protected function getLoginUrl()
{
return $this->urlGenerator->generate('app_login');
}
private function setLastLoginAt(User $user){
//TODO à voir si on garde le champ lastLoginAt ou si on utilise celui des logs
$date = new \DateTime("now", new \DateTimeZone("Europe/Paris"));
$user->setLastLoginAt($date);
$this->entityManager->persist($user);
//Persistence en BD pour les stats - date sur createdAt
$log = new Log();
$log->setUser( $user );
$log->setEvent('login');
$log->setSources(['ip'=>!empty($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : "",'date'=>$date->format('Y-m-d H:i'),'login'=>$user->getEmail()]);
$this->entityManager->persist($log);
$this->entityManager->flush();
}
}