I was looking for a little help to find all users with a particular Custom Permission
assigned to them, either via Profile
or Permission Set
.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Update
Please note that for the running user, you can use the FeatureManagement
class:
Boolean isEnabled = FeatureManagement.checkPermission('My_Permission_Api_Name');
Surprisingly, I don’t think you can do it more simply than the below.
Execution
public static List<User> getUsersWithCustomPermission(String name) { Set<Id> permissionSetIds = new Set<Id>(); for (SetupEntityAccess access : [ SELECT ParentId FROM SetupEntityAccess WHERE SetupEntityId IN ( SELECT Id FROM CustomPermission WHERE DeveloperName = :name ) ]) { permissionSetIds.add(access.ParentId); } return permissionSetIds.isEmpty() ? new List<User>() : [ SELECT Username FROM User WHERE Id IN ( SELECT AssigneeId FROM PermissionSetAssignment WHERE PermissionSetId IN :permissionSetIds ) ]; }
Explanation
At the end of the day, you need to hit four separate tables to make this work.
CustomPermission
SetupEntityAccess
(adds the CustomPermission to a PermissionSet)PermissionSet
PermissionSetAssignment
You can reduce your queries consumed to two by using inner-joins.
EDIT
It was mentioned in the comments that you may want to filter for namespace. To do so, I would modify the above join on CustomPermission
as below:
SELECT Id FROM CustomPermission WHERE DeveloperName = :name AND NamespacePrefix = null
You could also use overloads at the method level:
public static List<User> getUsersWithCustomPermission(String name) { return getUsersWithCustomPermission(name, null); } public static List<User> getUsersWithCustomPermission(String name, String namespacePrefix) { // use modified queries }
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0