In the Summer’22 release, Salesforce introduced the new Apex security feature – User mode.
Why do we need user mode?
By default, Salesforce runs all apex code in the system mode. The system mode ignores user permissions. It’s possible to check access using methods (stripInaccessible, isAccessible, etc) or include WITH SECURITY_ENFORCED in SOQL. But all these approaches have downsides.
How does user mode work?
You can specify user mode for database operations to enhance the security context of Apex. Unlike system mode, user mode uses Field-level security and object permissions of the running user. Also, user mode always applies sharing rules (system mode controls it by using class sharing keywords).
How to use user mode?
In SOQL, you can choose the mode of the operation by using WITH USER_MODE or WITH SYSTEM_MODE.
List leads = [SELECT Id FROM Lead WITH USER_MODE];
Database operations can specify user mode by adding “as user”.
Account newAccount = new Account(Name = 'New Account'); insert as user newAccount;
The new AccessLevel class helps to define the two modes in which Apex runs database operations: user or system mode. See examples below of how to use these new overloaded methods to perform DML and query operations:
Database.query
String searchQuery = 'SELECT Id FROM Lead LIMIT 10'; List leads = Database.query(searchQuery, AccessLevel.USER_MODE);
Search.query
String searchquery = 'FIND\'Edge*\'IN ALL FIELDS RETURNING Account(id,name),Contact, Lead'; List<List> searchList = Search.query(searchquery, AccessLevel.USER_MODE);
Database DML methods (insert, update, upsert, merge, delete, undelete, and convertLead)
List newAccounts = new List{new Account(Name = 'New Account')}; List sr = Database.insert(newAccounts, AccessLevel.USER_MODE);