- Using your terminal, navigate to your Drupal site's root directory.
- Use the require command from Composer to add the library:
composer require alsar/stack-ip-restrict
- Composer will then add the library to the composer.json file and install the library along with any dependencies. Its namespace will now be registered.
- Now, you will need to implement a module that registers the library as a middleware service. We'll call the module ip_restrict. Add the following code to the ip_restrict.info.yml file:
name: IP Restrict type: module description: Restricts access to the Drupal site based on allowed IP addresses core: 8.x
- Create ip_restrict.services.yml. This will register the library with Drupal's service container:
parameters:
ip_restrict:
enabled: true
ipAddresses: ['127.0.0.1', 'fe80::1', '::1']
services:
ip_restrict.middleware:
class: Alsar\Stack\IpRestrict
arguments: ['%ip_restrict%']
tags:
- { name: http_middleware }
The parameters section defines configuration values, which can be overridden in the site's services.yml file. The services section defines the service's machine name, class file, its constructor arguments, and any tags.
- Next, you will need to implement a compiler pass injection. This will allow us to alter our service in the container definition when it is compiled. Create a src/Compiler directory and make IpRestrictPass.php.
When making a compiler pass class, the class and filename must be formatted in a specific way. It is the camel case version of the module name followed by Pass.
- The IpRestrictPass.php will provide the IpRestrictPass class, which implements \Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface:
<?php
namespace Drupal\ip_restrict\Compiler;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
/**
* Adds the IP Restrict middleware if enabled.
*/
class IpRestrictPass implements CompilerPassInterface {
/**
* {@inheritdoc}
*/
public function process(ContainerBuilder $container) {
if (FALSE === $container->hasDefinition('ip_restrict.middleware')) {
return;
}
$ip_restrict_config = $container->getParameter('ip_restrict');
if (!$ip_restrict_config['enabled']) {
$container->removeDefinition('ip_restrict.middleware');
}
}
}
In our compiler pass, we check the enabled parameter and remove our middleware if it has been disabled (so that it does not restrict allowed IPs).
- Enable the module. The stack middleware service will be registered and now supporting restrict access from local IP addresses.