You are here

class IpLoginController in IP Login 4.x

Hierarchy

Expanded class hierarchy of IpLoginController

3 files declare their use of IpLoginController
EarlyIpLoginMiddleware.php in src/StackMiddleware/EarlyIpLoginMiddleware.php
IpLoginMiddleware.php in src/StackMiddleware/IpLoginMiddleware.php
ip_login.module in ./ip_login.module
Hooks for the IP login module.

File

src/IpLoginController.php, line 12

Namespace

Drupal\ip_login
View source
class IpLoginController extends ControllerBase {

  /**
   * Menu callback for IP-based login: do the actual login.
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   A redirect response object that may be returned by the controller.
   */
  public function loginProcess(Request $request) {
    $uid = $this
      ->checkIpLoginExists($request);
    if (empty($uid)) {
      \Drupal::logger('ip_login')
        ->warning('IP login processing accessed without any matches from @ip.', [
        '@ip' => $request
          ->getClientIp(),
      ]);
    }
    else {
      static::doUserLogin($uid, $request);
    }
    $destination = Url::fromUserInput(\Drupal::destination()
      ->get());
    if ($destination
      ->isRouted()) {

      // Valid internal path.
      return $this
        ->redirect($destination
        ->getRouteName(), $destination
        ->getRouteParameters());
    }
    else {
      return $this
        ->redirect('<front>');
    }
  }

  /**
   * Logs in a user.
   *
   * @param int|string $uid
   *   A valid user ID.
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The current request object.
   */
  public static function doUserLogin($uid, Request $request) {
    $user = User::load($uid);
    user_login_finalize($user);
    \Drupal::logger('ip_login')
      ->notice('Logging in user @uid through IP login from @ip.', [
      '@uid' => $uid,
      '@ip' => $request
        ->getClientIp(),
    ]);
    \Drupal::messenger()
      ->addMessage(t('You have been logged in automatically using IP login.'));
  }

  /**
   * Looks up if current request IP matches an IP login.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   A request object.
   *
   * @return string|false
   *   Returns the user ID if the IP address was matched, FALSE otherwise.
   */
  public static function checkIpLoginExists(Request $request) {
    $ip = inet_pton($request
      ->getClientIp());

    // This query is done super early in the request (before page cache), so we
    // can optimize the majority case when the entity type is using core's
    // default storage handler, and do a straight database query.
    $entity_type = \Drupal::entityTypeManager()
      ->getDefinition('user');
    if (is_subclass_of($entity_type
      ->getStorageClass(), SqlContentEntityStorage::class)) {
      $result = \Drupal::database()
        ->select('users_field_data', 'ufd')
        ->fields('ufd', [
        'uid',
      ])
        ->condition('ip_login__ip_start', $ip, '<=')
        ->condition('ip_login__ip_end', $ip, '>=')
        ->condition('status', 1)
        ->orderBy('uid', 'DESC')
        ->range(0, 1)
        ->execute()
        ->fetchCol();
      $uid = reset($result);
    }
    else {
      $query = \Drupal::entityQuery('user')
        ->condition('ip_login.ip_start', $ip, '<=')
        ->condition('ip_login.ip_end', $ip, '>=')
        ->condition('status', 1);
      $uids = $query
        ->execute();
      $uid = reset($uids);
    }
    return $uid;
  }

  /**
   * Checks whether a user can log into another account.
   *
   * @param \Drupal\Core\Session\AccountInterface $user
   *   The user account.
   *
   * @return bool
   *   Returns TRUE if the given user can login into another account, FALSE
   *   otherwise.
   */
  public static function canLoginAsAnotherUser(AccountInterface $user) {

    // People who can administer this module can.
    if ($user
      ->hasPermission('administer ip login')) {
      return TRUE;
    }

    // If the user doesn't have a matching IP, then we let them log in normally.
    if (!self::checkIpLoginExists(\Drupal::request())) {
      return TRUE;
    }

    // For all other users check the correct permission.
    return $user
      ->hasPermission('can log in as another user');
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$currentUser protected property The current user service. 1
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$formBuilder protected property The form builder. 2
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 2
ControllerBase::$stateService protected property The state service.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 46
ControllerBase::currentUser protected function Returns the current user. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 2
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 2
ControllerBase::redirect protected function Returns a redirect response object for the specified route.
ControllerBase::state protected function Returns the state storage service.
IpLoginController::canLoginAsAnotherUser public static function Checks whether a user can log into another account.
IpLoginController::checkIpLoginExists public static function Looks up if current request IP matches an IP login.
IpLoginController::doUserLogin public static function Logs in a user.
IpLoginController::loginProcess public function Menu callback for IP-based login: do the actual login.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 4
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.