You are here

gauth_login.module in Google Auth 7.2

Same filename and directory in other branches
  1. 7 gauth_login/gauth_login.module

Google Auth Api for drupal.

File

gauth_login/gauth_login.module
View source
<?php

/**
 * @file
 * Google Auth Api for drupal.
 */

/**
 * Implements hook_help().
 */
function gauth_login_help($path, $arg) {
  switch ($path) {
    case 'admin/help#gauth_login':
      $path = $GLOBALS['base_url'] . '/' . drupal_get_path('module', 'gauth');
      $output = '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t("This module allows users to login using their google accounts.  If a user account in drupal doesn't exist then a account is created and user gets logged in by that account or if the configuration is set to not to create a new account then the configured message is displayed to the user.  If account exists then the user gets logged in by that account.") . '</p>';
      $output .= '<p>' . t("This module also offers a setting to restrict domains for google apps hosted accounts.  This feature don't allow users to login from a normal gmail account and restricts it to login only using the email address of the configured domain.  Admins should enable this feature understanding there own needs, as the module can't show any error or message to users from other domains.") . '</p>';
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<p>' . t("This module provides the option to allow end users to login using their google accounts") . '</p>';
      return $output;
  }
}

/**
 * Implements hook_menu().
 */
function gauth_login_menu() {
  $items = array();
  $items['admin/config/services/gauth_login'] = array(
    'title' => 'Google Login Settings',
    'description' => 'Google Login settings.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'gauth_login_settings',
    ),
    'access arguments' => array(
      'administer site configuration',
    ),
    'file' => 'gauth_login.admin.inc',
  );
  return $items;
}

/**
 * Implementation of hook_gauth_google_response().
 */
function gauth_login_gauth_google_response() {
  if (isset($_GET['state'])) {
    $state = json_decode($_GET['state'], TRUE);
    if (isset($state['src']) && $state['src'] != 'gauth_login') {

      // Handle response only if the request was from gauth_login.
      return;
    }
    if ($state['hash'] != $_SESSION['gauth_login_state']['hash']) {
      drupal_set_message(t('Invalid state parameter'), 'error');
      drupal_access_denied();
      return;
    }
    $redirect_url = isset($state['destination']) ? $state['destination'] : '';
    if (isset($_GET['code'])) {
      $client_id = variable_get('gauth_login_client_id');
      $client_secret = variable_get('gauth_login_client_secret');
      $api_key = variable_get('gauth_login_developer_key');
      $client = new Google_Client();
      $client
        ->setApplicationName("Google OAuth2");
      $client
        ->setClientId($client_id);
      $client
        ->setClientSecret($client_secret);
      $client
        ->setRedirectUri(gauth_callback_url());
      $client
        ->setDeveloperKey($api_key);
      $client
        ->setApprovalPrompt('force');
      $scopes = gauth_google_services_scopes('oauth2');
      $client
        ->addScope($scopes);
      $client
        ->fetchAccessTokenWithAuthCode($_GET['code']);
      $account['access_token'] = json_encode($client
        ->getAccessToken());
      $client = new Google_Client();
      $client
        ->setApplicationName("Google OAuth2");
      $client
        ->setClientId($client_id);
      $client
        ->setClientSecret($client_secret);
      $client
        ->setRedirectUri(gauth_callback_url());
      $client
        ->setDeveloperKey($api_key);
      $client
        ->setApprovalPrompt('force');
      $client
        ->setAccessToken($account['access_token']);
      $scopes = gauth_google_services_scopes('oauth2');
      $client
        ->addScope($scopes);
      $oauth = new Google_Service_Oauth2($client);
      $info = $oauth->userinfo
        ->get();
      if ($uid = gauth_login_load_google_id($info['id'])) {
        $form_state['uid'] = $uid;
        user_login_submit(array(), $form_state);
      }
      else {
        $account['client_id'] = variable_get('gauth_login_client_id');
        $account['client_secret'] = variable_get('gauth_login_client_secret');
        $account['developer_key'] = variable_get('gauth_login_developer_key');
        $account['services'] = 'oauth2';
        $account['is_authenticated'] = TRUE;
        if (!($new_user = gauth_login_find_existing_user($info))) {
          if (variable_get('gauth_login_create_user', TRUE)) {
            $user = new stdClass();
            $user->mail = $info['email'];
            $user->name = user_load_by_name($info['name']) ? $info['name'] . time() : $info['name'];
            $user->is_new = TRUE;
            $user->status = 1;
            $new_user = user_save($user);
          }
          else {
            drupal_set_message(t(variable_get('gauth_login_create_user_not_allowed_message', 'Can not find a user with this email. Did you use other google account while registering?')));
            drupal_goto('user/login');
          }
        }
        $form_state['uid'] = $new_user->uid;
        user_login_submit(array(), $form_state);
        global $user;
        $token = drupal_hash_base64(drupal_random_bytes(55));
        $_SESSION['pass_reset_' . $user->uid] = $token;
        if (variable_get('gauth_login_prom_message', TRUE)) {
          drupal_set_message(t("Click <a href='!url' target=_blank>here</a> to set password", array(
            '!url' => url('user/' . $user->uid . '/edit', array(
              'query' => array(
                'pass-reset-token' => $token,
              ),
            )),
          )), 'warning');
        }
        $gauth_login = array(
          'google_id' => $info['id'],
          'uid' => $user->uid,
        );
        drupal_write_record('gauth_login', $gauth_login);
        $account['name'] = 'Gauth Login ' . $user->uid;
        $account['uid'] = $user->uid;
        drupal_write_record('gauth_accounts', $account);
      }
    }
    drupal_goto($redirect_url);
  }
}

