[SalesForce] Retrieving permission sets

Does the metadata api returns the object permissions in the permissions sets? I want to retrieve the object permissions for standard as well as custom objects.

Best Answer

USING SOQL

You can fetch this information by Querying 3 objects - PermissionSet, PermissionSetAssignment and ObjectPermissions.

SELECT Id,IsOwnedByProfile,Label FROM PermissionSet
WHERE IsOwnedByProfile = TRUE

The above query will return the permission set that you have created and not owned by profile.Then you can use below query to get the object permissions -

SELECT Assignee.Name, PermissionSet.Id, PermissionSet.isOwnedByProfile, PermissionSet.Profile.Name, PermissionSet.Label
FROM PermissionSetAssignment WHERE PermissionSetId
IN (SELECT ParentId FROM ObjectPermissions
WHERE SObjectType = 'XYZ__c' AND
PermissionsCreate = true)

Reference - https://developer.salesforce.com/blogs/engineering/2012/06/using-soql-to-determine-your-users-permissions-2.html

USING METADATA

You can use metadata API to retrieve the object permissions.If you check metadata developer guide and search for PermissionSet , you can easily see that this type returns multiple parameters from API v29.0 onwards like-applicationVisibilities,classAccesses, fieldPermissions,ObjectPermissions, etc.

Specifically talking about ObjectPermissions, the return type is PermissionSetObjectPermissions[] (List of PermissionSetObjectPermissions). Now this list has all the information that you require like - allowCreate, allowDelete, allowEdit, allowRead, modifyAllRecords,object, viewAllRecords. Out of this Object is a string type while rest are all boolean corresponding to the permissions on object.

Reference - https://resources.docs.salesforce.com/sfdc/pdf/api_meta.pdf (Metadata API v.34 Summer'15 page 416)

Now if you are looking for developing this using Apex, kindly refer this package - https://github.com/financialforcedev/apex-mdapi
and this example - https://github.com/financialforcedev/apex-mdapi/blob/master/apex-mdapi/src/classes/MetadataServiceExamples.cls#L234