[SalesForce] Is it possible to query the Security Permissions on a Apex Class via SOQL

I wish to know how many apex classes does a particular profile have permissions to execute. Is there any way to write a SOQL query to get this information?

We are in process of setting up a community and we don't want to give more permissions than necessary to the Community User Profile.

We also want to keep checking this via a scheduled batch job that the permissions haven't exceeded.

I know FieldLevelPermissions can be used to check on SObjects and fields, but how can I check for permissions on an Apex class?

Best Answer

You can query the SetupEntityAccess object via Apex Code. This provides three fields: ParentId, SetupEntityId, and SetupEntityType.

Basically, get the user's profile Id, then query the PermissionSet object that represents that profile:

Id permssionSetId = [SELECT Id FROM PermissionSet WHERE ProfileId = :UserInfo.getProfileId()].Id;

Finally, query the SetupEntityAccess table for all records matching:

SELECT ParentId, SetupEntityId FROM SetupEntityAccess 
WHERE ParentId = :permissionSetId AND SetupEntityType = 'ApexClass'

For each row that matches, they have access; if there is no corresponding row, then they do not have access. SetupEntityId is the ApexClass ID, so you'll probably also want to query all ApexClass records where NamespacePrefix is null.