5

I wanted to access the administrative permissions in the apex controller for e.g. want to check that the "API Enabled" checkbox is enabled or not.

Please let me know if there is a way to do this.

Thanks in advance!!!

2
  • "API Enabled" is available at profile level. Also this is available for "System Administrator" or cloned "System Administrator" profiles. So can you please explain where do you want to check through Apex?
    – Saroj Bera
    Jul 22, 2015 at 8:19
  • HI saroj thanx for reply!! I have a custom button on click of which it is redirecting to vf page .. so for some custom profile i need to show a message that "you don't have access to this" so for that along with profiles need to check that "API Enabled" checkbox is enabled or not on that particular profile.. Jul 22, 2015 at 8:52

3 Answers 3

4

Below is a code to check the "API Enabled" status for logged in user profile. You can query from other profiles in similar way. Hope this will help.

    User user_temp = [SELECT ProfileId FROM User where Id = :UserInfo.getUserId()]; 
    Profile temp_profile = [SELECT PermissionsApiEnabled FROM Profile Where Id = :user_temp.ProfileId];
    Boolean api_permission= temp_profile.PermissionsApiEnabled;
    System.debug('api_permission '+api_permission);
3
  • thanx!!! thats work for me...will mark it as answer and also vote it up :) Jul 22, 2015 at 9:47
  • 1
    this answer will only work if you only care about Profile permissions --- if your user's Profile has PermissionsApiEnabled = false, but the User has been assigned a PermissionSet with PermissionsApiEnabled = true, then this code will be inaccurate, as the User will have permission to access the API, but this code will say that the User cannot access the API.
    – zachelrath
    Jul 22, 2015 at 10:33
  • hmm Will remember your point @zachelrath Jul 23, 2015 at 5:23
5

You need to check for whether the running User has been assigned the PermissionsApiEnabled Permission --- however, you need to check this on both the running User's Profile AND on any Permission Sets that the running User has been assigned.

The below is a modified version of utility methods that we use to obtain check for various User permissions. The GetRunningUserRecord() method is very generic to allow for requesting both multiple fields on the User object (e.g. other Permissions fields in addition to PermissionsApiEnabled) via the Profile relationship, as well as for querying these fields via the User's PermissionSetAssignments child relationship / sub-query. It also gets cached so that you don't have to re-query the User record every time your Apex code wants to check whether the User has a given Permission assigned to them.

Here's the code:

