src/UserBundle/Controller/OAuth/GoogleController.php line 23

Open in your IDE?
  1. <?php
  2. namespace App\UserBundle\Controller\OAuth;
  3. use App\BaseBundle\Controller\AbstractController;
  4. use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
  5. use KnpU\OAuth2ClientBundle\Client\Provider\GoogleClient;
  6. use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
  7. use League\OAuth2\Client\Provider\GoogleUser;
  8. use Symfony\Component\HttpFoundation\Request;
  9. use Symfony\Component\HttpFoundation\Response;
  10. use Symfony\Component\Routing\Annotation\Route;
  11. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  12. use Symfony\Component\Security\Core\Security;
  13. class GoogleController extends AbstractOAuthController
  14. {
  15. /**
  16. * Link to this controller to start the "connect" process
  17. *
  18. * @Route("/connect/google", name="connect_google_start")
  19. */
  20. public function connect(ClientRegistry $clientRegistry):Response
  21. {
  22. // will redirect to Google!
  23. return $clientRegistry
  24. ->getClient('google') // key used in config/packages/knpu_oauth2_client.yaml
  25. ->redirect([// the scopes you want to access
  26. 'https://www.googleapis.com/auth/userinfo.email',
  27. 'https://www.googleapis.com/auth/userinfo.profile'
  28. ]);
  29. }
  30. /**
  31. * After going to Google, you're redirected back here
  32. * because this is the "redirect_route" you configured
  33. * in config/packages/knpu_oauth2_client.yaml
  34. *
  35. * @Route("/connect/google/check", name="connect_google_check")
  36. */
  37. public function connectCheckAction(Request $request, ClientRegistry $clientRegistry):Response
  38. {
  39. // ** if you want to *authenticate* the user, then
  40. // leave this method blank and create a Guard authenticator
  41. // (read below)
  42. /** @var GoogleClient $client */
  43. $client = $clientRegistry->getClient('google');
  44. try {
  45. // the exact class depends on which provider you're using
  46. /** @var GoogleUser $user */
  47. $user = $client->fetchUser();
  48. return $this->createUserOrLogin($request, $user);
  49. } catch (IdentityProviderException $e) {
  50. // something went wrong!
  51. // probably you should return the reason to the user
  52. $error = new AuthenticationException($e->getMessage());
  53. $request->getSession()->set(Security::AUTHENTICATION_ERROR, $error);
  54. return $this->redirectToRoute("app_user_login");
  55. }
  56. }
  57. }