2

How do I restrict access to the route by current user in Drupal 8?

I want to create a new tab in user profile path: '/user/{user}/my-cool-tab', which should be accessible by current user only. For example:

  • path /user/5/my-cool-tab should be available only for UID=5
  • path /user/7/my-cool-tab should be available only for UID=7
  • etc.

Which way is the simplest and correct for that?

2 Answers 2

2

You need an access check where you compare the passed user id with the current user, here's an example from simplenews:

public function checkAccess(UserInterface $user) {
  $account = $this->currentUser();

  return AccessResult::allowedIfHasPermission($account, 'administer simplenews subscriptions')
    ->orIf(AccessResult::allowedIfHasPermission($account, 'subscribe to newsletters')
      ->andIf(AccessResult::allowedIf($user->id() == $account->id())));
}

Note that this includes and admin permission check, for admins that can actually see the page for other users.

If you do not need that, you could also just make your route /my-cool-page and use the current user for whatever you are doing. With D8's routing system, you can even make local task appear on the user page if you want to.

1
  • 1
    I thought there is some standard way to achieve that, because it looks very common situation as for me.. anyway thanks.
    – graceman9
    Aug 11, 2016 at 13:55
0

If anyone wants to see full details how to achieve such case.

Route Path with custom access checking function

path: '/user/{user}/my-cool-tab'
...
requirements:
    _custom_access: '\Drupal\mymodule\Controller\AccessCheck::myRoutePermission'

Create new controller which specifically check the accesses.

mymodule/src/Controller/AccessCheck.php
<?php

namespace Drupal\mymodule\Controller;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Drupal\Core\Session\AccountInterface;

/**
 * Access Checks controller.
 */
class AccessCheck extends ControllerBase {

  /**
   * The request stack.
   *
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  protected $requestStack;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * The controller constructor.
   *
   * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
   *   The request stack.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Session\AccountInterface $current_user
   *   The current user.
   */
  public function __construct(RequestStack $request_stack, EntityTypeManagerInterface $entity_type_manager, AccountInterface $current_user) {
    $this->requestStack = $request_stack->getCurrentRequest();
    $this->entityTypeManager = $entity_type_manager;
    $this->currentUser = $this->entityTypeManager->getStorage('user')->load($current_user->id());
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('request_stack'),
      $container->get('entity_type.manager'),
      $container->get('current_user')
    );
  }

  /**
   * Checks access for __ route.
   */
  public function myRoutePermission() {
    $uid = $this->requestStack->attributes->get('user_id');
    if ($this->currentUser->hasPermission('administer users')) {
      return AccessResult::allowed();
    }
    elseif ($uid != $this->currentUser->id()) {
      // Return 403 Access Denied page.
      return AccessResult::forbidden();
    }
    return AccessResult::allowed();
  }

}

This way you can add any number of access checking function with any type of checks.

Your Answer

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

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