src/Security/Authenticator/OAuth2Authenticator.php line 81

Open in your IDE?
  1. <?php
  2. /**
  3.  * Created by PhpStorm.
  4.  * User: matti
  5.  * Date: 26/08/2019
  6.  * Time: 09:19
  7.  */
  8. namespace App\Security\Authenticator;
  9. use App\Security\Provider\OAuth2Provider;
  10. use App\Service\OAuth2AuthenticatorService;
  11. use Doctrine\ORM\EntityManagerInterface;
  12. use Symfony\Bundle\FrameworkBundle\Routing\Router;
  13. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  14. use Symfony\Component\HttpFoundation\RedirectResponse;
  15. use Symfony\Component\HttpFoundation\Request;
  16. use Symfony\Component\HttpFoundation\Response;
  17. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  18. use Symfony\Component\Routing\RouterInterface;
  19. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  20. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  21. use Symfony\Component\Security\Core\Exception\CustomUserMessageAccountStatusException;
  22. use Symfony\Component\Security\Core\Security;
  23. use Symfony\Component\Security\Core\User\ChainUserProvider;
  24. use Symfony\Component\Security\Core\User\UserInterface;
  25. use Symfony\Component\Security\Core\User\UserProviderInterface;
  26. use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
  27. class OAuth2Authenticator extends AbstractGuardAuthenticator
  28. {
  29.     /**
  30.      * @var EntityManagerInterface
  31.      */
  32.     private $em;
  33.     /**
  34.      * @var RouterInterface
  35.      */
  36.     private $router;
  37.     /**
  38.      * @var OAuth2AuthenticatorService
  39.      */
  40.     private $oAuth2AuthenticatorService;
  41.     /** @var EventDispatcherInterface  */
  42.     private $dispatcher;
  43.     /**
  44.      * @param EntityManagerInterface $entityManagerInterface
  45.      * @param Router $router
  46.      * @param OAuth2AuthenticatorService $oAuth2AuthenticatorService
  47.      */
  48.     public function __construct(
  49.         EntityManagerInterface $entityManagerInterface,
  50.         RouterInterface $router,
  51.         OAuth2AuthenticatorService $oAuth2AuthenticatorService,
  52.         EventDispatcherInterface $eventDispatcherInterface
  53.     )
  54.     {
  55.         $this->em $entityManagerInterface;
  56.         $this->router $router;
  57.         $this->oAuth2AuthenticatorService $oAuth2AuthenticatorService;
  58.         $this->dispatcher $eventDispatcherInterface;
  59.     }
  60.     /**
  61.      * @param Request $request
  62.      * @return bool
  63.      */
  64.     public function supports(Request $request)
  65.     {
  66.         $support $request->query->get('code') !== null true false;
  67.         if($support){
  68.             $request->query->set('_remember_me'true);
  69.         }
  70.         $session $request->getSession();
  71.         if ($session->has('company_access_office_id')) {
  72.             return false;
  73.         }
  74.         return $support && $this->oAuth2AuthenticatorService->getRedirectUrl() === $request->attributes->get('_route');
  75.     }
  76.     /**
  77.      * Returns a response that directs the user to authenticate.
  78.      *
  79.      * This is called when an anonymous request accesses a resource that
  80.      * requires authentication. The job of this method is to return some
  81.      * response that "helps" the user start into the authentication process.
  82.      *
  83.      * Examples:
  84.      *  A) For a form login, you might redirect to the login page
  85.      *      return new RedirectResponse('/login');
  86.      *  B) For an API token authentication system, you return a 401 response
  87.      *      return new Response('Auth header required', 401);
  88.      *
  89.      * @param Request $request The request that resulted in an AuthenticationException
  90.      * @param AuthenticationException $authException The exception that started the authentication process
  91.      *
  92.      * @return Response
  93.      */
  94.     public function start(Request $requestAuthenticationException $authException null)
  95.     {
  96.         // TODO: Implement start() method.
  97.         return new RedirectResponse('login');
  98.     }
  99.     /**
  100.      * Get the authentication credentials from the request and return them
  101.      * as any type (e.g. an associate array).
  102.      *
  103.      * Whatever value you return here will be passed to getUser() and checkCredentials()
  104.      *
  105.      * For example, for a form login, you might:
  106.      *
  107.      *      return array(
  108.      *          'username' => $request->request->get('_username'),
  109.      *          'password' => $request->request->get('_password'),
  110.      *      );
  111.      *
  112.      * Or for an API token that's on a header, you might use:
  113.      *
  114.      *      return array('api_key' => $request->headers->get('X-API-TOKEN'));
  115.      *
  116.      * @param Request $request
  117.      *
  118.      * @return mixed Any non-null value
  119.      *
  120.      * @throws \UnexpectedValueException If null is returned
  121.      */
  122.     public function getCredentials(Request $request)
  123.     {
  124.         return [
  125.             'code' => $request->query->get('code')
  126.         ];
  127.     }
  128.     /**
  129.      * Return a UserInterface object based on the credentials.
  130.      *
  131.      * The *credentials* are the return value from getCredentials()
  132.      *
  133.      * You may throw an AuthenticationException if you wish. If you return
  134.      * null, then a UsernameNotFoundException is thrown for you.
  135.      *
  136.      * @param mixed $credentials
  137.      * @param UserProviderInterface $userProvider
  138.      *
  139.      * @throws AuthenticationException
  140.      *
  141.      * @return UserInterface|null
  142.      */
  143.     public function getUser($credentialsUserProviderInterface $userProvider)
  144.     {
  145.         try {
  146.             $code $credentials['code'];
  147.             $officeUser $this->oAuth2AuthenticatorService->getUser($code);
  148.             //$tennantId = $officeUser->tennant_id;
  149.             //$objectId = $officeUser->oid;
  150.             $uniqueName $officeUser->username;
  151.             $user null;
  152.             if ($userProvider instanceof OAuth2Provider) {
  153.                 $user $userProvider->loadUserByUsername($uniqueName);
  154.             } else {
  155.                 $user $userProvider->loadUserByIdentifier($uniqueName);
  156.             }
  157.             if (!$user) {
  158.                 throw new AuthenticationException("User not found. Check that your credentials and the authentication method used are correct.");
  159.             }
  160.             if (!$user->getAbilitato()) {
  161.                 throw new CustomUserMessageAccountStatusException("Utente non abilitato al login");
  162.             }
  163.         }
  164.         catch (\Exception $e) {
  165.             throw $e;
  166.         }
  167.         return $user;
  168.     }
  169.     /**
  170.      * Returns true if the credentials are valid.
  171.      *
  172.      * If any value other than true is returned, authentication will
  173.      * fail. You may also throw an AuthenticationException if you wish
  174.      * to cause authentication to fail.
  175.      *
  176.      * The *credentials* are the return value from getCredentials()
  177.      *
  178.      * @param mixed $credentials
  179.      * @param UserInterface $user
  180.      *
  181.      * @return bool
  182.      *
  183.      * @throws AuthenticationException
  184.      */
  185.     public function checkCredentials($credentialsUserInterface $user)
  186.     {
  187.         // TODO: Implement checkCredentials() method.
  188.         return true;
  189.     }
  190.     /**
  191.      * Called when authentication executed, but failed (e.g. wrong username password).
  192.      *
  193.      * This should return the Response sent back to the user, like a
  194.      * RedirectResponse to the login page or a 403 response.
  195.      *
  196.      * If you return null, the request will continue, but the user will
  197.      * not be authenticated. This is probably not what you want to do.
  198.      *
  199.      * @param Request $request
  200.      * @param AuthenticationException $exception
  201.      *
  202.      * @return Response|null
  203.      */
  204.     public function onAuthenticationFailure(Request $requestAuthenticationException $exception)
  205.     {
  206.         if ($request->getSession() instanceof SessionInterface) {
  207.             $request->getSession()->set(Security::AUTHENTICATION_ERROR$exception);
  208.         }
  209.         $route $this->router->generate('login');
  210.         return new RedirectResponse($route);
  211.     }
  212.     /**
  213.      * Called when authentication executed and was successful!
  214.      *
  215.      * This should return the Response sent back to the user, like a
  216.      * RedirectResponse to the last page they visited.
  217.      *
  218.      * If you return null, the current request will continue, and the user
  219.      * will be authenticated. This makes sense, for example, with an API.
  220.      *
  221.      * @param Request $request
  222.      * @param TokenInterface $token
  223.      * @param string $providerKey The provider (i.e. firewall) key
  224.      *
  225.      * @return Response|null
  226.      */
  227.     public function onAuthenticationSuccess(Request $requestTokenInterface $token$providerKey)
  228.     {
  229.         $route $this->router->generate('homepage');
  230.         return new RedirectResponse($route);
  231.     }
  232.     /**
  233.      * Does this method support remember me cookies?
  234.      *
  235.      * Remember me cookie will be set if *all* of the following are met:
  236.      *  A) This method returns true
  237.      *  B) The remember_me key under your firewall is configured
  238.      *  C) The "remember me" functionality is activated. This is usually
  239.      *      done by having a _remember_me checkbox in your form, but
  240.      *      can be configured by the "always_remember_me" and "remember_me_parameter"
  241.      *      parameters under the "remember_me" firewall key
  242.      *  D) The onAuthenticationSuccess method returns a Response object
  243.      *
  244.      * @return bool
  245.      */
  246.     public function supportsRememberMe()
  247.     {
  248.         return false;
  249.     }
  250. }