Как изменить доступ к ссылке меню по ролям пользователя

Главные вкладки

Аватар пользователя Iurii.P Iurii.P 26 октября 2018 в 14:46

Я написал модуль для Drupal 8, который позволяет управлять доступом к содержимому ноды по ролям пользователя. Мне нужно такое же решение для администрирования доступа к элементам меню - знаете ли вы какие-либо решения? Может быть есть хук для управления доступом к элементам меню , чтобы решить эту проблему?

Вот код моего модуля:


<?php

use Drupal\Core\Access\AccessResult;

/**
* Implements hook_node_access().
*/
function node_per_role_node_access(\Drupal\node\NodeInterface $node$op, \Drupal\Core\Session\AccountInterface $account) {
    
$current_roles $account->getRoles();
    
//return AccessResult::allowed();
    
if(in_array('administrator'$current_roles)){
        return 
AccessResult::allowed();
    }

    

$node_required_roles $node->get('field_role')->getValue();
    
    if(empty(
$node_required_roles)){
        return 
AccessResult::neutral();
    }

        

// role from node
    
$node_role_list = array();
    foreach(
$node_required_roles AS $nrr){
        
$node_role_list[] = $nrr['target_id'];
    }
    
    
// Get All users having the role of answer.
    
$roles = \Drupal\user\Entity\Role::loadMultiple();
    
$shop_role_list = array();
    
$user_role_list = array();
    foreach (
$roles as $role => $roleObj) {
      if (
$roleObj->hasPermission("shop user role")) {
        if(
in_array($role$node_role_list)){
            
$shop_role_list[] = $role;
        }
      }else{
        if(
in_array($role$node_role_list)){
            
$user_role_list[] = $role;
        }
      }
    }

    

$current_shop_role_list = array();
    
$current_user_role_list = array();
    
    
$user_access FALSE;
    
$shop_access FALSE;
        
    foreach (
$current_roles as $current_roles_value) {
        if(
in_array($current_roles_value$shop_role_list)){
            
$current_shop_role_list[] = $current_roles_value;
            if(
in_array($current_roles_value$shop_role_list)){
                
$user_access TRUE;
            }
        }else{
            
$current_user_role_list[] = $current_roles_value;
            if(
in_array($current_roles_value$user_role_list)){
                
$shop_access TRUE;
            }
        }
        
    }

    if(

$user_access && $shop_access){
        return 
AccessResult::allowed();
    }
    
/*foreach($node_required_roles AS $nrr){
        if(in_array($nrr['target_id'], $current_roles)){
             return AccessResult::allowed();
        }
    }*/
    
return AccessResult::forbidden();
}

/**
 * Implements hook_form_FORM_ID_alter().
 * hiding unnecessary roles from edit form
 */
function node_per_role_form_node_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  if(isset(
$form['field_role']['widget']['#options'])){
      
$options = &$form['field_role']['widget']['#options'];
      
      
$roles_to_unset = array(
          
'administrator',
          
'anonymous',
          
'authenticated'
      
);

      foreach(

$roles_to_unset AS $r){
          unset(
$options[$r]);
      }
    }
}
?>

Комментарии

Аватар пользователя VasyOK VasyOK 26 октября 2018 в 15:17

Насколько я знаю если у пользователя нет разрешения на просмотр ноды, он и не увидит ссылку в меню, ведущую на ноду.

Аватар пользователя Iurii.P Iurii.P 26 октября 2018 в 15:27

Вы правы, но не все меню-итемы ведут к нодам, некоторые показывают попапы с данными с других моих модулей либо перенаправляют на другие сервисы, к ним мне нужно ограничивать доступ в зависимости от ролей пользователей.