To access the site, all users (except the logged-in users) need to pass through an age gate. They can only leave the welcome page if they are 18 years or older.
I started by adding a session to my custom theme.theme file.
<?php
function scottishleader_preprocess(&$variables, $hook) {
static $hooks;
$route_name = \Drupal::routeMatch()->getRouteName();
$response = new\Symfony\Component\HttpFoundation\RedirectResponse('/welcome');
$session = \Drupal::request()->getSession();
$session->set('initialSession', 'initial');
if ($session->get('ageGate') == 'passed') {
$session->remove('initialSession');
}
if ($route_name != 'agegate.route' && $session->get('initialSession') == 'initial') {
$response->send();
}
if ($route_name == 'agegate.route' && $session->get('ageGate') == 'passed') {
$homeRoute = new\Symfony\Component\HttpFoundation\RedirectResponse('/');
$homeRoute->send();
}
}
Next, I created a custom module for the age gate and the routing.yml looks like the following.
agegate.route:
path: '/welcome'
defaults:
_controller: '\Drupal\agegate\Controller\AgeGateController::content'
_form: '\Drupal\agegate\Form\AgeGateForm'
requirements:
_permission: 'access content'
The AgeGateController
class renders a form.
class AgeGateController extends ControllerBase {
public function content(){
return \Drupal::formBuilder()->getForm('Drupal\agegate\Form\AgeGateForm');
}
}
It was all working fine until I realized that, if I am logged and I try to access the front page, I get redirected infinite times!
So, for some reason, my code only works on users that aren't logged-in.
How can I create this age gate functionality?