1

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?

1

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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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