Advertisement
iruindegi

OauthAuthenticator.php

Mar 16th, 2023
544
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 4.08 KB | None | 0 0
  1. <?php
  2.  
  3. namespace App\Security;
  4.  
  5. use App\Entity\Langilea;
  6. use App\Entity\User; // your user entity
  7. use Doctrine\ORM\EntityManagerInterface;
  8. use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
  9. use KnpU\OAuth2ClientBundle\Security\Authenticator\OAuth2Authenticator;
  10. use Symfony\Component\HttpFoundation\RedirectResponse;
  11. use Symfony\Component\HttpFoundation\Request;
  12. use Symfony\Component\HttpFoundation\Response;
  13. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  14. use Symfony\Component\Routing\RouterInterface;
  15. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  16. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  17. use Symfony\Component\Security\Core\Exception\UserNotFoundException;
  18. use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
  19. use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
  20. use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
  21. use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;
  22. use Symfony\Component\Security\Http\Util\TargetPathTrait;
  23.  
  24. class OauthAuthenticator  extends OAuth2Authenticator implements AuthenticationEntrypointInterface
  25. {
  26.     use TargetPathTrait;
  27.  
  28.     public const LOGIN_ROUTE = 'app_login';
  29.     private ClientRegistry $clientRegistry;
  30.     private EntityManagerInterface $entityManager;
  31.     private RouterInterface $router;
  32.  
  33.     public function __construct(
  34.         private readonly UrlGeneratorInterface $urlGenerator,
  35.         ClientRegistry                         $clientRegistry,
  36.         EntityManagerInterface                 $entityManager,
  37.         RouterInterface                        $router)
  38.     {
  39.         $this->clientRegistry = $clientRegistry;
  40.         $this->entityManager = $entityManager;
  41.         $this->router = $router;
  42.     }
  43.  
  44.     public function supports(Request $request): ?bool
  45.     {
  46.         // continue ONLY if the current ROUTE matches the check ROUTE
  47.         return $request->attributes->get('_route') === 'oauth_check';
  48.     }
  49.  
  50.     public function authenticate(Request $request): Passport
  51.     {
  52.         $client = $this->clientRegistry->getClient('generic');
  53.         $accessToken = $this->fetchAccessToken($client);
  54.  
  55.         return new SelfValidatingPassport(
  56.             new UserBadge($accessToken->getToken(), function() use ($accessToken, $client) {
  57.                 $user = $client->fetchUserFromToken($accessToken);
  58.  
  59.                 $na = $user->getId();
  60.  
  61.                 // 1) have they logged in with Facebook before? Easy!
  62.                 $existingUser = $this->entityManager->getRepository(Langilea::class)->findOneBy(['NA' => $na]);
  63.  
  64.                 if ($existingUser) {
  65.                     return $existingUser;
  66.                 }
  67.  
  68.                 throw new UserNotFoundException();
  69.             })
  70.         );
  71.     }
  72.  
  73.     public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
  74.     {
  75.         if ($targetPath = $this->getTargetPath($request->getSession(), $firewallName)) {
  76.             return new RedirectResponse($targetPath);
  77.         }
  78.  
  79.         if (in_array('ROLE_ADMIN',$token->getRoleNames())) {
  80.             return new RedirectResponse($this->urlGenerator->generate('app_admin'));
  81.         }
  82.         return new RedirectResponse($this->urlGenerator->generate('app_default'));
  83.     }
  84.  
  85.     protected function getLoginUrl(Request $request): string
  86.     {
  87.         return $this->urlGenerator->generate(self::LOGIN_ROUTE);
  88.     }
  89.  
  90.     public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
  91.     {
  92.         $message = strtr($exception->getMessageKey(), $exception->getMessageData());
  93.  
  94.         return new Response($message, Response::HTTP_FORBIDDEN);
  95.     }
  96.  
  97.     public function start(Request $request, AuthenticationException $authException = null): RedirectResponse
  98.     {
  99.         return new RedirectResponse(
  100.             '/connect/', // might be the site, where users choose their oauth provider
  101.             Response::HTTP_TEMPORARY_REDIRECT
  102.         );
  103.     }
  104. }
  105.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement