LoginFirewall.php in Restrict Login or Role Access by IP Address 8.4
File
src/LoginFirewall.php
View source
<?php
namespace Drupal\restrict_by_ip;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\Url;
use Drupal\Core\Utility\UnroutedUrlAssemblerInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\restrict_by_ip\IPToolsInterface;
use Drupal\restrict_by_ip\Exception\IPOutOfRangeException;
class LoginFirewall implements LoginFirewallInterface {
protected $ipTools;
protected $config;
protected $logger;
protected $urlGenerator;
public function __construct(IPToolsInterface $ip_tools, ConfigFactoryInterface $config_factory, LoggerChannelFactoryInterface $logger_factory, UnroutedUrlAssemblerInterface $url_generator) {
$this->ipTools = $ip_tools;
$this->config = $config_factory
->get('restrict_by_ip.settings');
$this->logger = $logger_factory
->get('restrict_by_ip');
$this->urlGenerator = $url_generator;
}
public function execute(AccountInterface $account) {
if ($account
->isAuthenticated() && !$this
->isLoginAllowed($account)) {
$user_ip = $this->ipTools
->getUserIP();
$this->logger
->notice(t('Login denied from @ip for %name.', [
'%name' => $account
->getAccountName(),
'@ip' => $user_ip,
]));
user_logout();
$path = $this->config
->get('error_page');
$options = [
'absolute' => TRUE,
];
if ($path) {
$redirect = $this->urlGenerator
->assemble('base:' . $path, $options);
}
else {
$redirect = Url::fromRoute('<current>', [], $options)
->toString();
}
$response = new RedirectResponse($redirect, RedirectResponse::HTTP_FOUND);
$response
->send();
}
}
public function isLoginAllowed(AccountInterface $account) {
if ($global = $this
->checkGlobalRestriction()) {
return TRUE;
}
if ($user = $this
->checkUserRestriction($account)) {
return TRUE;
}
if ($global === NULL && $user === NULL) {
return TRUE;
}
return FALSE;
}
private function checkGlobalRestriction() {
$global_data = $this->config
->get('login_range');
if (strlen($global_data) == 0) {
return NULL;
}
return $this
->checkIpRestriction($global_data);
}
private function checkUserRestriction(AccountInterface $account) {
$user_data = $this->config
->get('user.' . $account
->id());
if (strlen($user_data) == 0) {
return NULL;
}
return $this
->checkIpRestriction($user_data);
}
private function checkIpRestriction($ip) {
$user_ip = $this->ipTools
->getUserIP();
$valid = FALSE;
$ranges = explode(';', $ip);
foreach ($ranges as $range) {
try {
$this->ipTools
->validateCIDR($user_ip, $range);
} catch (IPOutOfRangeException $e) {
continue;
}
$valid = TRUE;
}
return $valid;
}
}