public with sharing class Utils {

    // Retrieve detailed information on the running User.
    // This query will only be made if needed
    private static User cachedRunningUserRecord;
    public static User GetRunningUserRecord() {
        if (cachedRunningUserRecord == null) {
            Set<String> neededFields = new Set<String>{
                'Profile.PermissionsApiEnabled',
                'Profile.PermissionsModifyAllData'
            };

            Map<String,String> relatedObjectsQueries = new Map<String,String>{
                'PermissionSetAssignments' => 
                    '(select Id, PermissionsApiEnabled, PermissionsModifyAllData '
                    + 'from PermissionSetAssignments '
                    + 'where PermissionSet.PermissionsApiEnabled = true '
                    + 'or PermissionSet.PermissionsModifyAllData = true)'
            };
            DescribeSObjectResult dsor = User.SObjectType.getDescribe();
            List<Schema.ChildRelationship> childRels = dsor.getChildRelationships();

            // Check to see whether the user has access to our desired child relationships
            for (String s : relatedObjectsQueries.keyset()) {
                boolean foundChildRel = false;
                for (Schema.ChildRelationship cr : childRels){
                    if (cr.getRelationshipName() == s) {
                        foundChildRel = true;
                        break;
                    }
                }
                if (!foundChildRel) {
                    relatedObjectsQueries.remove(s);
                }
            }

            if (!neededFields.isEmpty() || !relatedObjectsQueries.isEmpty()) {

                String neededFieldsQuery = !neededFields.isEmpty() ? String.join(new List<String>(neededFields),',') : '';
                String relatedObjectsQuery = !relatedObjectsQueries.isEmpty() ? String.join(relatedObjectsQueries.values(),',') : '';

                try {
                    cachedUserRecord = Database.query(
                        'select '
                        // Add all of the fields on the User record that we need
                        + neededFieldsQuery
                        // Add any related object subqueries
                        + (neededFieldsQuery.length()>0 ? ', ' : '') + relatedObjectsQuery
                        + ' from User where Id = \''+UserInfo.getUserId()+'\' limit 1'
                    );
                } catch (Exception ex) {}   
            }
        }
        return cachedRunningUserRecord;
    }

    public static boolean DoesRunningUserHavePermission(String permName) {
         User u = GetRunningUserRecord();
         // Determine whether the running user has a given Permission   
         boolean hasPerm = false;

         if (u != null) {           
            // First check the Profile          
            SObject prof = u.getSObject('Profile');
            if (prof != null && Boolean.valueOf(prof.get(permName)) == true) {
                return true;
             }
             // Then check Permission Set Assignments
             else {
                List<SObject> assigns = u.getSObjects('PermissionSetAssignments');
                if ((assigns != null && !assigns.isEmpty()) {
                    for (PermissionSetAssignment psa : assigns) {
                        if (psa.get(permName)!=null && Boolean.valueOf(psa.get(permName)) == true) {
                            hasPerm = true;
                            break;
                        }
                    }
                }           
             }          
          }
          return hasPerm;
     }
}

You can use this to determine whether the running user is Api Enabled like this:

boolean isApiEnabled = Utils.DoesRunningUserHavePermission('PermissionsApiEnabled');

As well as check for other Permissions that you have requested:

boolean canModifyAllData = Utils.DoesRunningUserHavePermission('PermissionsModifyAllData');
2

Here is an extended apex helper based on the response from @zachelrath. It has a reasonable amount of caching built-in. Unit tests included below.

GIST: https://gist.github.com/jkentjnr/599d6df0332e7fa6efb493b8156ddac3

public without sharing class SystemPermissionUtility {

    // Add the permissions you need to look for here.
    // - Could be extended to read from another source.
    private static List<String> getPermissionList() {
        return new List<String>{
            'PermissionsApiEnabled',
            'PermissionsModifyAllData'
        };
    }

    // ---

    public static Map<String, Boolean> permissionCache;
    private static User p_userWithPermissions { get; set; }

    public static User getUserWithPermissions() {

        if (p_userWithPermissions == null) {

            List<String> permissionList = SystemPermissionUtility.getPermissionList();

            List<String> userFieldsList = new List<String>{ 'Id', 'Name' };
            for (String permission : permissionList) {
                userFieldsList.add('Profile.' + permission);
            }

            List<String> permissionSetAssignmentFieldsList = new List<String>();
            for (String permission : permissionList) {
                permissionSetAssignmentFieldsList.add('PermissionSet.' + permission);
            }

            p_userWithPermissions = Database.Query(
                String.join(
                    new List<String> {
                        'SELECT',
                        String.join(userFieldsList, ', '),
                        ',',
                        '(SELECT Id,',
                        String.join(permissionSetAssignmentFieldsList, ', '),
                        'FROM PermissionSetAssignments WHERE',
                        String.join(permissionSetAssignmentFieldsList, ' = TRUE OR '),
                        ' = TRUE)',
                        'FROM User WHERE Id = \'' + UserInfo.getUserId() + '\' LIMIT 1'
                    },
                    ' '
                )
            );

        }

        return p_userWithPermissions;

    }

    public static Boolean userHasPermission(String permissionName) {

        if (permissionCache == null)
            // Lazy load the permission cache.
            permissionCache = new Map<String, Boolean>();
        else {
            // Check the cache for permission.
            if (permissionCache.containsKey(permissionName) == true) {
                return permissionCache.get(permissionName);
            }
        }

        // Get the user with permissions (cached if possible)
        User u = getUserWithPermissions();

        // Determine whether the running user has a given Permission   
        Boolean hasPermission = false;

        if (u != null) {    
            // First check the Profile          
            SObject profile = u.getSObject('Profile');
            if (profile != null && Boolean.valueOf(profile.get(permissionName)) == true) {
                hasPermission = true;
            }
            // Then check Permission Set Assignments
            else {
                List<SObject> psaList = u.getSObjects('PermissionSetAssignments');
                System.Debug('psaList: ' + psaList);
                if (psaList != null && psaList.isEmpty() == false) {
                    for (SObject psa : psaList) {
                        SObject ps = psa.getSObject('PermissionSet');
                        if (ps.get(permissionName) != null && Boolean.valueOf(ps.get(permissionName)) == true) {
                            hasPermission = true;
                            break;
                        }
                    }
                }
            }
        }

        // Cache the permission and return the result.
        permissionCache.put(permissionName, hasPermission);
        return hasPermission;

    }
}

Unit tests:

@isTest
private class SystemPermissionUtilityTest {

    // TODO: Modify references to ApplicationMock to create Standard & Admin users.

    @isTest
    static void testUserHasPermission_Valid_Profile_Missing_PermissionSet_Success() {

        // Get a basic user.
        User u = ApplicationMock.getStandardUser();

        // Create PermissionSet and assign to test user
        SystemPermissionUtilityTest.createPermissionSetAndAssignUser(u);

        System.runAs(u) {
            System.assertEquals(true, SystemPermissionUtility.userHasPermission('PermissionsModifyAllData'));
        }

    }

    @isTest
    static void testUserHasPermission_Valid_Profile_Missing_PermissionSet_Missing() {

        // Get a basic user.
        User u = ApplicationMock.getStandardUser();

        System.runAs(u) {
            System.assertEquals(false, SystemPermissionUtility.userHasPermission('PermissionsModifyAllData'));
        }

    }

    @isTest
    static void testUserHasPermission_Valid_Profile_Success_PermissionSet_Success() {

        // Get a sys admin user.
        User u = ApplicationMock.getSysAdminUser();

        // Create PermissionSet and assign to test user
        SystemPermissionUtilityTest.createPermissionSetAndAssignUser(u);

        System.runAs(u) {
            System.assertEquals(true, SystemPermissionUtility.userHasPermission('PermissionsModifyAllData'));
        }

    }

    @isTest
    static void testUserHasPermission_Valid_Profile_Success_PermissionSet_Missing() {

        // Get a sys admin user.
        User u = ApplicationMock.getSysAdminUser();

        System.runAs(u) {
            System.assertEquals(true, SystemPermissionUtility.userHasPermission('PermissionsModifyAllData'));
        }

    }

    static void createPermissionSetAndAssignUser(User u) {

        PermissionSet ps = new PermissionSet();
        ps.Name = 'SystemPermissionUtilityTest';
        ps.Label = 'SystemPermissionUtilityTest';
        ps.PermissionsModifyAllData = true;
        ps.PermissionsAssignTopics = true;
        ps.PermissionsConnectOrgToEnvironmentHub = true;
        ps.PermissionsConvertLeads = true;
        ps.PermissionsCreateCustomizeFilters = true;
        ps.PermissionsCreateTopics = true;
        ps.PermissionsDeleteTopics = true;
        ps.PermissionsEditEvent = true;
        ps.PermissionsEditPublicDocuments = true;
        ps.PermissionsEditPublicFilters = true;
        ps.PermissionsEditPublicReports = true;
        ps.PermissionsEditPublicTemplates = true;
        ps.PermissionsEditReports = true;
        ps.PermissionsEditTask = true;
        ps.PermissionsEditTopics = true;
        ps.PermissionsImportLeads = true;
        ps.PermissionsManageCategories = true;
        ps.PermissionsManageDashboards = true;
        ps.PermissionsManageNetworks = true;
        ps.PermissionsRunReports = true;
        ps.PermissionsSolutionImport = true;
        ps.PermissionsTransferAnyEntity = true;
        ps.PermissionsTransferAnyLead = true;
        ps.PermissionsUseTeamReassignWizards = true;
        ps.PermissionsViewAllData = true;
        ps.PermissionsViewEventLogFiles = true;
        ps.PermissionsViewSetup = true;
        insert ps;

        PermissionSetAssignment psa = new PermissionSetAssignment();
        psa.AssigneeId = u.Id;
        psa.PermissionSetId = ps.Id;
        insert psa;

    }

}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .