src/Security/GoogleAuthenticator.php line 21
<?php# src/Security/GoogleAuthenticator.phpnamespace App\Security;use App\Entity\User;use App\IlaveU\ShopBundle\Entity\Customer\Customer;use League\OAuth2\Client\Provider\GoogleUser;use Doctrine\ORM\EntityManagerInterface;use KnpU\OAuth2ClientBundle\Client\ClientRegistry;use KnpU\OAuth2ClientBundle\Security\Authenticator\OAuth2Authenticator;use Symfony\Component\HttpFoundation\RedirectResponse;use Symfony\Component\HttpFoundation\Request;use Symfony\Component\HttpFoundation\Response;use Symfony\Component\Routing\RouterInterface;use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;use Symfony\Component\Security\Core\Exception\AuthenticationException;use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;use Symfony\Component\Security\Http\Authenticator\Passport\Passport;use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;class GoogleAuthenticator extends OAuth2Authenticator{private ClientRegistry $clientRegistry;private EntityManagerInterface $entityManager;private RouterInterface $router;public function __construct(ClientRegistry $clientRegistry,EntityManagerInterface $entityManager,RouterInterface $router) {$this->clientRegistry = $clientRegistry;$this->entityManager = $entityManager;$this->router = $router;}public function supports(Request $request): ?bool{// continue ONLY if the current ROUTE matches the check ROUTEreturn $request->attributes->get('_route') === 'connect_google_check';}public function authenticate(Request $request): Passport{$client = $this->clientRegistry->getClient('google');$accessToken = $this->fetchAccessToken($client);return new SelfValidatingPassport(new UserBadge($accessToken->getToken(), function () use ($accessToken,$client) {/** @var GoogleUser $googleUser */$googleUser = $client->fetchUserFromToken($accessToken);$email = $googleUser->getEmail();// have they logged in with Google before? Easy!$existingUser = $this->entityManager->getRepository(User::class)->findOneBy(['googleId' => $googleUser->getId()]);//User doesnt exist, we create it !if (!$existingUser) {$existingUserPerMail = $this->entityManager->getRepository(User::class)->findOneBy(['username' => $email]);if ($existingUserPerMail) {$existingUser = $existingUserPerMail;} else {$existingUser = new User();$existingUser->setUsername($email);$existingUser->setPassword($googleUser->getId());$existingUser->setRoles(["ROLE_CUSTOMER"]);}$existingUser->setGoogleId($googleUser->getId());//Customer//$existingUser->setHostedDomain($googleUser->getHostedDomain());}$existingCustomer = $this->entityManager->getRepository(Customer::class)->findOneBy(['user' => $existingUser]);if (!$existingCustomer or !$existingCustomer->getUser()) {$existingCustomerPerEmail = $this->entityManager->getRepository(Customer::class)->findOneBy(['email' => $email]);if(!$existingCustomerPerEmail){$existingCustomer = new Customer();$existingCustomer->setEmail($googleUser->getEmail());$existingCustomer->setPhone('060000000000');$existingCustomer->setAddress('');}else{$existingCustomer = $existingCustomerPerEmail;}}$existingCustomer->setFirstName($googleUser->getFirstName() ?? "--");$existingCustomer->setLastName($googleUser->getLastName() ?? "--");$existingCustomer->setUser($existingUser);$existingUser->setAvatar($googleUser->getAvatar());$this->entityManager->persist($existingCustomer);$this->entityManager->persist($existingUser);$this->entityManager->flush();return $existingUser;}));}public function onAuthenticationSuccess(Request $request,TokenInterface $token,string $firewallName): ?Response {// change "app_dashboard" to some route in your appreturn new RedirectResponse($this->router->generate('connect_google_after_connexion')."?googleId=123");// or, on success, let the request continue to be handled by the controller//return null;}public function onAuthenticationFailure(Request $request,AuthenticationException $exception): ?Response {$message = strtr($exception->getMessageKey(),$exception->getMessageData());return new Response($message, Response::HTTP_FORBIDDEN);}// public function start(Request $request, AuthenticationException $authException = null): Response// {// /*// * If you would like this class to control what happens when an anonymous user accesses a// * protected page (e.g. redirect to /login), uncomment this method and make this class// * implement Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface.// *// * For more details, see https://symfony.com/doc/current/security/experimental_authenticators.html#configuring-the-authentication-entry-point// */// }}