You are here

restrict_by_ip.module in Restrict Login or Role Access by IP Address 8.4

Restrict logins or roles to whitelisted IP addresses.

File

restrict_by_ip.module
View source
<?php

/**
 * @file
 * Restrict logins or roles to whitelisted IP addresses.
 */

/**
 * Implements hook_help().
 *
 * @TODO
 */
function restrict_by_ip_help($section) {
  $output = '';
  switch ($section) {
    case 'admin/help#restrict_by_ip':
      $output = '<p>The site administrator can limit a user to only be able to login from certain IP Addresses or ranges of IP Addresses using CIDR notation. Individual roles may also be limited to a those from specified IP addresses and rangers.</p>';
      break;
  }
  return $output;
}

/**
 * Implements hook_init().
 *
 * @TODO
 */
function restrict_by_ip_init() {
  global $user;

  // Login restriction check moved here to prevent access from stale session data
  _restrict_by_ip_login($user);
}

/**
 * Implements hook_boot().
 *
 * @TODO
 */
function restrict_by_ip_boot() {
  global $user;

  // Call the function early in boot process to check/strip roles
  restrict_by_ip_role_check($user);
}

/**
 * Implements hook_user_login().
 */
function restrict_by_ip_user_login($account) {
  $login_firewall = \Drupal::service('restrict_by_ip.login_firewall');
  $login_firewall
    ->execute($account);
}

/**
 * Implements hook_user_delete().
 */
function restrict_by_ip_user_delete($account) {
  if ($account
    ->isAuthenticated()) {
    $config = \Drupal::service('config.factory')
      ->getEditable('restrict_by_ip.settings');
    $config
      ->clear('user.' . $account
      ->id())
      ->save();
  }
}

/**
 * Implements hook_form_alter().
 */
function restrict_by_ip_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_form' || $form_id == 'user_register_form') {

    // Add restrict by ip form fields to user add/edit form.
    if (\Drupal::currentUser()
      ->hasPermission('administer restrict by ip')) {
      $address_entry = '';
      if ($form_id == 'user_form') {
        $user = $form_state
          ->getFormObject()
          ->getEntity();

        // Grab the current restrict by ip data if it exists.
        $config = \Drupal::config('restrict_by_ip.settings');
        $address_entry = $config
          ->get('user.' . $user
          ->id());
      }
      $form['#validate'][] = 'restrict_by_ip_user_profile_validate';
      $form['actions']['submit']['#submit'][] = 'restrict_by_ip_user_profile_submit';
      $form['rip'] = [
        '#type' => 'details',
        '#attributes' => [
          'class' => [
            'restrict-by-ip',
          ],
        ],
        '#title' => t('Restrict by IP settings'),
        '#weight' => 5,
        '#open' => TRUE,
      ];
      $form['rip']['restrict_by_ip_address'] = [
        '#type' => 'textfield',
        '#default_value' => $address_entry,
        '#maxlength' => NULL,
        '#description' => t('Enter IP Address Ranges in CIDR Notation separated with semi-colons, with no trailing semi-colon. E.G. 10.20.30.0/24;192.168.199.1/32;1.0.0.0/8<br />For more information on CIDR notation <a href="http://www.brassy.net/2007/mar/cidr_basic_subnetting" target="_blank">click here</a>.<br /><strong>Leave field empty to disable IP restrictions for this user.</strong>'),
      ];
    }
  }
}

/**
 * Custom validation function for the user_profile_form page.
 */
function restrict_by_ip_user_profile_validate($form, &$form_state) {
  $ip_tools = \Drupal::service('restrict_by_ip.ip_tools');
  $ips = $form_state
    ->getvalue('restrict_by_ip_address');
  if (strlen($ips) > 0) {
    foreach (explode(';', $ips) as $ip) {
      try {
        $ip_tools
          ->validateIP($ip);
      } catch (\Drupal\restrict_by_ip\Exception\InvalidIPException $e) {
        $form_state
          ->setErrorByName('restrict_by_ip_address', t($e
          ->getMessage()));
      }
    }
  }
}

/**
 * Custom submit function for the user_profile_form page.
 */
function restrict_by_ip_user_profile_submit($form, &$form_state) {
  $config = \Drupal::service('config.factory')
    ->getEditable('restrict_by_ip.settings');
  $user = $form_state
    ->getFormObject()
    ->getEntity();
  $ips = $form_state
    ->getValue('restrict_by_ip_address');
  if (strlen($ips) > 0) {
    $config
      ->set('user.' . $user
      ->id(), $ips)
      ->save();
  }
  else {
    $config
      ->clear('user.' . $user
      ->id())
      ->save();
  }
}

/**
 * Implements hook_user_role_delete().
 *
 * Delete role IP restrictions when a role is deleted.
 */
function restrict_by_ip_user_role_delete($role) {
  $config = \Drupal::service('config.factory')
    ->getEditable('restrict_by_ip.settings');
  $config
    ->clear('role.' . $role
    ->id())
    ->save();
}

/**
 * Perform an IP restriction check for all roles belonging to the given user.
 *
 * @TODO
 */
function restrict_by_ip_role_check(&$user) {
  $ip2check = _restrict_by_ip_get_ip();

  // Check each role belonging to specified user
  foreach ($user->roles as $rid => $name) {
    $form_name = _restrict_by_ip_hash_role_name($name);
    $ranges = variable_get('restrict_by_ip_role_' . $form_name, '');

    // Only check IP if an IP restriction is set for this role
    if (strlen($ranges) > 0) {
      $ipaddresses = explode(';', $ranges);
      $match = FALSE;
      foreach ($ipaddresses as $ipaddress) {
        if (_restrict_by_ip_cidrcheck($ip2check, $ipaddress)) {
          $match = TRUE;
        }
      }
      if (!$match) {
        unset($user->roles[$rid]);
      }
    }
  }
}

/**
 * When a user entity is loaded, remove any roles that are restricted based on
 * IP whitelists.
 *
 * @param \Drupal\user\Entity\User[] $users
 *   Array of user entities keyed by entity ID.
 */
function restrict_by_ip_user_load($users) {
  $role_firewall = \Drupal::service('restrict_by_ip.role_firewall');
  $remove_roles = $role_firewall
    ->rolesToRemove();
  foreach ($users as $user) {
    foreach ($remove_roles as $role) {
      $user
        ->removeRole($role);
    }
  }
}

Functions

Namesort descending Description
restrict_by_ip_boot Implements hook_boot().
restrict_by_ip_form_alter Implements hook_form_alter().
restrict_by_ip_help Implements hook_help().
restrict_by_ip_init Implements hook_init().
restrict_by_ip_role_check Perform an IP restriction check for all roles belonging to the given user.
restrict_by_ip_user_delete Implements hook_user_delete().
restrict_by_ip_user_load When a user entity is loaded, remove any roles that are restricted based on IP whitelists.
restrict_by_ip_user_login Implements hook_user_login().
restrict_by_ip_user_profile_submit Custom submit function for the user_profile_form page.
restrict_by_ip_user_profile_validate Custom validation function for the user_profile_form page.
restrict_by_ip_user_role_delete Implements hook_user_role_delete().