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.