You are here

function http_auth_page_top in HTTP Auth 8

Implements hook_page_top().

File

./http_auth.module, line 11
Enables Drupal to add HTTP Auth from frontend on all over the site/pages.

Code

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