src/Security/FacebookAuthenticator.php line 22

Open in your IDE?
  1. <?php
  2. namespace App\Security;
  3. use App\Entity\User;
  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 League\OAuth2\Client\Provider\FacebookUser;
  9. use Symfony\Component\HttpFoundation\RedirectResponse;
  10. use Symfony\Component\HttpFoundation\Request;
  11. use Symfony\Component\HttpFoundation\Response;
  12. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  13. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  14. use Symfony\Component\Security\Core\User\UserProviderInterface;
  15. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  16. use Symfony\Component\Security\Core\Exception\UserNotFoundException;
  17. use Symfony\Component\Routing\RouterInterface;
  18. use  Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
  19. class FacebookAuthenticator extends SocialAuthenticator
  20. {
  21.     /** @var ClientRegistry */
  22.     private $clientRegistry;
  23.     /** @var EntityManagerInterface */
  24.     private $entityManager;
  25.     /** @var RouterInterface */
  26.     private $router;
  27.     /** @var User */
  28.     private $user null;
  29.     /** @var UserPasswordHasherInterface */
  30.     private $userPasswordHasher;
  31.     /** @var FlashBagInterface */
  32.     private $flashBag;
  33.     /**
  34.      * FacebookAuthenticator constructor.
  35.      * 
  36.      * @param ClientRegistry $clientRegistry
  37.      * @param RouterInterface $router
  38.      * @param EntityManagerInterface $entityManager
  39.      * @param UserPasswordHasherInterface $userPasswordHasher
  40.      * @param FlashBagInterface $flashBag
  41.      */
  42.     public function __construct(
  43.         ClientRegistry $clientRegistry,
  44.         EntityManagerInterface $entityManager,
  45.         RouterInterface $router,
  46.         UserPasswordHasherInterface $userPasswordHasher,
  47.         FlashBagInterface $flashBag
  48.     ) {
  49.         $this->clientRegistry $clientRegistry;
  50.         $this->router $router;
  51.         $this->entityManager $entityManager;
  52.         $this->userPasswordHasher $userPasswordHasher;
  53.         $this->flashBag $flashBag;
  54.     }
  55.     /**
  56.      * @param Request $request
  57.      * @return bool
  58.      */
  59.     public function supports(Request $request)
  60.     {
  61.         // continue ONLY if the current ROUTE matches the check ROUTE
  62.         return $request->attributes->get('_route') === 'connect_facebook_check';
  63.     }
  64.     /**
  65.      * @param Request $request
  66.      * @return \League\OAuth2\Client\Token\AccessToken|mixed
  67.      */
  68.     public function getCredentials(Request $request)
  69.     {
  70.         // this method is only called if supports() returns true
  71.         return $this->fetchAccessToken($this->getFacebookClient());
  72.     }
  73.     /**
  74.      * @param mixed $credentials
  75.      * @param UserProviderInterface $userProvider
  76.      * @return User|null|object|\Symfony\Component\Security\Core\User\UserInterface
  77.      */
  78.     public function getUser($credentialsUserProviderInterface $userProvider)
  79.     {
  80.         /** @var FacebookUser $facebookUser */
  81.         $facebookUser $this->getFacebookClient()->fetchUserFromToken($credentials);
  82.         $facebookId $facebookUser->getId();
  83.         $email $facebookUser->getEmail();
  84.         $user $this->entityManager->getRepository(User::class)->findOneBy(['facebookId' => $facebookId]);
  85.         if (null === $user) {
  86.             $user $this->entityManager->getRepository(User::class)->findOneBy(['email' => $email]);
  87.             if (null === $user) {
  88.                 throw new UserNotFoundException;
  89.                 // $firstname = $facebookUser->getFirstName();
  90.                 // $lastname = $facebookUser->getLastName();
  91.                 // $profileUrl = $facebookUser->getPictureUrl();
  92.                 // $gender = $facebookUser->getGender();
  93.                 // $genders = ['male' => 'm', 'female' => 'f'];
  94.                 // /** @var User $user */
  95.                 // $user = new User();
  96.                 // $user->setEmail($email);
  97.                 // $user->setRoles(['ROLE_USER']);
  98.                 // $user->setPassword($this->passwordEncoder->encodePassword($user, 'ayoub123'));
  99.                 // $user->setIsVerified(true);
  100.                 // $user->setFirstname($firstname);
  101.                 // $user->setLastname($lastname);
  102.                 // $user->setProfileUrl($profileUrl);
  103.                 // $user->setFacebookId($facebookId);
  104.                 // if (isset($genders[$gender])) {
  105.                 //     $user->setGender($genders[$gender]);
  106.                 // }
  107.                 // $this->entityManager->persist($user);
  108.             }
  109.             $user->setFacebookId($facebookId);
  110.             $this->entityManager->flush();
  111.         }
  112.         $this->user $user;
  113.         return $userProvider->loadUserByIdentifier($user->getUsername());
  114.     }
  115.     /**
  116.      * @return FacebookClient
  117.      */
  118.     private function getFacebookClient()
  119.     {
  120.         return $this->clientRegistry->getClient('facebook');
  121.     }
  122.     /**
  123.      * @param Request $request
  124.      * @param TokenInterface $token
  125.      * @param string $providerKey
  126.      * @return null|Response
  127.      */
  128.     public function onAuthenticationSuccess(Request $requestTokenInterface $token$providerKey)
  129.     {
  130.         // on success, let the request continue
  131.         $this->user->setLastLogin(new \DateTimeImmutable());
  132.         $this->entityManager->flush();
  133.         return null;
  134.     }
  135.     /**
  136.      * @param Request $request
  137.      * @param AuthenticationException $exception
  138.      * @return RedirectResponse
  139.      */
  140.     public function onAuthenticationFailure(Request $requestAuthenticationException $exception): RedirectResponse
  141.     {
  142.         // $message = strtr($exception->getMessageKey(), $exception->getMessageData());
  143.         $this->flashBag->add('danger''Votre compte Facebook n\'est pas autorisé');
  144.         return new RedirectResponse($this->router->generate('app_login'));
  145.     }
  146.     /**
  147.      * Called when authentication is needed, but it's not sent.
  148.      * This redirects to the 'login'.
  149.      *
  150.      * @param Request $request
  151.      * @param AuthenticationException|null $authException
  152.      *
  153.      * @return RedirectResponse
  154.      */
  155.     public function start(Request $requestAuthenticationException $authException null)
  156.     {
  157.         return new RedirectResponse(
  158.             '/connect/'// might be the site, where users choose their oauth provider
  159.             Response::HTTP_TEMPORARY_REDIRECT
  160.         );
  161.     }
  162. }