<?php
namespace App\Security;
use App\Exception\reCaptcha3Exception;
use App\Services\{EntityServices\UserEntityService,
ParameterService,
reCaptcha3ValidatorService,
Tenants\Tenant1\CookieService,
TenantService};
use Symfony\Component\HttpFoundation\JsonResponse;
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\AuthenticationException;
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;
class LoginFormAuthenticator extends AbstractFormLoginAuthenticator implements PasswordAuthenticatedInterface
{
use TargetPathTrait;
public const LOGIN_ROUTE = 'user_sign_in';
private $urlGenerator;
private $csrfTokenManager;
private $passwordEncoder;
private $userEntityService;
private $tenantService;
private $cookieService;
private $reCaptcha3ValidatorService;
public function __construct(
UrlGeneratorInterface $urlGenerator,
CsrfTokenManagerInterface $csrfTokenManager,
TenantService $tenantService,
UserEntityService $userEntityService,
UserPasswordEncoderInterface $passwordEncoder,
CookieService $cookieService,
ParameterService $parameterService,
reCaptcha3ValidatorService $reCaptcha3ValidatorService
)
{
$this->urlGenerator = $urlGenerator;
$this->csrfTokenManager = $csrfTokenManager;
$this->passwordEncoder = $passwordEncoder;
$this->tenantService = $tenantService;
$this->userEntityService = $userEntityService;
$this->cookieService = $cookieService;
$this->tenant = $tenantService->defineTenant();
$this->reCaptcha3ValidatorService = $reCaptcha3ValidatorService;
$this->reCaptcha3ValidatorService->setAccess(
$parameterService->getParameter($this->tenant->getSettingsArrayAssoc()['config'] ?? 'non-existent', 'reCaptcha3.secretKey'),
$parameterService->getParameter($this->tenant->getSettingsArrayAssoc()['config'] ?? 'non-existent', 'reCaptcha3.allowableScore')
);
}
public function supports(Request $request)
{
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'),
'tenant' => $this->tenantService->defineTenant(),
'csrf_token' => $request->request->get('_csrf_token'),
'gRecaptchaToken' => $request->request->get('reCAPTCHA_token'),
];
$request->getSession()->set(
Security::LAST_USERNAME,
$credentials['email']
);
return $credentials;
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
$this->reCaptcha3ValidatorService->setToken($credentials['gRecaptchaToken']);
if ($this->reCaptcha3ValidatorService->validate()) {
throw new reCaptcha3Exception('reCaptcha3 validation failed.');
}
// $token = new CsrfToken('SignInForm', $credentials['csrf_token']);
// if (!$this->csrfTokenManager->isTokenValid($token)) {
// throw new InvalidCsrfTokenException('csrf not passed');
// }
$user = $this->userEntityService->findUser($credentials['email'], $credentials['tenant']);
if (!$user) {
// fail authentication with a custom error
throw new CustomUserMessageAuthenticationException('sign_in.email_not_found');
}
return $user;
}
public function checkCredentials($credentials, UserInterface $user)
{
return $this->passwordEncoder->isPasswordValid($user, $credentials['password']);
}
/**
* 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, string $providerKey)
{
// if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) {
// return new RedirectResponse($targetPath);
// }
// $response = new RedirectResponse($this->urlGenerator->generate('user_profile'));
// $response = $this->cookieService->addCookieToResponse($response, $request);
// return $response;
if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) {
return new JsonResponse(['redirectUri' => $targetPath]);
}
if ($request->request->get('referral') !== "null") {
$response = new JsonResponse(['redirectUri' => $request->request->get('referral')]);
} else {
$response = new JsonResponse(['redirectUri' => $this->urlGenerator->generate('user_profile')]);
}
$response = $this->cookieService->addCookieToResponse($response, $request);
return $response;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
// $request->getSession()->set( Security::AUTHENTICATION_ERROR, 'exception.sign_in.auth_failed');
// return new RedirectResponse($this->getLoginUrl());
return new JsonResponse($exception->getMessage(), Response::HTTP_UNAUTHORIZED);
}
protected function getLoginUrl()
{
return $this->urlGenerator->generate(self::LOGIN_ROUTE);
}
}