/**
 * Finds an existing user based on info from Google.
 *
 * @param array $info
 *   The 'userinfo' array from OAuth.
 *
 * @return object|NULL
 *   An existing Drupal user object if found; otherwise NULL.
 */
function gauth_login_find_existing_user($info) {

  // First, see if there is a user with the given e-mail.
  if ($new_user = user_load_by_mail($info['email'])) {
    return $new_user;
  }

  // Next, see if any modules have another way of tracking down existing users.
  foreach (module_implements('gauth_login_find_existing_user') as $module) {
    if ($new_user = module_invoke($module, 'gauth_login_find_existing_user', $info)) {
      return $new_user;
    }
  }
}

/**
 * Implements hook_form_alter().
 */
function gauth_login_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_login' || $form_id == 'user_login_block') {
    $form['submit_google'] = array(
      '#type' => 'submit',
      '#value' => t(''),
      '#submit' => array(
        'gauth_login_user_login_submit',
      ),
      '#limit_validation_errors' => array(),
      '#weight' => 1000,
    );
    drupal_add_css(drupal_get_path('module', 'gauth_login') . '/gauth_login.css');
  }
}

/**
 * Login using google, submit handler
 */
function gauth_login_user_login_submit() {
  if (variable_get('gauth_login_client_id', FALSE)) {
    $info = libraries_load('google-api-php-client');
    if (!$info['loaded']) {
      drupal_set_message(t("Can't authenticate with google as library is missing check Status report or Readme for requirements"), 'error');
      return FALSE;
    }
    $client = new Google_Client();
    $client
      ->setApplicationName("Google OAuth2");
    $client
      ->setClientId(variable_get('gauth_login_client_id'));
    $client
      ->setClientSecret(variable_get('gauth_login_client_secret'));
    $client
      ->setRedirectUri(gauth_callback_url());
    $client
      ->setDeveloperKey(variable_get('gauth_login_developer_key'));
    $scopes = gauth_google_services_scopes('oauth2');
    $client
      ->addScope($scopes);
    if (!isset($_SESSION['gauth_login_state'])) {
      $state = array(
        'src' => 'gauth_login',
        'hash' => md5(rand()),
      );
      if (isset($_GET['destination'])) {
        $state['destination'] = $_GET['destination'];
        unset($_GET['destination']);
      }
    }
    else {
      $state = $_SESSION['gauth_login_state'];
    }
    $_SESSION['gauth_login_state'] = $state;
    $state = drupal_json_encode($state);
    $client
      ->setState($state);
    $url = $client
      ->createAuthUrl();
    if ($restrict_domain = variable_get('gauth_login_domain_restriction', FALSE)) {
      $url .= '&hd=' . $restrict_domain;
    }
    drupal_goto($url);
  }
  else {
    drupal_set_message(t('Gauth Login is not configured. Please contact site administrator'), 'error');
  }
}

/**
 * Function returns uid of passed google id
 */
function gauth_login_load_google_id($id) {
  $rs = db_select('gauth_login', 'gl')
    ->fields('gl', array(
    'uid',
  ))
    ->condition('google_id', $id, '=')
    ->execute()
    ->fetchAssoc();
  return empty($rs) ? FALSE : $rs['uid'];
}

/**
 * Implmenentation of hook_user_delete();
 */
function gauth_login_user_delete($user) {
  db_delete('gauth_login')
    ->condition('uid', $user->uid)
    ->execute();
}

Functions

Namesort descending Description
gauth_login_find_existing_user Finds an existing user based on info from Google.
gauth_login_form_alter Implements hook_form_alter().
gauth_login_gauth_google_response Implementation of hook_gauth_google_response().
gauth_login_help Implements hook_help().
gauth_login_load_google_id Function returns uid of passed google id
gauth_login_menu Implements hook_menu().
gauth_login_user_delete Implmenentation of hook_user_delete();
gauth_login_user_login_submit Login using google, submit handler