Search code examples
salesforceapexcheckmarx

FLS Create for Saleforce Object


Is there a way to apply FLS Create check - Schema.sObjectType.Account.fields.Name.isCreateable() to the following?

public static Account createAccount() {
    return new Account(
        Name = 'Test',
        OwnerId = UserInfo.getUserId()
    );
}

Wondering if there is a way to apply without re-writing to the following:

public static Account createAccount() {
    Account a = new Account();
    if (Schema.sObjectType.Account.fields.Name.isCreateable()) {
        a.Name = 'Test';
    }
    if (Schema.sObjectType.Account.fields.OwnerId.isCreateable()) {
        a.OwnerId = UserInfo.getUserId();
    }
    insert a;
}

Solution

  • You can create a generic method that can iterate on each field to check for the FLS.

    • if access available then retain
    • if access not available then remove the particular field from the object instance.

    I Have created a Generic Method to truncate the non-writable fields as follow:

        public static List<SObject> truncateNotWriteableFields(List<SObject> listSObject){
    
        Set<String> readOnlyFields = new Set<String>();
        List<SObject> listSObjectNew = new List<SObject>();
        if(listSObject.size() < 1){
            return listSObjectNew;
        }
        Schema.SObjectType sObjType = listSObject.getSObjectType();
    
        for(SObjectField field : sObjType.getDescribe().fields.getMap().values()){
            if(field.getDescribe().isAccessible() && !field.getDescribe().isUpdateable() && !field.getDescribe().isCreateable()){
                readOnlyFields.add(String.valueOf(field));
            }
        }
        readOnlyFields.remove('Id'); // avoid removal in update
        for(SObject obj : listSObject){
            Map<String, Object> objMap = (Map<String, Object>) JSON.deserializeUntyped( JSON.serialize( obj ) );
            objMap.keySet().removeAll(readOnlyFields);
            SObject objWithoutNotWritableFields = (SObject) JSON.deserialize( JSON.serialize( objMap ), SObject.class );
            system.debug('objWithoutNotWritableFields=>'+objWithoutNotWritableFields);
            listSObjectNew.add(objWithoutNotWritableFields);
        }
        
        return listSObjectNew;
    }