I have written a basic controller class which does insert/delete/update. I wanted to validate whether I'm thinking about CRUD/FLS enforcements the right way. Also wanted to know what are the best practices for doing the same?
public with sharing class MyController {
MyCustomObj__c obj;
String[] queryFields = new String[] {'Id', 'FirstName__C', 'LastName__c'};
MyController(){
//What is the best practice for query FLS/CRUD enforcement
DescribeSObjectResult describeObject = objType.getDescribe();
Map<String, Schema.SObjectField> objectFields = describeObject.fields.getMap();
String namespace = 'curr_ns'; //temporary
for (String field : fields) {
if (!(objectFields.get(namespace + field).getDescribe().isCreateable() &&
objectFields.get(field).getDescribe().isUpdateable())){
throw CRUDException();
}
}
this.obj = [SELECT Id, FirstName__C, LastName__c from MyCustomObj__c
where Id:someId];
}
public void save(){
//Is this enough? Or Should there be checks for each field being inserted?
if(!myCustomObj.getSobjectType().getDescribe.isCreatable()){
throw CRUDException('');
}
insert obj;
}
public void delete(){
if(!myCustomObj.getSobjectType().getDescribe.isDeletable()){
throw CRUDException('');
}
delete obj;
}
public void upsert(){
if(!(myCustomObj.getSobjectType().getDescribe.isUpdateable() &&
myCustomObj.getSobjectType().getDescribe.isCreatable()){
throw CRUDException('');
}
upsert obj;
}
}
Couple of questions with the above approach:
- Do we have to enforce FLS for all queries in the controller?
- What is the best practice for enforcing FLS in queries? Currently I have to maintain a list of strings with fieldNames. When looking up the object map I need to append the namespace as well. Whenever I have to add a field to the query I need to update 2 places. Is there a cleaner approach?
- For inserts/updates, do we need to check whether all the fields being inserted our createable/updateable?
- There are some open source light weight DML managers - DML Manager Is it advisable to use these? One of the limitations of the said DML Manager is that it performs 2 queries for every DML operation which is not preferred.