I created a page in a custom module. I want only the current user to access this page on their behalf.

For example, I am user ID 51. If I go to :

/user/51/tasks

I can see this page.

If I go to another user :

/user/78/tasks

I must have an error 403 access denied.

Here is my full module :

https://git.drupalcode.org/sandbox/zenimagine-3076032

How to do this ?

/task_notify/task_notify.routing.yml

task_notify.user_page.tasks:
  path: '/user/{user}/tasks'
  defaults:
    _controller: '\Drupal\task_notify\Controller\TaskNotifyUserController::Tasks'
    _title: 'Liste des tâches'
  requirements:
    _custom_access: '\Drupal\task_notify\Controller\TaskNotifyUserController::taskAccess'

/task_notify/src/Controller/TaskNotifyUserController.php

<?php

namespace Drupal\task_notify\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Session\AccountInterface;
use Drupal\user\UserInterface;

class TaskNotifyUserController extends ControllerBase {

  public function Tasks() {
    return [
      '#theme' => 'task_notify_user_template',
    ];
  }

  public function taskAccess(AccountInterface $account, UserInterface $user) {
    return AccessResult::allowedIf($account->id() == $user->id())
      ->orIf(AccessResult::allowedIfHasPermission($account, 'administer users'));
  }

}

Comments

wombatbuddy’s picture

<?php

namespace Drupal\task_notify\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class TaskNotifyUserController extends ControllerBase {

  /**
   * The current route match.
   *
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   */
  protected $route_match;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    $instance = parent::create($container);
    $instance->route_match = $container->get('current_route_match');
    return $instance;
  }

  /**
   * {@inheritdoc}
   */
  public function Tasks() {
    return [
      '#theme' => 'task_notify_user_template',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function taskAccess(AccountInterface $account) {
    $uid = $this->route_match->getParameter('user');

    return AccessResult::allowedIf($account->id() == $uid)
      ->orIf(AccessResult::allowedIfHasPermission($account, 'administer users'));
  }

}
zenimagine’s picture

Perfect it works thank you