23

Is there any way to check in Apex if the running user has a specific Custom Permission? The best I know of using available methods involves two separate SOQL queries:

public static Boolean doesRunningUserHavePermission(String apiName)
{
    Set<Id> accessiblePermissionIds = new Set<Id>();
    for (SetupEntityAccess access : [
        SELECT SetupEntityId FROM SetupEntityAccess
        WHERE SetupEntityType = 'CustomPermission' AND ParentId IN (
            SELECT PermissionSetId FROM PermissionSetAssignment
            WHERE AssigneeId = :UserInfo.getUserId()
        )
    ]) accessiblePermissionIds.add(access.SetupEntityId);

    return 0 < [
        SELECT count() FROM CustomPermission
        WHERE Id IN :accessiblePermissionIds
        AND DeveloperName = :apiName
    ];
}

And then I would need to run:

Boolean hasPermission doesRunningUserHavePermission('CanPerformSomeOperation');
3

3 Answers 3

46

As of the Winter 18 Release, we can now use the FeatureManagement class for this requirement. The above method can be removed entirely and I can simply call:

Boolean hasPermission = FeatureManagement.checkPermission('CanPerformSomeOperation');

Thanks to @sfdcfox for pointing this one out.

9

Adrian Larson's answer of using FeatureManagement's static Boolean checkPermission(String customPermissionDeveloperName) will Efficiently Check if the Running User has a Custom Permission.

Testing Apex when using FeatureManagement's static Boolean checkPermission(String customPermissionDeveloperName) isn't so simple. Often, using Custom Permissions will grant a User something private or special, and I want to make sure my Unit Test is doing what I think it's doing when a User both has and doesn't have the Custom Permission(s) in question. So, I made a github repo, TestCustomPermissions, to automate adding Custom Permissions. See README.md for documentation and example.

-2

At User object, simply add formula

$Permission.<<Permission set name>>

and use this checkbox anywhere else in the Org.

1
  • Bloats the data model. New permission = new field?
    – Trang Oul
    Nov 14, 2023 at 10:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .