src/Security/MyAzureAuthenticator.php line 23

Open in your IDE?
  1. <?php
  2. namespace App\Security;
  3. use App\Entity\Kernel\User// your user entity
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use KnpU\OAuth2ClientBundle\Security\Authenticator\SocialAuthenticator;
  6. use KnpU\OAuth2ClientBundle\Client\Provider\AzureClient;
  7. use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
  8. use Symfony\Component\HttpFoundation\Request;
  9. use Symfony\Component\HttpFoundation\Response;
  10. use Symfony\Component\Routing\RouterInterface;
  11. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  12. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  13. use Symfony\Component\Security\Core\User\UserProviderInterface;
  14. use Symfony\Component\HttpFoundation\RedirectResponse;
  15. use App\Service\Kernel\UserService;
  16. use App\Service\Kernel\KernelService;
  17. //use Symfony\Component\HttpFoundation\Session\SessionInterface;
  18. use Symfony\Component\HttpFoundation\RequestStack;
  19. use Symfony\Contracts\Translation\TranslatorInterface;
  20. class MyAzureAuthenticator extends SocialAuthenticator
  21. {
  22.     private $clientRegistry;
  23.     private $em;
  24.     private $router;
  25.     private $userService;
  26.     private $kernelService;
  27.     //private $session;
  28.     private $translator;
  29.     private $requestStack;
  30.     public function __construct(ClientRegistry $clientRegistryEntityManagerInterface $emRouterInterface $routerUserService $userServiceKernelService $kernelServiceRequestStack $requestStackTranslatorInterface $translator)
  31.     {
  32.         $this->clientRegistry $clientRegistry;
  33.         $this->em $em;
  34.     $this->router $router;
  35.         $this->userService $userService;
  36.         $this->kernelService $kernelService;
  37.         //$this->session = $session;
  38.         $this->requestStack $requestStack;
  39.         $this->translator $translator;
  40.     }
  41.     public function supports(Request $request)
  42.     {
  43.         // continue ONLY if the current ROUTE matches the check ROUTE
  44.         return $request->attributes->get('_route') === 'connect_azure_check';
  45.     }
  46.     public function getCredentials(Request $request)
  47.     {
  48.         // this method is only called if supports() returns true
  49.         // For Symfony lower than 3.4 the supports method need to be called manually here:
  50.         // if (!$this->supports($request)) {
  51.         //     return null;
  52.         // }
  53.         return $this->fetchAccessToken($this->getAzureClient());
  54.     }
  55.     public function getUser($credentialsUserProviderInterface $userProvider)
  56.     {
  57.         /** @var FacebookUser $facebookUser */
  58.         $azureUser $this->getAzureClient()
  59.             ->fetchUserFromToken($credentials);
  60.         
  61.         //$email = $azureUser->getEmail();
  62.         // 1) have they logged in with Facebook before? Easy!
  63.         $existingUser $this->em->getRepository(User::class)
  64.             ->findOneBy(['uuid' => $azureUser->getId()]);
  65.         if ($existingUser) {
  66.             return $existingUser;
  67.         }
  68.         
  69.         
  70.         // 2) do we have a matching user by email?
  71.         //$user = $this->em->getRepository(User::class)
  72.         //    ->findOneBy(['email' => $email]);
  73.         // 3) Maybe you just want to "register" them by creating
  74.         // a User object
  75.                 
  76.         /*$user = new User();
  77.         $user->setUuid($azureUser->getId());
  78.         $user->setEmail($azureUser->toArray()['upn']);
  79.         $user->setFirstName($azureUser->getFirstName());
  80.         $user->setLastName($azureUser->getLastName());
  81.         $user->setPassword("?E(H+MbQeThWmZq4t7w!zPP&F)J@NcRf");
  82.         $this->em->persist($user);
  83.         $this->em->flush();*/
  84.         $defaultorg $this->kernelService->getApplicationInfoValue("Kernel.Defaultorganization");
  85.         $defaulttimezone $this->kernelService->getApplicationInfoValue("Kernel.Defaulttimezone");
  86.         $user $this->userService->CreateUser($azureUser->getId(), $azureUser->toArray()['upn'], $azureUser->getFirstName(), $azureUser->getLastName(), "?E(H+MbQeThWmZq4t7w!zPP&F)J@NcRf",
  87.                 """en-US"$defaulttimezonenull$defaultorg,1);
  88.         return $user;
  89.     }
  90.     /**
  91.      * @return AzureClient
  92.      */
  93.     private function getAzureClient()
  94.     {
  95.         return $this->clientRegistry
  96.             // "facebook_main" is the key used in config/packages/knpu_oauth2_client.yaml
  97.             ->getClient('azure');
  98.     }
  99.     public function onAuthenticationSuccess(Request $requestTokenInterface $token$providerKey)
  100.     {
  101.         $user $token->getUser();
  102.         if ($this->userService->CanLogin($user) == true)
  103.         {
  104.             $this->userService->Login($user);
  105.             $targetUrl $this->router->generate('app_home', ['_locale' => "".$user->getLocale()]);
  106.         }
  107.         else
  108.         {
  109.             $token->setAuthenticated(false);
  110.             //$this->session->set('error', $this->translator->trans("User.NotAllowedToLogin", [], 'messages', "en-US"));
  111.             $this->requestStack->getSession()->set('error'$this->translator->trans("User.NotAllowedToLogin", [], 'messages'"en-US"));
  112.             $targetUrl $this->router->generate('app_logout');
  113.         }
  114.         // change "app_homepage" to some route in your app
  115.         
  116.         return new RedirectResponse($targetUrl);
  117.     
  118.         // or, on success, let the request continue to be handled by the controller
  119.         //return null;
  120.     }
  121.     public function onAuthenticationFailure(Request $requestAuthenticationException $exception)
  122.     {
  123.         $message strtr($exception->getMessageKey(), $exception->getMessageData());
  124.         return new Response($messageResponse::HTTP_FORBIDDEN);
  125.     }
  126.     /**
  127.      * Called when authentication is needed, but it's not sent.
  128.      * This redirects to the 'login'.
  129.      */
  130.     public function start(Request $requestAuthenticationException $authException null)
  131.     {
  132.         return new RedirectResponse(
  133.             '/connect/azure/'// might be the site, where users choose their oauth provider
  134.             Response::HTTP_TEMPORARY_REDIRECT
  135.         );
  136.     }
  137.     // ...
  138. }