src/Security/GoogleAuthenticator.php line 21

  1. <?php
  2. # src/Security/GoogleAuthenticator.php
  3. namespace App\Security;
  4. use App\Entity\User;
  5. use App\IlaveU\ShopBundle\Entity\Customer\Customer;
  6. use League\OAuth2\Client\Provider\GoogleUser;
  7. use Doctrine\ORM\EntityManagerInterface;
  8. use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
  9. use KnpU\OAuth2ClientBundle\Security\Authenticator\OAuth2Authenticator;
  10. use Symfony\Component\HttpFoundation\RedirectResponse;
  11. use Symfony\Component\HttpFoundation\Request;
  12. use Symfony\Component\HttpFoundation\Response;
  13. use Symfony\Component\Routing\RouterInterface;
  14. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  15. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  16. use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
  17. use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
  18. use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
  19. class GoogleAuthenticator extends OAuth2Authenticator
  20. {
  21.     private ClientRegistry $clientRegistry;
  22.     private EntityManagerInterface $entityManager;
  23.     private RouterInterface $router;
  24.     public function __construct(
  25.         ClientRegistry $clientRegistry,
  26.         EntityManagerInterface $entityManager,
  27.         RouterInterface $router
  28.     ) {
  29.         $this->clientRegistry $clientRegistry;
  30.         $this->entityManager $entityManager;
  31.         $this->router $router;
  32.     }
  33.     public function supports(Request $request): ?bool
  34.     {
  35.         // continue ONLY if the current ROUTE matches the check ROUTE
  36.         return $request->attributes->get('_route') === 'connect_google_check';
  37.     }
  38.     public function authenticate(Request $request): Passport
  39.     {
  40.         $client $this->clientRegistry->getClient('google');
  41.         $accessToken $this->fetchAccessToken($client);
  42.         return new SelfValidatingPassport(
  43.             new UserBadge($accessToken->getToken(), function () use (
  44.                 $accessToken,
  45.                 $client
  46.             ) {
  47.                 /** @var GoogleUser $googleUser */
  48.                 $googleUser $client->fetchUserFromToken($accessToken);
  49.                 $email $googleUser->getEmail();
  50.                 // have they logged in with Google before? Easy!
  51.                 $existingUser $this->entityManager
  52.                     ->getRepository(User::class)
  53.                     ->findOneBy(['googleId' => $googleUser->getId()]);
  54.                 //User doesnt exist, we create it !
  55.                 if (!$existingUser) {
  56.                     $existingUserPerMail $this->entityManager
  57.                         ->getRepository(User::class)
  58.                         ->findOneBy(['username' => $email]);
  59.                     if ($existingUserPerMail) {
  60.                         $existingUser $existingUserPerMail;
  61.                     } else {
  62.                         $existingUser = new User();
  63.                         $existingUser->setUsername($email);
  64.                         $existingUser->setPassword($googleUser->getId());
  65.                         $existingUser->setRoles(["ROLE_CUSTOMER"]);
  66.                     }
  67.                     $existingUser->setGoogleId($googleUser->getId());
  68.                     //Customer
  69.                     //$existingUser->setHostedDomain($googleUser->getHostedDomain());
  70.                 }
  71.                 $existingCustomer $this->entityManager
  72.                     ->getRepository(Customer::class)
  73.                     ->findOneBy(['user' => $existingUser]);
  74.                 if (!$existingCustomer or !$existingCustomer->getUser()) {
  75.                     $existingCustomerPerEmail $this->entityManager
  76.                     ->getRepository(Customer::class)
  77.                     ->findOneBy(['email' => $email]);
  78.                     if(!$existingCustomerPerEmail){
  79.                         $existingCustomer = new Customer();
  80.                         $existingCustomer->setEmail($googleUser->getEmail());
  81.                         $existingCustomer->setPhone('060000000000');
  82.                         $existingCustomer->setAddress('');
  83.                     }else{
  84.                         $existingCustomer $existingCustomerPerEmail;
  85.                     }
  86.                     
  87.                 }
  88.                 $existingCustomer->setFirstName($googleUser->getFirstName() ?? "--");
  89.                 $existingCustomer->setLastName($googleUser->getLastName() ?? "--");
  90.                 $existingCustomer->setUser($existingUser);
  91.                 $existingUser->setAvatar($googleUser->getAvatar());
  92.                 $this->entityManager->persist($existingCustomer);
  93.                 $this->entityManager->persist($existingUser);
  94.                 $this->entityManager->flush();
  95.                 return $existingUser;
  96.             })
  97.         );
  98.     }
  99.     public function onAuthenticationSuccess(
  100.         Request $request,
  101.         TokenInterface $token,
  102.         string $firewallName
  103.     ): ?Response {
  104.         // change "app_dashboard" to some route in your app
  105.         return new RedirectResponse(
  106.             $this->router->generate('connect_google_after_connexion')."?googleId=123"
  107.         );
  108.         // or, on success, let the request continue to be handled by the controller
  109.         //return null;
  110.     }
  111.     public function onAuthenticationFailure(
  112.         Request $request,
  113.         AuthenticationException $exception
  114.     ): ?Response {
  115.         $message strtr(
  116.             $exception->getMessageKey(),
  117.             $exception->getMessageData()
  118.         );
  119.         return new Response($messageResponse::HTTP_FORBIDDEN);
  120.     }
  121.     //    public function start(Request $request, AuthenticationException $authException = null): Response
  122.     //    {
  123.     //        /*
  124.     //         * If you would like this class to control what happens when an anonymous user accesses a
  125.     //         * protected page (e.g. redirect to /login), uncomment this method and make this class
  126.     //         * implement Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface.
  127.     //         *
  128.     //         * For more details, see https://symfony.com/doc/current/security/experimental_authenticators.html#configuring-the-authentication-entry-point
  129.     //         */
  130.     //    }
  131. }