Friday, June 21, 2019

Custom permissions in Salesforce

Custom permissions let you define access checks that can be assigned to users via permission sets or profiles, similar to how you assign user permissions and other access settings. For example, you can define access checks in Apex that make a button on a Visualforce page available only if a user has the appropriate custom permission.

1. Create a Custom Permission.


2. Assign it to your profile.


3. Use the sample code.

Visualforce Page:

<apex:page controller="Sample">
    Checking Custom Permission in Visualforce page - {!$Permission.Create_Account}
    <br/><br/>
    Checking Custom Permission from Apex Class - {!accessBool }
</apex:page>

Apex Controller:

public with sharing class Sample { 
    
    public Boolean accessBool {get;set;}
    
    public Sample() {
        accessBool = checkUserHasCustomPermissionAccess('Create_Account', UserInfo.getUserId());
    }
    
    public static Boolean checkUserHasCustomPermissionAccess(String permissionName, Id userId) {
        Set < Id > permissionSetIds = new Set < Id >();
        List < User > userList = new List < User >();
        for ( SetupEntityAccess access : [ SELECT ParentId FROM SetupEntityAccess 
                                           WHERE SetupEntityId IN ( SELECT Id 
                                                                    FROM CustomPermission 
                                                                    WHERE DeveloperName = :permissionName )
        ]) 
            permissionSetIds.add(access.ParentId);
        userList = [ SELECT Username FROM User WHERE Id IN (
                SELECT AssigneeId FROM PermissionSetAssignment
                WHERE PermissionSetId IN :permissionSetIds AND AssigneeId =: userId ) ];
        return userList.isEmpty() ? false : true;
    }
    
}

Output:


No comments:

Post a Comment