I am trying to redirect unauthenticated users. So anytime an unauthenticated user tries to get to the base url, redirect them to an external url. Currently works, but continues to redirect to the external url even after user is authenticated and logged in. So I am trying to disable cache whenever the base URL is accessed.
Here is my current code for redirecting in my src/EventSubscriber/RedirectAnonymousSubscriber.php
file:
class RedirectAnonymousSubscriber implements EventSubscriberInterface {
private $redirectCode = 301;
public function checkForRedirection(GetResponseEvent $event) {
// to kill page caching:
// \Drupal::service('page_cache_kill_switch')->trigger();
$is_authenticated = \Drupal::currentUser()->isAuthenticated();
$route_name = \Drupal::routeMatch()->getRouteName();
if (!$is_authenticated && $route_name !== 'user.login') {
$response = new RedirectResponse('https://example.com', $this->redirectCode);
$response->send();
exit(0);
}
}
public static function getSubscribedEvents() {
$events[KernelEvents::REQUEST][] = array('checkForRedirection', 30);
return $events;
}
}
Would that would be the correct way to go about things? And how would I go about implementing that in my *.routing.yml file and elsewhere? Thanks!