<?php
namespace App\Security;
use App\Entity\Customer\Customer;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Persistence\ManagerRegistry;
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\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
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\Guard\PasswordAuthenticatedInterface;
use Symfony\Component\Security\Http\Util\TargetPathTrait;
use App\Service\Tools;
use App\Service\ObpAPI;
class CustomerFormAuthenticator extends AbstractFormLoginAuthenticator implements PasswordAuthenticatedInterface
{
use TargetPathTrait;
public const LOGIN_ROUTE = 'customer_login';
private $entityManager;
private $doctrine;
private $urlGenerator;
private $csrfTokenManager;
private $passwordEncoder;
private $obpAPIservice;
private $pass_valid;
private $centre_prefere = 'lons';
public function __construct(EntityManagerInterface $entityManager, UrlGeneratorInterface $urlGenerator, CsrfTokenManagerInterface $csrfTokenManager, UserPasswordEncoderInterface $passwordEncoder, ManagerRegistry $doctrine, ObpAPI $obpAPIservice)
{
$this->entityManager = $doctrine->getManager('customer');
$this->urlGenerator = $urlGenerator;
$this->csrfTokenManager = $csrfTokenManager;
$this->passwordEncoder = $passwordEncoder;
$this->obpAPIservice = $obpAPIservice;
}
public function supports(Request $request): bool
{
return self::LOGIN_ROUTE === $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'),
'g-recaptcha-response' => $request->request->get('g-recaptcha-response'),
];
$request->getSession()->set(
Security::LAST_USERNAME,
$credentials['email']
);
return $credentials;
}
public function getUser($credentials, UserProviderInterface $userProvider): ?Customer
{
$token = new CsrfToken('authenticate', $credentials['csrf_token']);
if (!$this->csrfTokenManager->isTokenValid($token)) {
throw new InvalidCsrfTokenException();
}
$dataObpAPI = array(
'email' => $credentials['email'],
'password' => $credentials['password'],
'g-recaptcha-response' => $credentials['g-recaptcha-response'],
'instance' => $this->obpAPIservice->getBaseInstance(),
);
$urlApi = $this->obpAPIservice->getContactApiUrl();
$customer_obp_infos = json_decode(
$this->obpAPIservice->CallAPI('POST', $urlApi.'/auth/users/login', json_encode($dataObpAPI))
);
// dd($credentials,$customer_obp_infos);
if (is_object($customer_obp_infos) && !$customer_obp_infos->meta->success) {
// fail authentication with a custom error
$this->pass_valid = false;
throw new CustomUserMessageAuthenticationException($customer_obp_infos->meta->message);
}
$this->pass_valid = (is_object($customer_obp_infos) && $customer_obp_infos->meta->success) ? true : false;
$user = $this->entityManager->getRepository(Customer::class)->findOneBy(['email' => $credentials['email']]);
if($this->pass_valid && !$user) {
$customer = new Customer();
$entityManager = $this->getDoctrine()->getManager('customer');
$entityManager->persist( $customer );
$entityManager->flush();
$number = str_pad((int)$customer->getId(), 6, '0', STR_PAD_LEFT);
$customer->setCustomerNumber( $number );
$customer->setEmail( $credentials['email'] );
$customer->setFirstname( $customer_obp_infos->data->firsname );
$customer->setLastname( $customer_obp_infos->data->lastname );
$customer->setPhoneMobile( $customer_obp_infos->data->phone );
$birthdate = new \DateTime( $customer_obp_infos->data->birthdate );
$customer->setBirthday( $birthdate );
if($customer_obp_infos->data->dialCountry) {
$customer->setCountry( $customer_obp_infos->data->dialCountry );
}
$customer->setStatut('Actif');
$customer->setActive(1);
$entityManager->persist( $customer );
$entityManager->flush();
return $customer;
}
// dd($userProvider,$user);
if (!$user) {
// fail authentication with a custom error
throw new CustomUserMessageAuthenticationException('Utilisateur introuvable');
}
return $user;
}
public function checkCredentials($credentials, UserInterface $user): bool
{
return $this->pass_valid;
}
/**
* Used to upgrade (rehash) the user's password automatically over time.
*/
public function getPassword($credentials): ?string
{
return $credentials['password'];
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey): ?Response
{
// dd($request->getSession());
if ($request->request->get('_target_path')){
$this->saveTargetPath($request->getSession(), $providerKey, $request->request->get('_target_path'));
}
if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) {
return new RedirectResponse($targetPath);
}
// For example : return new RedirectResponse($this->urlGenerator->generate('some_route'));
return new RedirectResponse($this->urlGenerator->generate('home'));
}
protected function getLoginUrl(): string
{
return $this->urlGenerator->generate(self::LOGIN_ROUTE);
}
}