Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
By zenimagine on
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
<?php
Perfect it works thank you
Perfect it works thank you