Question

Drupal 6

I'm trying to make it so anonymous users can access a few overview pages, but if they click on any other menu item they'll be taken to the login page. Right now the way my site is set up, using the "Node Privacy by Role" module, I can restrict content based on whether or not the user is anonymous, but I can't leave the menu items visible if it's restricted. If I set a node to be not accessible for anonymous users, it just disappears from the menu.

Does anyone know if there is a way to restrict anonymous users from certain menu items, yet leave the menu items visible in the menu so when they click on them they get sent to the login page?

OTHER TIPS

Though this question is old, and the OP asked for Drupal 6, I am gonna answer this for Drupal 7, 8, and 9 since it is one of the first results on Google.

When following this guide, it will be compatible for Drupal 8, and 9, but if you want to find the answer for Drupal 7, go to the bottom of the post.

First, you register the event subscriber in redirect_anonymous_users.services.yml in your module folder:

services:
  redirect_anonymous_users.event_subscriber:
    class: Drupal\redirect_anonymous_users\EventSubscriber\RedirectAnonymousSubscriber
    arguments: []
    tags:
      - {name: event_subscriber}

Then add RedirectAnonymousSubscriber.php for your custom event subscriber in your module in the /src/EventSubscriber/ folder.

namespace Drupal\redirect_anonymous_users\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;

/**
 * Event subscriber subscribing to KernelEvents::REQUEST.
 */
class RedirectAnonymousSubscriber implements EventSubscriberInterface {

  public function checkAuthStatus(GetResponseEvent $event) {
    if (
      \Drupal::currentUser()->isAnonymous() &&
      \Drupal::routeMatch()->getRouteName() != 'user.login'
    ) {
      $response = new RedirectResponse('/user/login', 302);
      $response->send();
    }
  }

  /**
   * {@inheritDoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('checkAuthStatus');

    return $events;
  }

}

Now for Drupal 7, go ahead and replace this line:

$response->send();

with these lines:

$event->setResponse($response);
$event->stopPropagation();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top