Displaying elements based on User permissions

In Mautic, it’s possible to control the visibility of elements on the user interface based on the User’s permissions. This allows for showing or hiding certain features, links, or sections depending on the User’s Role and the permissions associated with that Role.

This approach enhances security and provides a tailored experience for each User based on their Role and access level.

Using the securityIsGranted function

To display elements conditionally based on User permissions, use the securityIsGranted function in Twig templates. The securityIsGranted function checks if the current User has the specified permission and returns a boolean value indicating whether the User has the permission granted or not.

Here’s the basic syntax:

{% if securityIsGranted('permission:string') %}
    <!-- Content to display if the user has the specified permission -->
{% endif %}

In this structure, permission:string represents the permission to verify. Mautic uses a hierarchical permission system, in the format of bundle:level:permission.

定位定义的权限

Mautic 以每个 bundle 为基础组织其权限。 每个 bundle 通常在其自己的专用 PHP 文件中定义一组权限。 这些权限定义的标准位置为:

[BundleName]/Security/[BundleName]Permissions.php

例如:

  • 用户权限:UserBundle/Security/UserPermissions.php

  • 邮件权限:EmailBundle/Security/EmailPermissions.php

  • 短信权限:SmsBundle/Security/SmsPermissions.php

这些 PHP 文件包含扩展 AbstractPermissions 的类,并定义了该 bundle 中可用的特定权限。 通常包括用于构建权限矩阵和检查单个权限的方法。

检查权限文件

打开其中一个权限文件时,通常会发现:

  • 一个名为 definePermissions 的方法,它概述了 bundle 中所有可用的权限。

  • 定义权限级别的常量,例如 LEVEL_VIEW, LEVEL_EDIT, LEVEL_FULL

  • 用于检查特定权限的方法,例如 canViewUserscanEditEmails

例如,在 UserPermissions.php 文件中,UserPermissions 类使用更结构化的方法定义了 UserBundle 中可用的权限。 以下是重要的部分:

$this->permissions = [
    'profile' => [
        'editusername' => 1,
        'editemail'    => 2,
        'editposition' => 4,
        'editname'     => 8,
        'full'         => 1024,
    ],
];

在此示例中,profile 键表示权限类别,嵌套数组定义了用于编辑用户名、电子邮件、职位、姓名以及完全访问用户资料的操作的特定权限级别。

要将这些权限密钥与 Twig 模板中的 securityIsGranted 函数一起使用,请构造适当的权限字符串。 权限字符串遵循以下格式:[bundle]:[level]:[permission].

UserPermissions 类中的权限密钥映射到相应的权限字符串:

  • editusername => user:profile:editusername

  • editemail => user:profile:editemail

  • editposition => user:profile:editposition

  • editname => user:profile:editname

  • full => user:profile:full

在每个 if 语句中,将 securityIsGranted 函数与相应的权限字符串配对。 如果当前用户具有指定的权限,则 if 代码块内的代码将运行,从而显示用于编辑用户资料信息的相应表单字段。

有关更多信息,请参阅安全文档。