I have a feature where if a user navigates to a specific url (www.mysite.com/special-content
) they are redirected to the login page, where we've appended a destination to the request (www.mysite.com/user/login?destination=special-content
).
We created a custom module using a checkAuthStatus
event subscriber to detect anonymous users and redirect them appropriately:
$ cat src/EventSubscriber/RedirectAnonymousSubscriber.php
<?php
namespace Drupal\anon_redirect\EventSubscriber;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Event subscriber subscribing to KernelEvents::REQUEST.
*/
class RedirectAnonymousSubscriber implements EventSubscriberInterface {
public function __construct() {
$this->account = \Drupal::currentUser();
}
public function checkAuthStatus(GetResponseEvent $event) {
$paths = [
'/special-content',
'/more-special-content'
];
if ($this->account->isAnonymous()) {
foreach ( $paths as $path ) {
if ( substr($_SERVER['REQUEST_URI'], 0, strlen($path)) === $path ) {
$url = \Drupal\Core\Url::fromUri('internal:/user/login',[
'query'=>['destination'=>$_SERVER['REQUEST_URI']],
]);
$response = new RedirectResponse('/user/login?destination='.$_SERVER['REQUEST_URI'], 302);
$response->send();
return;
}
}
}
}
public static function getSubscribedEvents() {
$events[KernelEvents::REQUEST][] = ['checkAuthStatus'];
return $events;
}
}
This has been working fine for a few months, but recently I got complains that people were not getting redirected. Upon investigation, I saw that they were getting 'access denied', as evidenced by the watchdog log. That is, when they are not logged in, they see our 301 page, instead of getting redirected.
Frustratingly, I've only been able to intermittently reproduce this problem. Sometimes I get the 301 page, sometimes I get the login page with the proper redirect query appended. I've tried both Firefox and Chrome, private sessions, clearing cookies, etc.
I suspect that whatever decides access also is listening to checkAuthStatus
and sometimes having the final word about what page is ultimately sent to the end-user, and our module's behavior is not implemented, while other times, our event listener is invoked.
My question is if there is any way I can see what event listeners are subscribed to the checkAuthStatus
event, and ideally, which one is having the final word as to the ultimate response from Drupal. I suspect another one is somehow getting prioritized over mine, and would like to confirm or deny that theory.
return
in thecheckForRedirection()
method in the answer to the question you linked. It does return$events
ingetSubscribedEvents()
, but so does my code. Also I don't see where the priority is set in the linked question or accepted answer.$event->setResponse($response)