<?php
namespace App\Security;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
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;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Routing\RouterInterface;
class LoginFormAuthenticator extends AbstractFormLoginAuthenticator
{
use TargetPathTrait;
private $entityManager;
private $urlGenerator;
private $csrfTokenManager;
private $passwordEncoder;
private $route;
public function __construct(RouterInterface $route,EntityManagerInterface $entityManager, UrlGeneratorInterface $urlGenerator, CsrfTokenManagerInterface $csrfTokenManager, UserPasswordEncoderInterface $passwordEncoder)
{
$this->entityManager = $entityManager;
$this->urlGenerator = $urlGenerator;
$this->csrfTokenManager = $csrfTokenManager;
$this->passwordEncoder = $passwordEncoder;
$this->router = $route;
}
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->entityManager->getRepository(User::class)->findOneBy(['email' => $credentials['email']]);
if (!$user) {
// fail authentication with a custom error
throw new CustomUserMessageAuthenticationException("Email n'existe pas.");
}
$date_now = new \DateTime();
if(!$user->getIsEnabled()) {
// fail authentication with a custom error
throw new CustomUserMessageAuthenticationException('Votre compte est désactivé.');
}
if($user->getIsArchived()) {
// fail authentication with a custom error
throw new CustomUserMessageAuthenticationException('Votre compte est supprimé.');
}
return $user;
}
public function checkCredentials($credentials, UserInterface $user)
{
return $this->passwordEncoder->isPasswordValid($user, $credentials['password']);
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
if ($request->hasSession()) {
if($exception->getMessage() == 'Authentication failed because App\Security\LoginFormAuthenticator::checkCredentials() did not return true.')
$request->getSession()->set(Security::AUTHENTICATION_ERROR, new CustomUserMessageAuthenticationException('Mot de passe invalide.'));
else
$request->getSession()->set(Security::AUTHENTICATION_ERROR, $exception);
}
if ($request->isXmlHttpRequest()) {
$rep =array(
'redirect'=>'',
'success'=>false,
'erreur'=>$exception->getMessage() == 'Authentication failed because App\Security\LoginFormAuthenticator::checkCredentials() did not return true.' ? 'Mot de passe invalide.':$exception->getMessage(),
);
$response = new Response();
$response->setContent(json_encode($rep));
$response->setStatusCode(200);
return $response;
}
$url = $this->urlGenerator->generate('app_login');
if('app_login' === $request->attributes->get('_route')) {
$url = $this->urlGenerator->generate('app_login');
}
return new RedirectResponse($url);
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
$Roles = $token->getUser()->getRoles();
$user = $token->getUser();
$user->setDerniereConnecxion(new \DateTime('now',new \DateTimeZone('Europe/Paris')));
$this->entityManager->persist($user);
$this->entityManager->flush();
if (in_array("ROLE_SUPER_ADMINISTRATOR", $Roles) or in_array("ROLE_ADMIN", $Roles)){
return new RedirectResponse($this->urlGenerator->generate('admin_project_list_home'));
}else if (in_array("ROLE_DEV", $Roles) or in_array("ROLE_EPC", $Roles) or in_array("ROLE_RESPONSABLE", $Roles) or in_array("ROLE_RESPONSABLE_DEVELOPPEMENT", $Roles) or in_array("ROLE_CONSTRUCTEUR", $Roles)){
return new RedirectResponse($this->urlGenerator->generate('user_project_view'));
} else if (in_array("ROLE_GESTION_FINANCIER", $Roles)){
return new RedirectResponse($this->urlGenerator->generate('admin_project_list_home'));
} else if (in_array("ROLE_OPERATEUR_FINANCIER", $Roles)){
return new RedirectResponse($this->urlGenerator->generate('admin_facture_finance_liste'));
} else if (in_array("ROLE_DEVELOPPEMENT_ANALYSTE", $Roles) or in_array("ROLE_ANALYSTE", $Roles) or in_array("ROLE_ASSET_MANAGER", $Roles) or in_array("ROLE_COMPTABLE", $Roles) or in_array("ROLE_ADMINISTRATEUR_FINANCIER", $Roles)){
return new RedirectResponse($this->urlGenerator->generate('admin_facture_finance_liste'));
} else if (in_array("ROLE_AUDITEUR", $Roles)){
return new RedirectResponse($this->urlGenerator->generate('admin_project_list_home'));
} else if (in_array("ROLE_MAITRE_OEUVRE", $Roles) or in_array("ROLE_AMO", $Roles) or in_array("ROLE_MACON", $Roles) or in_array("ROLE_CONSTRUCTEUR", $Roles) or in_array("ROLE_CHARPENTIER", $Roles) or in_array("ROLE_ELECTRICIEN", $Roles) or in_array("ROLE_POSEUR", $Roles) ){
return new RedirectResponse($this->urlGenerator->generate('intervenant_project_view'));
} else if (in_array("ROLE_FOURNISSEUR", $Roles)){
return new RedirectResponse($this->urlGenerator->generate('intervenant_project_view'));
}
if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) {
return new RedirectResponse($targetPath);
}
// For example : return new RedirectResponse($this->urlGenerator->generate('some_route'));
throw new \Exception('TODO: provide a valid redirect inside '.__FILE__);
}
protected function getLoginUrl()
{
return $this->urlGenerator->generate('app_login');
}
}