<?php
/**
* Copyright (c) 2011-present Qualiteam software Ltd. All rights reserved.
* See https://www.x-cart.com/license-agreement.html for license details.
*/
namespace XCart\Security\Http\Authenticator;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\UserNotFoundException;
use Symfony\Component\Security\Core\User\UserInterface;
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 XCart\Security\DTO\WebUser;
use XLite\Core\Auth;
use XLite\Core\Database;
use XLite\Model\Profile;
final class WebAuthenticator extends AbstractAuthenticator
{
private \XLite\Model\Repo\Profile $profileRepository;
public function __construct()
{
$this->profileRepository = Database::getRepo(Profile::class);
}
public function supports(Request $request): bool
{
return $request->query->get('target') !== 'login';
}
public function authenticate(Request $request): Passport
{
$user = Auth::getInstance()->getProfile() ?? new Profile();
return new SelfValidatingPassport(
new UserBadge(
$user->getLogin(),
function (string $userIdentifier): UserInterface {
$profile = $this->profileRepository->findByLogin($userIdentifier);
if ($profile === null) {
$e = new UserNotFoundException(sprintf('User with "%s" not found.', $userIdentifier));
$e->setUserIdentifier($userIdentifier);
throw $e;
}
return new WebUser($profile);
}
)
);
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
return null;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
{
return $request->getRequestUri() === '/admin/' && $request->getMethod() !== Request::METHOD_POST
? new RedirectResponse(
\XLite::getInstance()->getShopURL('admin/?target=login')
)
: null;
}
}