You are here

restws_basic_auth.module in RESTful Web Services 7

Same filename and directory in other branches
  1. 7.2 restws_basic_auth/restws_basic_auth.module

Basic authentication login - module file.

File

restws_basic_auth/restws_basic_auth.module
View source
<?php

/**
 * @file
 * Basic authentication login - module file.
 */

/**
 * Implements hook_init().
 *
 * Performs a user login from the credentials in the HTTP Authorization header.
 */
function restws_basic_auth_init() {
  if (user_is_anonymous() && isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {

    // Login only user names that match a pattern.
    $user_regex = variable_get('restws_basic_auth_user_regex', '/^restws.*/');
    if (preg_match($user_regex, $_SERVER['PHP_AUTH_USER'])) {
      $form_state = array();
      $form_state['values']['name'] = $_SERVER['PHP_AUTH_USER'];
      $form_state['values']['pass'] = $_SERVER['PHP_AUTH_PW'];
      drupal_form_submit('user_login', $form_state);
      if (!user_is_anonymous()) {
        drupal_static_reset();

        // Always make sure to disable the page cache after we authenticated the
        // user so that a response never gets into the page cache.
        drupal_page_is_cacheable(FALSE);
      }
      else {

        // Clear the login form error and remove the login failure message.
        $form =& drupal_static('form_set_error', array());
        $form = array();
        drupal_get_messages();
      }
    }
  }
}

/**
 * Implements hook_restws_request_alter().
 */
function restws_basic_auth_restws_request_alter(array &$request) {

  // Disable page caching for security reasons so that an authenticated user
  // response never gets into the page cache for anonymous users.
  // This is necessary because the page cache system only looks at session
  // cookies, but not at HTTP Basic Auth headers.
  drupal_page_is_cacheable(FALSE);
}