You are here

http_auth.module in HTTP Auth 8

Same filename and directory in other branches
  1. 7 http_auth.module

Enables Drupal to add HTTP Auth from frontend on all over the site/pages.

File

http_auth.module
View source
<?php

/**
 * @file
 * Enables Drupal to add HTTP Auth from frontend on all over the site/pages.
 */

/**
 * Implements hook_page_top().
 */
function http_auth_page_top(array &$page_top) {
  $user_roles = \Drupal::currentUser()
    ->getRoles();
  if (is_array($user_roles) && in_array("administrator", $user_roles)) {
    return;
  }
  $realm = 'Restricted Page';
  $http_auth = \Drupal::config('http_auth.settings')
    ->get();
  if (isset($http_auth) && !empty($http_auth) && isset($http_auth['activate']) && $http_auth['activate'] == 1) {
    if ($http_auth['applicable'] == 'admin') {
      if (strpos($_SERVER['REQUEST_URI'], '/admin') === FALSE && strpos($_SERVER['REQUEST_URI'], '/user') === FALSE && strpos($_SERVER['REQUEST_URI'], '/user/login') === FALSE) {
        return;
      }
    }
    $username = isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : '';
    $password = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : '';
    if (!($http_auth['username'] == $username && $http_auth['password'] == $password)) {
      $message = $http_auth['message'];
      header('WWW-Authenticate: Basic realm="' . $realm . '"');
      header('HTTP/1.0 401 Unauthorized');
      if (empty($message)) {
        $message = "This page is Restricted. Please contact the administrator for access.";
      }
      die(http_auth_cancel_page($message));
    }
  }
}

/**
 * Returns the page to the unauthenticated user.
 */
function http_auth_cancel_page($message = '') {
  $sitename = \Drupal::config('system.site')
    ->get('name');
  if ($sitename == '') {
    $sitename = "Locked";
  }
  return '<html>
            <head>
              <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
              <title>' . $sitename . ' | Restricted Site</title>
            </head>
            <body class="http-restricted">
              <p>' . $message . '</p>
            </body>
          </html>';
}

Functions

Namesort descending Description
http_auth_cancel_page Returns the page to the unauthenticated user.
http_auth_page_top Implements hook_page_top().