44
55namespace App \Security ;
66
7+ use App \Repository \ServerRepository ;
8+ use App \Repository \UserRepository ;
79use Symfony \Component \HttpFoundation \JsonResponse ;
810use Symfony \Component \HttpFoundation \Request ;
911use Symfony \Component \HttpFoundation \Response ;
1012use Symfony \Component \Security \Core \Authentication \Token \TokenInterface ;
1113use Symfony \Component \Security \Core \Exception \AuthenticationException ;
14+ use Symfony \Component \Security \Core \Exception \BadCredentialsException ;
1215use Symfony \Component \Security \Core \Exception \CustomUserMessageAuthenticationException ;
1316use Symfony \Component \Security \Http \Authenticator \AbstractAuthenticator ;
1417use Symfony \Component \Security \Http \Authenticator \Passport \Badge \UserBadge ;
@@ -20,6 +23,12 @@ class ApiKeyAuthenticator extends AbstractAuthenticator
2023 public const string AUTH_HEADER = 'Authorization ' ;
2124 public const string AUTH_HEADER_PREFIX = 'Apikey ' ;
2225
26+ public function __construct (
27+ private readonly ServerRepository $ serverRepository ,
28+ private readonly UserRepository $ userRepository ,
29+ ) {
30+ }
31+
2332 /**
2433 * Called on every request to decide if this authenticator should be used for the request.
2534 *
@@ -40,7 +49,14 @@ public function authenticate(Request $request): Passport
4049 throw new CustomUserMessageAuthenticationException ('No API token provided ' );
4150 }
4251
43- return new SelfValidatingPassport (new UserBadge ($ apiKey ));
52+ // Users and servers can authenticate to use the API.
53+ $ apiUser = $ this ->serverRepository ->findOneBy (['apiKey ' => $ apiKey ])
54+ ?? $ this ->userRepository ->findOneBy (['apiKey ' => $ apiKey ]);
55+ if (null !== $ apiUser ) {
56+ return new SelfValidatingPassport (new UserBadge ($ apiUser ->getUserIdentifier ()));
57+ }
58+
59+ throw new BadCredentialsException ('Invalid credentials. ' );
4460 }
4561
4662 public function onAuthenticationSuccess (Request $ request , TokenInterface $ token , string $ firewallName ): ?Response
0 commit comments