src/Security/MyAzureAuthenticator.php line 22

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