<?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() {
  // Try to fill PHP_AUTH_USER & PHP_AUTH_PW with REDIRECT_HTTP_AUTHORIZATION
  // for compatibility with Apache PHP CGI/FastCGI.
  // This requires the following line in your ".htaccess"-File:
  // RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
  if (!empty($_SERVER['REDIRECT_HTTP_AUTHORIZATION']) && !isset($_SERVER['PHP_AUTH_USER']) && !isset($_SERVER['PHP_AUTH_PW'])) {
    $authentication = base64_decode(substr($_SERVER['REDIRECT_HTTP_AUTHORIZATION'], 6));
    list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':', $authentication);
  }
  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);
}
