9

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');
19

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.

6

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.

0

At User object, simply add formula

IF( $Permission.<<Permission set name>>, TRUE, FALSE)

and use this checkbox anywhere else in the Org.

  • You never ever need to have any formula that reads IF(condition, true, false). You can always simplify it to just condition. – Adrian Larson Oct 8 at 14:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.