A Fresh Approach To Implement User Level Security Using Apex Code

Starting from the Summer ’22 release, there has been a significant expansion in the Apex security model. Now, it’s possible to designate Apex database operations to run in either user or system modes. This blog will explore the process of writing Secure Apex Code using User Mode Database Operations (Summer ’22 release) in a more straightforward manner. Please note that this feature is currently in the Beta phase.

The updated Database methods include an AccessLevel parameter, enabling the execution of database operations in user mode, deviating from the default system mode. Ordinarily, Apex code operates in system mode, granting it notably higher permissions compared to the user executing the code. To bolster the security context of Apex, it’s now feasible to specify user mode access for database operations. Notably, in user mode, Field-Level Security (FLS) and object permissions of the executing user are respected, unlike in system mode. Additionally, user mode consistently applies sharing rules, whereas in system mode, they’re governed by  class sharing keywords.

User Mode and System Mode

Within SOQL queries, we can specify the operational mode using USER_MODE or SYSTEM_MODE. Here’s an example that specifically designates the user mode.

List<Account> accts = [SELECT Id, Name, Phone, BillingCity FROM Account WITH USER_MODE];

List<Contact> cons = [SELECT Id, FirstName, LastName, Account.Name FROM Contact WITH USER_MODE]; 

Performing database operations in USER or SYSTEM MODE

Database operations offer the option to specify either user or system mode. Here’s an example illustrating the insertion of a new account using user mode.

Account acct = new Account(
    Name='Ayub Ansari',

insert as USER acct;

Account acc = [SELECT Id, Name, Phone FROM Account WHERE Name ='Ayub Ansari'];

acc.Email = 'info@AyubAnsari.com

update as SYSTEM acc; 

Syntax that’s adaptable or changeable during runtime

The recently introduced AccessLevel class embodies the two modes of Apex database operation execution. Employ this class to specify the mode as either user mode or system mode. Utilize these updated methods for conducting DML and query operations:

  • Database.query methods
  • Search.query methods
  • Database DML methods (insert, update, upsert, merge, delete, undelete, and convertLead)

Here are a few examples:

Account acc = Database.query('SELECT Id, Name FROM Account WHERE Name = 'Ayub Ansari'', AccessLevel.USER_MODE);

//Database.insert example

Database.insert(new Account(Name = 'Ayub Ansari'),AccessLevel.USER_MODE);

Click here Check out the release notes for Secure Apex Code leveraging user mode database operations.