public function IpRule::check in Access Filter 8
Checks the current access by the rule.
Parameters
\Symfony\Component\HttpFoundation\Request $request: A request instance.
Return value
\Drupal\Core\Access\AccessResult The access result.
Overrides RuleInterface::check
File
- src/
Plugin/ AccessFilter/ Rule/ IpRule.php, line 71
Class
- IpRule
- Filter rule using IP address.
Namespace
Drupal\access_filter\Plugin\AccessFilter\RuleCode
public function check(Request $request) {
$pattern = isset($this->configuration['address']) ? $this->configuration['address'] : '*';
if ($pattern == '*') {
$is_ip_matched = TRUE;
}
else {
$ip = $request
->getClientIp();
$ip_long = ip2long($ip);
$patterns = explode('-', $pattern);
if (isset($patterns[1])) {
// Check as 2 IP address range format.
$is_ip_matched = $ip_long >= ip2long($patterns[0]) && $ip_long <= ip2long($patterns[1]);
}
else {
// Check as single IP address and subnet format.
$check = explode('/', $pattern);
if (!isset($check[1])) {
$check[1] = 32;
}
$network_long = ip2long($check[0]);
$mask_long = bindec(str_repeat('1', $check[1]) . str_repeat('0', 32 - $check[1]));
$is_ip_matched = ($ip_long & $mask_long) == $network_long;
}
}
if ($is_ip_matched) {
if ($this->configuration['action'] == 'allow') {
return AccessResult::allowed();
}
return AccessResult::forbidden();
}
return AccessResult::neutral();
}