<?php
namespace App\Security;
use App\Entity\User;
use App\Entity\Panier;
use App\Entity\PanierProduit;
use App\Entity\Ref;
use App\Entity\Typeref;
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\Exception\InvalidCsrfTokenException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Csrf\CsrfToken;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Component\Security\Http\Util\TargetPathTrait;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;
use Symfony\Component\Security\Http\LoginLink\Exception\InvalidLoginLinkExceptionInterface;
use Symfony\Component\Security\Http\LoginLink\LoginLinkHandlerInterface;
class ParentLoginFormAuthenticator extends AbstractAuthenticator implements AuthenticationEntryPointInterface
{
use TargetPathTrait;
private $entityManager;
private $urlGenerator;
private $csrfTokenManager;
private $passwordEncoder;
private $session;
private $signatureHasher;
public function __construct(EntityManagerInterface $entityManager, UrlGeneratorInterface $urlGenerator, CsrfTokenManagerInterface $csrfTokenManager, UserPasswordHasherInterface $passwordEncoder, SessionInterface $session, LoginLinkHandlerInterface $signatureHasher)
{
$this->entityManager = $entityManager;
$this->urlGenerator = $urlGenerator;
$this->csrfTokenManager = $csrfTokenManager;
$this->passwordEncoder = $passwordEncoder;
$this->session = $session;
$this->signatureHasher = $signatureHasher;
}
public function supports(Request $request): ?bool
{
return 'app_back_Parent' === $request->attributes->get('_route')
&& $request->isMethod('POST')
|| 'login_check' === $request->attributes->get('_route');
}
public function authenticate(Request $request): Passport
{
$passwordlessLogin = false;
$credentials = [
'email' => $request->request->get('email'),
'password' => $request->request->get('password'),
// 'codesejour' => $request->request->get('codesejour'),
'csrf_token' => $request->request->get('_csrf_token'),
];
if ($request->attributes->get('_route') === 'login_check') {
$email = $request->query->get('user');
try {
$user = $this->signatureHasher->consumeLoginLink($request);
} catch (InvalidLoginLinkExceptionInterface $e) {
throw new CustomUserMessageAuthenticationException($e->getMessage());
}
if (!$user) {
throw new CustomUserMessageAuthenticationException("Ce lien a expiré.");
}
$passwordlessLogin = true;
$credentials = [
'email' => $email,
'password' => $request->request->get('password'),
'csrf_token' => $request->request->get('_csrf_token')
];
}
$request->getSession()->set(
Security::LAST_USERNAME,
$credentials['email']
);
$token = new CsrfToken('authenticate', $credentials['csrf_token']);
if (!$this->csrfTokenManager->isTokenValid($token) && $passwordlessLogin == false) {
throw new InvalidCsrfTokenException();
}
$parent = $this->entityManager->getRepository(User::class)->findOneBy(['email' => $credentials['email']]);
$user = $parent;
if ($user) {
if ($user->getActivatemail() == null) {
throw new CustomUserMessageAuthenticationException("vous n’avez pas encore cliquer sur votre lien d’activation reçu par mail au moment de la création de votre compte.");
}
$Products = $this->session->get("Panier");
//Touhemi22-04:Initialisation de panier.
$typeref = $this->entityManager->getRepository(Typeref::class)->find(8);
$statutPanier = $this->entityManager->getRepository(Ref::class)->findOneBy(array("libiller" => "creer", "typeref" => $typeref));
$panierTrace = $this->entityManager->getRepository(Panier::class)->findOneBy(array("creerPar" => $user, "statut" => $statutPanier));
if ($Products == null) {
$Products = [];
}
if ($panierTrace == null) {
$panierTrace = new Panier();
$dateNow = new \Datetime();
$panierTrace->setDateCreation($dateNow);
$panierTrace->setCreerPar($user);
$panierTrace->setStatut($statutPanier);
$this->entityManager->persist($panierTrace);
$this->entityManager->flush();
}
$panierProduit = $this->entityManager->getRepository(PanierProduit::class)->findBy(array("idPanier" => $panierTrace));
foreach ($panierProduit as $produit) {
$p = [];
$p["id"] = $produit->getIdProduit()->getId();
$p["nom"] = $produit->getIdProduit()->getType()->getLabeletype();
$p["ident"] = $produit->getIdProduit()->getLabele();
$p["codesejour"] = $produit->getIdProduit()->getIdsjour()->getcodeSejour();
$montantTTC = '';
if ($produit->getIdProduit()->getIdConditionnement()) {
$montantTTC = $produit->getIdProduit()->getIdConditionnement()->getMontantTTC();
}
$p["mnt"] = $montantTTC;
$p["path"] ="";
if( $produit->getIdProduit()->getType())
{
if($produit->getIdProduit()->getType()->getAttachements()[0] !=null)
{
$p["path"] = $produit->getIdProduit()->getType()->getAttachements()[0]->getIdAttachement()->getPath();}}
$condition = '';
if ($produit->getIdProduit()->getIdConditionnement()) {
$condition = $produit->getIdProduit()->getIdConditionnement()->getId();
}
$p["condition"] = $condition;
$p["qte"] = $produit->getQuantite();
array_push($Products, $p);
}
$this->session->set('Panier', $Products);
}
if (!$user) {
// fail authentication with a custom error
throw new CustomUserMessageAuthenticationException("Votre identifiant est votre mail renseigné lors de la création de compte parent.");
}
if (!$user->hasRole('ROLE_PARENT')) {
throw new CustomUserMessageAuthenticationException('Votre identifiant est votre mail renseigné lors de la création de compte parent.');
}
if ($passwordlessLogin == false) {
if (!$this->passwordEncoder->isPasswordValid($user, $credentials['password'])) {
throw new CustomUserMessageAuthenticationException("Votre mot de passe est celui que vous avez renseigné lors de la création de votre compte parent.");
}
}
return new SelfValidatingPassport(new UserBadge($credentials['email']));
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
return new RedirectResponse($this->urlGenerator->generate('CodeSejour'));
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
{
return new RedirectResponse(
$this->urlGenerator->generate('app_back_Parent')
);
}
public function start(Request $request, ?AuthenticationException $authException = null)
{
return new RedirectResponse(
$this->urlGenerator->generate('app_back_Parent')
);
}
}