Can I find out if the current user has access to a record without querying?

  • I run a query from an apex class (with sharing), and I get no results I can be sure the user doesn't have permissions (if I know otherwise that the records do exist).

    But can I get this information without running a query?

    I was thinking of the Share objects but I suppose they aren't created for manual and rule based sharing?

    Edit: Why I want no query? Here's my real scenario. In a VF page displaying multiple records, I need to show an 'Edit' button against records for which the current user has edit permissions. My question should've been clearer; sincere apologies.

    What _information_ are you trying to get? A guarantee (or count) of how many records the user has permission to view?

  • To find out if a particular user has Edit access to a record, use the UserRecordAccess object. This object is available in API version 24.0 and later. You can use SOQL to query this object to find out if the user has edit access to the record in question.

    SELECT RecordId, HasEditAccess FROM UserRecordAccess WHERE UserId = [single ID] AND RecordId = [single ID]
    

    If you want to check a batch of records you can use

    SELECT RecordId FROM UserRecordAccess WHERE UserId=:UserInfo.getUserId() AND HasReadAccess = true AND RecordId IN :allRecordIds LIMIT 200
    

    But make sure that allRecordIds is a LIST of IDs. It doesn't work if allRecordIds is a SET of IDs. I guess that's a bug.

    Also, only a maximum amount of 200 recordIds can be checked in one query.

    Interesting, I didn't know this existed. Can you add the link to the documentation for UserRecordAccess to your answer as well? Was just having a random play with it and ran into the SOQL restrictions. E.g. "INVALID_FIELD: Can select only RecordID, a Has*Access field, and MaxAccessLevel".

    I just edited the link into the answer, but I'm not sure when it will show up. Here it is, in any case: http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_objects_userrecordaccess.htm

    Thanks for the edit @metadaddy. I completely forgot the link.

    "But make sure that allRecordIds is a LIST of IDs. It doesn't work if allRecordIds is a SET of IDs. I guess that's a bug." - That line just ended my hair pulling session.

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM

Tags used