You are here

public static function GauthResponseHandler::responseHandler in Google Auth 8

Function handles google response.

Parameters

\Symfony\Component\HttpFoundation\Request $request: Request object passed to controller.

Return value

\Symfony\Component\HttpFoundation\RedirectResponse Returns a redirect response object.

Throws

\Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException

\Drupal\Component\Plugin\Exception\PluginNotFoundException

\Drupal\Core\Entity\EntityStorageException

1 string reference to 'GauthResponseHandler::responseHandler'
gauth.routing.yml in ./gauth.routing.yml
gauth.routing.yml

File

src/Entity/Controller/GauthResponseHandler.php, line 31

Class

GauthResponseHandler
Provides a response handler for gauth entity.

Namespace

Drupal\gauth\Entity\Controller

Code

public static function responseHandler(Request $request) {
  $account_id = $request
    ->get('id');
  gauth_load_library();
  if (!class_exists('Google_Client')) {
    \Drupal::messenger()
      ->addError(t("Can't authenticate with google as library is missing check Status report or Readme for requirements"));
    $response = new RedirectResponse('/admin/config/services/gauth');
    return $response;
  }
  if ($account_id == NULL && isset($_SESSION['gauth_account_id'])) {
    $account_id = $_SESSION['gauth_account_id'];
  }
  elseif ($account_id) {
    $_SESSION['gauth_account_id'] = $account_id;
  }
  if ($account_id) {
    $gauth = \Drupal::entityTypeManager()
      ->getStorage('gauth')
      ->load($account_id);
    $client = Gauth::getGauthClient($gauth);
    $client
      ->setApplicationName("Google OAuth2");
    if ($request
      ->get('code')) {
      $client
        ->fetchAccessTokenWithAuthCode($request
        ->get('code'));
      $gauth
        ->setAccessToken(json_encode($client
        ->getAccessToken()));
      $gauth
        ->setAuthenticated(TRUE);
      $gauth
        ->save();
      unset($_SESSION['gauth_account_id']);
      $response = new RedirectResponse('/admin/config/services/gauth');
      \Drupal::messenger()
        ->addMessage(t('Api Account saved'));
      return $response;
    }
    if ($client) {
      $auth_url = $client
        ->createAuthUrl();
      $response = new TrustedRedirectResponse($auth_url);
      $response
        ->send();
    }
  }

  // Let other modules act of google response.
  \Drupal::moduleHandler()
    ->invokeAll('gauth_google_response', [
    $request,
  ]);
  $response = new RedirectResponse('/admin/config/services/gauth');
  return $response;
}