Drupal 8 study note 2: Defining permissions

  1. Permissions are stored in a mymodule.permissions.yml le. Add a mymodule. permissions.yml to the base directory of your module.
  2. First, we need to de ne the internal string used to identify this permission, such as view mymodule pages:
           view mymodule pages:
    
  3. Each permission is a YAML array of data. We need to provide a title key that will be

    displayed on the permissions page:

           view mymodule pages:
             title: 'View my module pages'
    
  4. Permissions have a description key to provide details of the permission on the permissions page:
           view mymodule pages:
             title: 'View my module pages'
             description: 'Allows users to view pages provided by My Module'
    
  5. Save your permissions.yml, and edit the module’s routing.yml to add the permission.
  6. Modify the route’s requirements key to have a _permissions key that is equal to the de ned permission:
           mymodule.mypage:
             path: /mypage
             defaults:
    
               _controller: '\Drupal\mymodule\Controller\
           MyPageController::customPage'
    
               _title: 'My custom page'
             requirements:
    
               _permission: 'view mymodule pages'
  1. Visit Con guration and then Development to rebuild Drupal’s caches.
  2. Visit People and then Permissions to add your permission to the authenticated userand anonymous user roles.

 

De ning permissions programmatically

Permissions can be de ned by a module programmatically or statically in a YAML le. A module needs to provide a permission_callbacks key in its permissions.yml that contains an array of classes and their methods or a procedural function name.

For example, the Filter module provides granular permissions based on the different text lters created in Drupal:

   permission_callbacks:
   - Drupal\filter\FilterPermissions::permissions

This tells the user_permissions service to execute the permissions method of the \Drupal\Filter\FilterPermissions class. The method is expected to return an array that matches the same structure as that of the permissions.yml le.

Checking whether a user has permissions

The user account interface provides a method for checking whether a user entity has a permission. To check whether the current user has a permission, you will get the current user, and you need to invoke the hasPermission method:

   \Drupal::currentUser()->hasPermission('my permission');

 

Extending Drupal

The \Drupal::currentUser() method returns the current active user object. This allows you to check whether the active user has permissions to perform some sort of actions.

Leave a Comment