You are here

function restws_basic_auth_init in RESTful Web Services 7.2

Same name and namespace in other branches
  1. 7 restws_basic_auth/restws_basic_auth.module \restws_basic_auth_init()

Implements hook_init().

Performs a user login from the credentials in the HTTP Authorization header.

File

restws_basic_auth/restws_basic_auth.module, line 13
Basic authentication login - module file.

Code

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);

        // Redetermine the page callback for restws calls like node/1.json
        // and user/1.json.
        _restws_determine_router_item();
      }
      else {

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