Sub topic 5
Writing data with as user
This chapter assumes you know basic Apex classes, SOQL and DML, profiles and permission sets, and the difference between object permissions (CRUD) and field-level security (FLS). Earlier chapters showed that Apex runs in system mode by default and that WITH USER_MODE makes a query respect the running user's access. This chapter covers the write side: DML statements that run in user mode.
Why DML needs its own enforcement
A class declared with sharing controls which records the code can see and change. It does not check whether the user may create, edit or delete the object, and it does not check whether the user may edit each field. Without extra enforcement, this code succeeds for a user whose profile has no Contact create permission:
public with sharing class UnsafeContactService {
public static void createContact(String lastName, String email) {
// System mode: no object permission or FLS check happens here.
insert new Contact(LastName = lastName, Email = email);
}
}If that method is exposed through an @AuraEnabled method or a REST endpoint, any user who can call it can write data their permissions would block in the UI. The as user keyword closes that gap.
The as user keyword
Add as user between the DML verb and the records:
public with sharing class ContactService {
public static void createContact(String lastName, String email) {
Contact c = new Contact(LastName = lastName, Email = email);
insert as user c;
}
}At runtime, Apex checks the running user's permissions before it writes anything. If a check fails, the statement throws and no records are saved.
The keyword is available on these statements:
| Statement | Example | Permission checked |
|---|---|---|
| insert | `insert as user records;` | Create on the object, edit access on each field you set |
| update | `update as user records;` | Edit on the object, edit access on each changed field |
| upsert | `upsert as user records;` | Create and edit, depending on which records are new |
| delete | `delete as user records;` | Delete on the object |
The check for fields applies to the fields your code assigns. A field with no value assigned does not trigger a field check for that record. Check the Apex Developer Guide for the current list of statements that support as user, because Salesforce has extended the syntax over several releases.
What user mode checks on a write
User mode applies three layers at once:
- Object permissions. The user needs Create, Edit or Delete on the sObject type, depending on the verb.
- Field-level security. The user needs edit access to every field your code sets. Read-only FLS is not enough.
- Sharing. The user's record access applies, even if the class is declared
without sharingor has no sharing keyword. For updates and deletes, the user must have edit or delete access to each record.
The last step in the diagram is a common source of confusion. User mode applies to the DML statement you wrote. Triggers, and the downstream effects of the save, still run in system mode. A trigger on Contact can therefore update an Account the user cannot edit, and as user does not stop it. Permission checks for work done inside a trigger have to be written in the trigger code.
Update and delete with a user mode query
A typical service method reads records in user mode, changes them and writes them back in user mode. Using both keeps the whole operation consistent:
public with sharing class AccountMaintenance {
public static void markAsProspect(Set<Id> accountIds) {
List<Account> accounts = [
SELECT Id, Type
FROM Account
WHERE Id IN :accountIds
WITH USER_MODE
];
for (Account a : accounts) {
a.Type = 'Prospect';
}
update as user accounts;
}
public static void removeAccounts(Set<Id> accountIds) {
List<Account> accounts = [
SELECT Id
FROM Account
WHERE Id IN :accountIds
WITH USER_MODE
];
delete as user accounts;
}
}The query uses WITH USER_MODE, so a user cannot even load records or fields they cannot read. The update as user statement then checks that Type is editable for this user. Reading a field and editing it are separate permissions, so a user can pass the first check and fail the second.
Database methods with AccessLevel
The Database class methods take an AccessLevel argument. Use them when you want partial success, or when you want to pass DmlOptions.
public with sharing class ContactBulkService {
public static List<Database.SaveResult> createContacts(List<Contact> contacts) {
return Database.insert(contacts, false, AccessLevel.USER_MODE);
}
}The signature is Database.insert(records, allOrNone, accessLevel). The same pattern exists for update, upsert and delete. AccessLevel.USER_MODE gives the same checks as as user. AccessLevel.SYSTEM_MODE is the explicit opposite, and later chapters cover when to use it.
The two forms differ in how they report failures:
| Form | Failure behavior |
|---|---|
| `insert as user records;` | Throws a `DmlException` for the whole statement |
| `Database.insert(records, true, AccessLevel.USER_MODE)` | All or none: throws on the first failure |
| `Database.insert(records, false, AccessLevel.USER_MODE)` | Returns one result per record. Check each result for errors |
With allOrNone set to false, the method returns normally even when a record fails. If you ignore the return value, failures disappear silently. Always loop over the results.
Handling failures
With the as user statement, wrap the call in a try/catch for DmlException:
public with sharing class ContactService {
public static void createContact(String lastName, String email) {
Contact c = new Contact(LastName = lastName, Email = email);
try {
insert as user c;
} catch (DmlException e) {
System.debug(LoggingLevel.WARN, 'Insert denied: ' + e.getMessage());
throw new AuraHandledException('You do not have permission to create this contact.');
}
}
}Two practical points apply here:
- Log the real message, show a generic one. The exception text can name objects and fields. That helps a developer, but a user-facing message should not reveal schema details the user is not allowed to see.
- Convert to the exception type your caller expects. An
@AuraEnabledmethod should throwAuraHandledExceptionso the front end receives a readable message instead of a generic "script-thrown exception".
With partial success, read the errors from each result:
public with sharing class ContactBulkService {
public static List<String> createContactsReportErrors(List<Contact> contacts) {
List<String> problems = new List<String>();
List<Database.SaveResult> results =
Database.insert(contacts, false, AccessLevel.USER_MODE);
for (Integer i = 0; i < results.size(); i++) {
if (!results[i].isSuccess()) {
for (Database.Error err : results[i].getErrors()) {
problems.add(
'Row ' + i + ': ' + err.getStatusCode() + ' - ' + err.getMessage()
);
}
}
}
return problems;
}
}The index in the result list matches the index in the input list, so contacts[i] is the record that failed. Run this against a low-privilege user in a sandbox to see exactly how your org reports object-level and field-level denials. Do not assume that every kind of permission failure appears as a per-record error.
Common mistakes
- Mixing modes in one method. A user mode query followed by a plain
updatewrites in system mode. Review each statement, not just the class. - Setting fields from code that the user cannot edit. If your method stamps a field such as a status or an internal flag,
as userfails for users without edit access to it. Either grant the permission through a permission set, or perform that one write in system mode on purpose (see the chapter on deliberate system mode). - Relying on the class sharing keyword.
with sharinghas no effect on object permissions or FLS. User mode DML applies sharing itself, so declaring the classwith sharingis still good practice but is no longer the only thing protecting the data. - Expecting triggers to be restricted. As described above, trigger code runs in system mode.
- Ignoring
Databaseresults. WithallOrNoneset tofalse, a returned list that nobody inspects hides every failure.
Quick checklist
- Does each DML statement in a user-facing method say
as useror passAccessLevel.USER_MODE? - Does each query that feeds a write use
WITH USER_MODE? - Is every
DmlExceptioncaught and turned into a message the caller can show? - With
allOrNoneset tofalse, does the code inspect everySaveResult? - Is any field that the user cannot edit set by your own code?
Exercise
A method runs update as user accounts; for a user who has Edit permission on Account and read-only FLS on Account.Type. The code sets a.Type = 'Prospect' on each record. What happens, and what two fixes are available?
Show answer
The statement throws a DmlException and no records are saved, because user mode requires edit access to every field the code assigns, and read-only FLS is not enough. One fix is to grant the user edit access to Type through a permission set. The other is to stop setting that field in user mode code, or to write it in a narrowly scoped system mode operation if the business rule allows it.
Exercise
What is the difference between Database.insert(contacts, true, AccessLevel.USER_MODE) and Database.insert(contacts, false, AccessLevel.USER_MODE) when one contact in the list fails a field-level security check?
Show answer
With allOrNone set to true, the call throws and none of the contacts are saved. With allOrNone set to false, the call returns normally. Contacts that pass are saved, and the failed contact has a SaveResult where isSuccess() is false and getErrors() describes the problem. The caller must loop over the results to notice it.
Exercise
A Contact trigger updates a related Account. A user without Edit permission on Account inserts a Contact with insert as user. Does the Account update succeed? Why?
Show answer
Yes, it can succeed. User mode applies to the DML statement in the calling code. The trigger runs in system mode, so its update to Account is not checked against the user's permissions. If the trigger must respect them, the trigger code has to use user mode itself.