8

I want to stop anonymous users being able to access a specific set of routes offered by the core/forum module.

specifically:

forum.index:
  path: '/forum'
defaults:
  _controller: '\Drupal\forum\Controller\ForumController::forumIndex'
  _title: 'Forums'
requirements:
  _permission: 'access content'

and

forum.page:
  path: '/forum/{taxonomy_term}'
defaults:
  _controller: '\Drupal\forum\Controller\ForumController::forumPage'
  _title_callback: '\Drupal\taxonomy\Controller\TaxonomyController::termTitle'
requirements:
  _permission: 'access content'

I just need to add: _user_is_logged_in: 'TRUE' to the routes' requirements.

How does one do this without 'hacking' core?

I have alternative routes for the above in my own module - with different names and controllers and in an ideal word I would also wish to redirect both those routes through my own. However, for a start I will take being able to stop anonymous users seeing my forums.

1
  • 1
    You have to implement event subscriber and hook into \Drupal\Core\Routing\RoutingEvents::ALTER event.
    – user21641
    Commented Jul 18, 2017 at 6:22

1 Answer 1

13

You can override route details in a route subscriber:

src/Routing/RouteSubscriber.php:

<?php

namespace Drupal\example\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('forum.index')) {
      $route->setRequirement('_user_is_logged_in', 'TRUE');
    }
  }

}

example.services.yml:

services:
  example.route_subscriber:
    class: Drupal\example\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

See Altering existing routes and adding new routes based on dynamic ones

If you want you can also replace the core classes with your own classes. You can have multiple routes for one class. Then you don't need a redirect.

2
  • I'm trying to override the route entity.node.content_translation_add, but the content_translation module is doing some kind of a hack to make sure it is always called last. Any suggestions? I'm thinking about overriding their implementation of the RouteSubscriber in my module. It smells bad, but I think that is the only way left.
    – Jigarius
    Commented Aug 30, 2018 at 15:49
  • 1
    Yes, this module uses a very low priortiy $events[RoutingEvents::ALTER] = ['onAlterRoutes', -210];, so if you want to alter the route you need to override getSubscribedEvents() from the base class and use something like -220.
    – 4uk4
    Commented Aug 30, 2018 at 18:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.