src/Security/LoginFormAuthenticator.php line 100

Open in your IDE?
  1. <?php
  2. namespace App\Security;
  3. use App\Exception\reCaptcha3Exception;
  4. use App\Services\{EntityServices\UserEntityService,
  5.     ParameterService,
  6.     reCaptcha3ValidatorService,
  7.     Tenants\Tenant1\CookieService,
  8.     TenantService};
  9. use Symfony\Component\HttpFoundation\JsonResponse;
  10. use Symfony\Component\HttpFoundation\Request;
  11. use Symfony\Component\HttpFoundation\Response;
  12. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  13. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  14. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  15. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  16. use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
  17. use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
  18. use Symfony\Component\Security\Core\Security;
  19. use Symfony\Component\Security\Core\User\UserInterface;
  20. use Symfony\Component\Security\Core\User\UserProviderInterface;
  21. use Symfony\Component\Security\Csrf\CsrfToken;
  22. use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
  23. use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;
  24. use Symfony\Component\Security\Guard\PasswordAuthenticatedInterface;
  25. use Symfony\Component\Security\Http\Util\TargetPathTrait;
  26. class LoginFormAuthenticator extends AbstractFormLoginAuthenticator implements PasswordAuthenticatedInterface
  27. {
  28.     use TargetPathTrait;
  29.     public const LOGIN_ROUTE 'user_sign_in';
  30.     private $urlGenerator;
  31.     private $csrfTokenManager;
  32.     private $passwordEncoder;
  33.     private $userEntityService;
  34.     private $tenantService;
  35.     private $cookieService;
  36.     private $reCaptcha3ValidatorService;
  37.     public function __construct(
  38.         UrlGeneratorInterface $urlGenerator
  39.         CsrfTokenManagerInterface $csrfTokenManager
  40.         TenantService $tenantService,
  41.         UserEntityService $userEntityService,
  42.         UserPasswordEncoderInterface $passwordEncoder,
  43.         CookieService $cookieService,
  44.         ParameterService $parameterService,
  45.         reCaptcha3ValidatorService $reCaptcha3ValidatorService
  46.     )
  47.     {
  48.         $this->urlGenerator $urlGenerator;
  49.         $this->csrfTokenManager $csrfTokenManager;
  50.         $this->passwordEncoder $passwordEncoder;
  51.         $this->tenantService $tenantService;
  52.         $this->userEntityService $userEntityService;
  53.         $this->cookieService $cookieService;
  54.         $this->tenant $tenantService->defineTenant();
  55.         $this->reCaptcha3ValidatorService $reCaptcha3ValidatorService;
  56.         $this->reCaptcha3ValidatorService->setAccess(
  57.             $parameterService->getParameter($this->tenant->getSettingsArrayAssoc()['config'] ?? 'non-existent''reCaptcha3.secretKey'),
  58.             $parameterService->getParameter($this->tenant->getSettingsArrayAssoc()['config'] ?? 'non-existent''reCaptcha3.allowableScore')
  59.         );
  60.      }
  61.     public function supports(Request $request)
  62.     {
  63.         return self::LOGIN_ROUTE === $request->attributes->get('_route')
  64.             && $request->isMethod('POST');
  65.     }
  66.     public function getCredentials(Request $request)
  67.     {
  68.         $credentials = [
  69.             'email' => $request->request->get('email'),
  70.             'password' => $request->request->get('password'),
  71.             'tenant' => $this->tenantService->defineTenant(),
  72.             'csrf_token' => $request->request->get('_csrf_token'),
  73.             'gRecaptchaToken' => $request->request->get('reCAPTCHA_token'),
  74.         ];
  75.         $request->getSession()->set(
  76.             Security::LAST_USERNAME,
  77.             $credentials['email']
  78.         );
  79.         return $credentials;
  80.     }
  81.     public function getUser($credentialsUserProviderInterface $userProvider)
  82.     {
  83.         $this->reCaptcha3ValidatorService->setToken($credentials['gRecaptchaToken']);
  84.         if ($this->reCaptcha3ValidatorService->validate()) {
  85.             throw new reCaptcha3Exception('reCaptcha3 validation failed.');
  86.         }
  87.         // $token = new CsrfToken('SignInForm', $credentials['csrf_token']);
  88.         // if (!$this->csrfTokenManager->isTokenValid($token)) {
  89.         //     throw new InvalidCsrfTokenException('csrf not passed');
  90.         // }
  91.         $user $this->userEntityService->findUser($credentials['email'], $credentials['tenant']);
  92.         if (!$user) {
  93.             // fail authentication with a custom error
  94.             throw new CustomUserMessageAuthenticationException('sign_in.email_not_found');
  95.         }
  96.         return $user;
  97.     }
  98.     public function checkCredentials($credentialsUserInterface $user)
  99.     {
  100.         return $this->passwordEncoder->isPasswordValid($user$credentials['password']);
  101.     }
  102.     /**
  103.      * Used to upgrade (rehash) the user's password automatically over time.
  104.      */
  105.     public function getPassword($credentials): ?string
  106.     {
  107.         return $credentials['password'];
  108.     }
  109.     public function onAuthenticationSuccess(Request $requestTokenInterface $tokenstring $providerKey)
  110.     {
  111. //        if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) {
  112. //            return new RedirectResponse($targetPath);
  113. //        }
  114. //        $response = new RedirectResponse($this->urlGenerator->generate('user_profile'));
  115. //        $response = $this->cookieService->addCookieToResponse($response, $request);
  116. //        return $response;
  117.         if ($targetPath $this->getTargetPath($request->getSession(), $providerKey)) {
  118.             return new JsonResponse(['redirectUri' => $targetPath]);
  119.         }
  120.         if ($request->request->get('referral') !== "null") {
  121.             $response = new JsonResponse(['redirectUri' => $request->request->get('referral')]);
  122.         } else {
  123.             $response = new JsonResponse(['redirectUri' => $this->urlGenerator->generate('user_profile')]);
  124.         }
  125.         $response $this->cookieService->addCookieToResponse($response$request);
  126.         return $response;
  127.     }
  128.     public function onAuthenticationFailure(Request $requestAuthenticationException $exception)
  129.     {
  130. //        $request->getSession()->set( Security::AUTHENTICATION_ERROR, 'exception.sign_in.auth_failed');
  131. //        return new RedirectResponse($this->getLoginUrl());
  132.         return new JsonResponse($exception->getMessage(), Response::HTTP_UNAUTHORIZED);
  133.     }
  134.     protected function getLoginUrl()
  135.     {
  136.         return $this->urlGenerator->generate(self::LOGIN_ROUTE);
  137.     }
  138. }