<?php
declare(strict_types=1);
namespace App\Infrastructure\Auth\Symfony\Security\Authenticator;
use Symfony\Component\HttpFoundation\JsonResponse;
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\Http\Authenticator\AbstractAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\VarDumper\VarDumper;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
class SiteAuthenticator extends AbstractAuthenticator implements LoggerAwareInterface
{
use LoggerAwareTrait;
public function supports(Request $request): ?bool
{
return $request->headers->has('Authorization');
}
public function authenticate(Request $request): Passport
{
$header = $request->headers->get('Authorization');
$username = null;
$password = null;
if (str_starts_with(strtolower($header), 'basic')) {
$basic = explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
$username = $basic[0] ?? null;
$password = $basic[1] ?? null;
if (null === $password) {
$username = null;
}
}
return new Passport(new UserBadge($username), new PasswordCredentials($password));
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
return null;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
{
$this->logger->error('Merchant authentication failed: ' . $exception->getMessage());
return new JsonResponse([
'error' => 'Authorization required',
'error_code' => 401,
], Response::HTTP_UNAUTHORIZED);
}
}