+ Start a Discussion
Sohan ShirodkarSohan Shirodkar 

Validate CRUD permission before SOQL/DML operation

PMD extension in VS Code is reporting this issue:
Validate CRUD permission before SOQL/DML operation

I can handle this by using something of this sort:
if (Schema.sObjectType.Contact.fields.Email.isAccessible()) {
   Contact c = [SELECT Email FROM Contact WHERE Id= :Id];
}

However my codebase is huge and I cannot repeat this snippet everywhere. Also, the number of fields to be checked, similar to Email field, is large.

Hence, I want to write a generic utility method for this which will take as argumet the object name and a set of field names. 
public static Boolean hasFieldReadAccess(String objectName, Set<String> fields){
        Schema.SObjectType obj = Schema.getGlobalDescribe().get(objectName);
        for(String field: fields){
            Schema.SObjectField sObjectField = obj.getDescribe().fields.getMap().get(field);
            if(!sObjectField.getDescribe().isAccessible()){
                return false;
            }
        }
        return true;
    }
However, when I call this method at the lin where PMD reports issue, it does not show it as resolved. Even if I directly include the following line, the issue is not resolved:
if(Schema.getGlobalDescribe().get('Contact').getDescribe().fields.getMap().get('Email').getDescribe().isAccessible()){
 //SOQL here
}

Any idea what is going wrong here? Does PMD only recognize the first code snippet for resolving the issue?

 
RahulForceRahulForce
Hey Sohan,

You're right, PMD will not throw error only if you follow the below syntax:-
if(Contact.SObjectType.getDescribe().isAccessible() && Schema.SObjectType.Contact.fields.Email.isAccessible()) {
    Contact c = [SELECT Email FROM Contact WHERE Id=:Id];
}
However, the good news is you don't have to check for permissions in the Spring 20 release. You can handle it in the query itself like:- 
Contact c = [SELECT Email FROM Contact WHERE Id=:Id WITH SECURITY_ENFORCED];
And it will work in dynamic queries as well 😊
Have a look at this link for more info:- Validate CRUD permission before SOQL/DML operation ? Well...that's History 😎 (https://www.sfdcstop.com/2020/03/validate-crud-permission-before-soqldml.html)