src/Infrastructure/Auth/Symfony/Security/Authenticator/SiteAuthenticator.php line 20

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Infrastructure\Auth\Symfony\Security\Authenticator;
  4. use Symfony\Component\HttpFoundation\JsonResponse;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  8. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  9. use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;
  10. use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
  11. use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials;
  12. use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
  13. use Symfony\Component\VarDumper\VarDumper;
  14. use Psr\Log\LoggerAwareInterface;
  15. use Psr\Log\LoggerAwareTrait;
  16. class SiteAuthenticator extends AbstractAuthenticator implements LoggerAwareInterface
  17. {
  18.     use LoggerAwareTrait;
  19.     public function supports(Request $request): ?bool
  20.     {
  21.         return $request->headers->has('Authorization');
  22.     }
  23.     public function authenticate(Request $request): Passport
  24.     {
  25.         $header $request->headers->get('Authorization');
  26.         $username null;
  27.         $password null;
  28.         if (str_starts_with(strtolower($header), 'basic')) {
  29.             $basic explode(':'base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
  30.             $username $basic[0] ?? null;
  31.             $password $basic[1] ?? null;
  32.             if (null === $password) {
  33.                 $username null;
  34.             }
  35.         }
  36.         return new Passport(new UserBadge($username), new PasswordCredentials($password));
  37.     }
  38.     public function onAuthenticationSuccess(Request $requestTokenInterface $tokenstring $firewallName): ?Response
  39.     {
  40.         return null;
  41.     }
  42.     public function onAuthenticationFailure(Request $requestAuthenticationException $exception): ?Response
  43.     {
  44.         $this->logger->error('Merchant authentication failed: ' $exception->getMessage());
  45.         return new JsonResponse([
  46.             'error' => 'Authorization required',
  47.             'error_code' => 401,
  48.         ], Response::HTTP_UNAUTHORIZED);
  49.     }
  50. }