How can I Efficiently Check if the Running User has a Custom Permission?

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

Answer

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.

Attribution
Source : Link , Question Author : Adrian Larson , Answer Author : Guy Clairbois

Leave a Comment