Untitled

 avatar
unknown
plain_text
5 months ago
2.3 kB
3
Indexable
<?php

namespace Drupal\site_manager_permissions\EventSubscriber;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * Dynamic permission subscriber for taxonomy vocabularies.
 */
class DynamicPermissionSubscriber implements EventSubscriberInterface {

  /**
   * The entity type manager service.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Constructs a new DynamicPermissionSubscriber object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   The entity type manager.
   */
  public function __construct(EntityTypeManagerInterface $entityTypeManager) {
    $this->entityTypeManager = $entityTypeManager;
  }

  /**
   * Modifies permissions dynamically during access checks.
   *
   * @param \Symfony\Component\HttpKernel\Event\ControllerEvent $event
   *   The controller event.
   */
  public function onKernelController(ControllerEvent $event) {
    // Get the current user.
    $current_user = \Drupal::currentUser();

    // Only target users with the "site_manager" role.
    if ($current_user->hasRole('site_manager')) {
      $user = $this->entityTypeManager->getStorage('user')->load($current_user->id());
      $profile_tag = $user->get('field_profile_tag')->value;

      // If the profile tag is not "site1", deny certain permissions.
      if ($profile_tag !== 'site1') {
        $current_user->setTemporaryPermission('create terms in vocabulary_year', FALSE);
        $current_user->setTemporaryPermission('edit terms in vocabulary_year', FALSE);
        $current_user->setTemporaryPermission('delete terms in vocabulary_year', FALSE);
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::CONTROLLER][] = ['onKernelController'];
    return $events;
  }
}





services:
  site_manager_permissions.dynamic_permission_subscriber:
    class: Drupal\site_manager_permissions\EventSubscriber\DynamicPermissionSubscriber
    arguments: ['@entity_type.manager']
    tags:
      - { name: event_subscriber }
Editor is loading...
Leave a Comment