Tuesday, August 11, 2015

[Salesforce / Apex] Can I find out if the current user has access to a record?

Yes you can!

And this is quite simple!
Query the UserRecordAccess object to have instant access to the following informations about a record and an user:

  • HasDeleteAccess: user has delete access on the record
  • HasEditAccess: user has edit access on the record
  • HasTransferAccess: user has transfer access on the record
  • HasReadAccess: user has read access on the record
  • MaxAccessLevel: picklist that tells the maximum access level on the record (None, Read, Edit, Delete, Transfer, All)
  • HasAllAccess: user can share the record

Here is a simple query (on a Case object):

List<UserRecordAccess> accessToRecord = [SELECT RecordId, MaxAccessLevel FROM UserRecordAccess WHERE UserId = :UserInfo.getUserId()  AND RecordId = '500000000000001AAA'];

On API 29.0 and earlier we have few limitations on SOQL:
  • When the running user is querying a user's access to a set of records, records that the running user does not have read access to are filtered out of the results.
  • When filtering by UserId and RecordId only, you must use SELECT RecordId and optionally one or more of the access level fields:HasReadAccess, HasEditAccess, HasDeleteAccess, HasTransferAccess, and HasAllAccess. You may include MaxAccessLevel.
  • When filtering by UserId, RecordId, and an access level field, you must use SELECT RecordId only.

Quite simple, it has been added since plaftorm version 24.0 but I discovered it few days ago!

No comments:

Post a Comment