Earlier days we used to use Custom Permission in Visualforce page and Formula fields etc.
We used to assign custom permission to a permission set. and We used to have one utility method to check whether user has permission set or not.
public static Boolean doPermissoncheck(String sPermissionName, String sUserId){
Boolean isPermAssigned;
List<PermissionSetAssignment> lstOfAssignment
= [SELECT Id, PermissionSet.Name,AssigneeId FROM PermissionSetAssignment
WHERE PermissionSet.Name =:sPermissionName AND AssigneeId=:sUserId];
isPermAssigned = lstOfAssignment.isEmpty()?false:true;
return isPermAssigned;
}
What If we want to know custom permission from one Permission Set ?
public static Boolean isThisCustomPermissionAssigned(String customPermissionName,
PermissionSet myPermissionSet){
CustomPermission customPermission =
[SELECT Id FROM CustomPermission WHERE DeveloperName = :customPermissionName Limit 1];
List<SetupEntityAccess> isPermissionSetAssigned =
[SELECT Id FROM SetupEntityAccess WHERE ParentId = :myPermissionSet.Id
AND SetupEntityId = :customPermission.Id];
return !isPermissionSetAssigned.isEmpty();
}
The key here is the object SetupEntityAccess which act as middle object to connect to
Permission set and Custom Permission, It also act same way when we add
custom permission to Profile.
To add/remove a custom permission from a permission set:
public static void addRemoveCustomPermission(Boolean addNewPermission,
String sPermissionSetName,String sCustomPermissionName){
List<PermissionSet> LstPermissionSet =
[SELECT Id FROM PermissionSet WHERE Label = :sPermissionSetName];
List<CustomPermission> lstcustomPermission =
[SELECT Id FROM CustomPermission WHERE DeveloperName = :sCustomPermissionName];
if(addNewPermission){
SetupEntityAccess enablePermission = new SetupEntityAccess
(ParentId=LstPermissionSet[0].Id, SetupEntityId=lstcustomPermission[0].Id);
insert enablePermission;
}
else{
List<SetupEntityAccess> permissionToRemove = [SELECT Id
FROM SetupEntityAccess
WHERE ParentId = :LstPermissionSet[0].Id
AND SetupEntityId = :lstcustomPermission[0].Id];
delete permissionToRemove[0];
}
}
Now we don't need all these codes to check If user has custom permission assigned or not.
Just one line of code will suffice.
Boolean hasCustomPermission =
FeatureManagement.checkPermission('customPermissionSetname');
No comments:
Post a Comment