You are here

GauthResponseHandler.php in Google Auth 8

File

src/Entity/Controller/GauthResponseHandler.php
View source
<?php

namespace Drupal\gauth\Entity\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Routing\TrustedRedirectResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Drupal\gauth\Entity\Gauth;

/**
 * Provides a response handler for gauth entity.
 *
 * @ingroup gauth
 */
class GauthResponseHandler extends ControllerBase {

  /**
   * Function handles google response.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   Request object passed to controller.
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   Returns a redirect response object.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  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;
  }

}

Classes

Namesort descending Description
GauthResponseHandler Provides a response handler for gauth entity.