You are here

AutoLoginUrlGeneral.php in Auto Login URL 2.x

Same filename and directory in other branches
  1. 8 src/AutoLoginUrlGeneral.php

File

src/AutoLoginUrlGeneral.php
View source
<?php

namespace Drupal\auto_login_url;

use Drupal\Component\Utility\Random;

/**
 * Class AutoLoginUrlGeneral.
 *
 * @package Drupal\auto_login_url
 */
class AutoLoginUrlGeneral {

  /**
   * Constructor.
   */
  public function __construct() {
  }

  /**
   * Check if this IP is blocked by flood.
   *
   * @return bool
   *   TRUE if it is blocked.
   */
  public function checkFlood() {

    // Maybe use DI in the future.
    $flood_config = \Drupal::config('user.flood');
    $flood = \Drupal::flood();
    if (!$flood
      ->isAllowed('user.failed_login_ip', $flood_config
      ->get('ip_limit'), $flood_config
      ->get('ip_window'))) {
      return TRUE;
    }
    else {
      return FALSE;
    }
  }

  /**
   * Register flood event for this IP.
   *
   * @param string $hash
   *   Code that passes through URL.
   */
  public function registerFlood($hash) {
    $flood_config = \Drupal::config('user.flood');
    $flood = \Drupal::flood();

    // Register flood event.
    $flood
      ->register('user.failed_login_ip', $flood_config
      ->get('ip_window'));

    // Log error.
    \Drupal::logger('auto_login_url')
      ->error('Failed Auto Login URL from ip: @ip and hash: @hash', [
      '@ip' => \Drupal::request()
        ->getClientIp(),
      '@hash' => $hash,
    ]);
  }

  /**
   * Get secret key for ALU or create now.
   */
  public function getSecret() {
    $config = \Drupal::config('auto_login_url.settings');

    // Check if it exists.
    $secret = $config
      ->get('secret');

    // Create if it does not exist.
    if ($secret == '') {
      $random_generator = new Random();
      $secret = $random_generator
        ->name(64);
      \Drupal::configFactory()
        ->getEditable('auto_login_url.settings')
        ->set('secret', $secret)
        ->save();
    }
    return $secret;
  }

  /**
   * Get user password hash.
   *
   * @param int $uid
   *   User id.
   *
   * @return string
   *   Hashed password.
   */
  public function getUserHash($uid) {
    $query = \Drupal::database()
      ->select('users_field_data', 'u');
    $query
      ->addField('u', 'pass');
    $query
      ->condition('u.uid', $uid);
    $query
      ->range(0, 1);
    return $query
      ->execute()
      ->fetchField();
  }

}

Classes

Namesort descending Description
AutoLoginUrlGeneral Class AutoLoginUrlGeneral.