Skip to content

Instantly share code, notes, and snippets.

@jeffdonthemic
Last active April 18, 2024 16:52
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jeffdonthemic/f8b21e3e89e7a0e45daf to your computer and use it in GitHub Desktop.
Save jeffdonthemic/f8b21e3e89e7a0e45daf to your computer and use it in GitHub Desktop.
Simple Apex Controller with CRUD and FLS
This simple controller (without CRUD and FLS) ...
public with sharing class AccountController {
@AuraEnabled
public static List<Account> findAll() {
return [SELECT id, name, Location__Latitude__s, Location__Longitude__s
FROM Account
WHERE Location__Latitude__s != NULL AND Location__Longitude__s != NULL
LIMIT 50];
}
}
... should be rewritten like this (With CRUD and FLS):
public with sharing class AccountController {
@AuraEnabled
public static List<Account> getAccounts() {
String [] fields = new String [] {
'Id',
’Name',
’Location__Latitude__s',
’Location__Longitude__s'
};
Map<String,Schema.SObjectField> m = Schema.SObjectType.Account.fields.getMap();
for (String field : fields) {
// Check if user has permission to view field
if (!m.get(field).getDescribe().isAccessible()) {
throw new System.NoAccessException()
return null;
}
}
return [SELECT id, name, Location__Latitude__s, Location__Longitude__s
FROM Account
WHERE Location__Latitude__s != NULL AND Location__Longitude__s != NULL
LIMIT 50];
}
}
@forcemantis
Copy link

Jeff, Should we also not check Schema.SObjectType.Account.isAccessible() either on line 28 or 39?

@Doudouz-EITECH
Copy link

+1

@rbenedetti
Copy link

If the field is accessible, so is the object.

@hcerpandam
Copy link

Hi, line 36 launches an unreachable statement (return after throwing exception). Shouldn't that be out?

@lbip
Copy link

lbip commented Feb 11, 2022

is that still necessary as we now have SECURITY_ENFORCED ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment