Search code examples
salesforcesoql

How can I query records based on User permissions?


Is there a way to only return Accounts (using SOQL) that the current user has write access to?

For example, if I go to a specific Account and click the [Sharing] button I can see a list of Users (and Groups) that have access to that record. When logged in as one of those Users, I can run a SOQL statement (through a custom Controller on a Visualforce page) to retrieve the Account record. However, I want to make sure the Account record is only returned if the User has permission to write to (or edit) that record. Any ideas? Thanks in advance!


Solution

  • The way to enforce sharing is to use the with sharing keywords. If, for whatever reason, you don't want to do this, you can wrap the DML statement in a try block at catch the DMLException. Call getDmlType() on the exception object to see if the failure was related to permission. I think the status code will be System.StatusCode.INSUFFICIENT_ACCESS_OR_READONLY. Here's a somewhat complete list of status codes.