How can I give a Grav user, access to manage only one particular plugin?

@joejac, AFAIK, Admin does not provide fine-grained permissions. But a plugin might come to the rescue…

The plugin:

  • does not prevent a user to see the list of plugins,
  • does not prevent the user to open a plugin.
  • does prevent a user from saving any changes for all plugins, except for the one required.

Since you said “[…] how can I give a Grav user, access to […]” I assume you want to give permission to only a subset of Admin users.

  • Create a group with any name you want.
  • Assign group to one or more users.
  • Create plugin ‘plugin-guard’ using $ bin/plugin devtools new-plugin
  • Subscribe to event ‘onAdminSave’
    if ($this->isAdmin()) {
      $this->enable([
        'onAdminSave' => ['onAdminSave', 0],
      ]);
    
      return;
    }
    
  • Add the following functions:
    public function onAdminSave(Event $event)
    {
      /** @var Data */
      $data = $event['object'];
    
      $blueprints = $data->blueprints();
      $type = $blueprints['type'];
      $slug = $blueprints['slug'];
      $name = $blueprints['name'];
    
      if ($type === 'plugin' && ($slug !== 'devtools' || ($slug === 'devtools' && !$this->isGroupMember()))) {
        $this->grav['messages']->add("No permission to save plugin $name", 'error');
        $url = $_SERVER['HTTP_REFERER'];
        $this->grav->redirect($url);
      }
    }
    
    protected function isGroupMember(): bool
    {
      /** @var User */
      $user = $this->grav['user'];
      $groups = $user->get('groups');
    
      return $groups && in_array('plugin-user', $groups);
    }
    
  • Replace ‘devtools’ with the name of the plugin you want to give access to
  • Replace ‘plugin-user’ with the name of the group you’ve created.
  • If access permission is for all users and not a group:
    • Remove function isGroupMember
    • Replace if-statement with if ($type === 'plugin' && $slug !== 'devtools')

Improvements:

  • To add some flexibility, add the required plugin, or plugins as a setting in plugin-guard.yaml.
1 Like