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