src/Security/MyFacebookAuthenticator.php line 155

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\FacebookClient;
  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\Security\Http\Authentication\AuthenticationUtils;
  18. use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
  19. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  20. class MyFacebookAuthenticator extends SocialAuthenticator
  21. {
  22.     private $clientRegistry;
  23.     private $em;
  24.     private $router;
  25.     private $userService;
  26.     private $kernelService;
  27.     private $session;
  28.     public function __construct(ClientRegistry $clientRegistry, EntityManagerInterface $em, RouterInterface $router, UserService $userService, KernelService $kernelService, SessionInterface $session)
  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.         
  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_facebook_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->getFacebookClient());
  51.     }
  52.     public function getUser($credentials, UserProviderInterface $userProvider)
  53.     {
  54.         
  55.         /** @var FacebookUser $facebookUser */
  56.         $facebookUser = $this->getFacebookClient()
  57.             ->fetchUserFromToken($credentials);
  58.         
  59.         
  60.          
  61.         $email = $facebookUser->getEmail();
  62.         // 1) have they logged in with Facebook before? Easy!
  63.         $existingUser = $this->em->getRepository(User::class)
  64.             ->findOneBy(['uuid' => $facebookUser->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.         /*$user = new User();
  76.         $user->setUuid($facebookUser->getId());
  77.         $user->setEmail($facebookUser->getEmail());
  78.         $user->setFirstName($facebookUser->getFirstName());
  79.         //$user->setLastName($facebookUser->getPictureUrl());
  80.         $user->setLastName($facebookUser->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($facebookUser->getId(), $facebookUser->getEmail(), $facebookUser->getFirstName(), $facebookUser->getLastName(), "?E(H+MbQeThWmZq4t7w!zPP&F)J@NcRf",
  87.                 "", "en-US", $defaulttimezone, null, $defaultorg,2);
  88.         return $user;
  89.     }
  90.     /**
  91.      * @return FacebookClient
  92.      */
  93.     private function getFacebookClient()
  94.     {
  95.         return $this->clientRegistry
  96.             // "facebook_main" is the key used in config/packages/knpu_oauth2_client.yaml
  97.             ->getClient('facebook_main');
  98.     }
  99.     public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
  100.     {
  101.         
  102.         $user = $token->getUser();
  103.         if ($this->userService->CanLogin($user) == true)
  104.         {
  105.             $this->userService->Login($user);
  106.             $targetUrl = $this->router->generate('app_home', ['_locale' => "".$user->getLocale()]);
  107.         }
  108.         else
  109.         {
  110.             $token->setAuthenticated(false);
  111.             $this->session->set('error', "User.NotAllowedToLogin");
  112.             $targetUrl = $this->router->generate('app_logout');
  113.         }
  114.         
  115.         // change "app_homepage" to some route in your app
  116.         
  117.         return new RedirectResponse($targetUrl);
  118.     
  119.         // or, on success, let the request continue to be handled by the controller
  120.         //return null;
  121.     }
  122.     public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
  123.     {
  124.         
  125.         $message = strtr($exception->getMessageKey(), $exception->getMessageData());
  126.         return new Response($message, Response::HTTP_FORBIDDEN);
  127.         
  128.         //$targetUrl = $this->router->generate('app_login');
  129.         //return new RedirectResponse($targetUrl);
  130.     }
  131.     /**
  132.      * Called when authentication is needed, but it's not sent.
  133.      * This redirects to the 'login'.
  134.      */
  135.     public function start(Request $request, AuthenticationException $authException = null)
  136.     {
  137.         return new RedirectResponse(
  138.             '/connect/facebook/', // might be the site, where users choose their oauth provider
  139.             Response::HTTP_TEMPORARY_REDIRECT
  140.         );
  141.     }
  142.     // ...
  143. }