8

This article shows a common way to check access in Apex with a syntax like:

if (!Schema.sObjectType.Contact.fields.Name.isAccessible()){
    return '';
}

However, it is very time/space-consuming to check every single field you want to access/update manually one at a time, especially when you are working with tens of fields every time.

I know ESAPI automatically does this check and verifies access to fields but I don't see it commonly used in the community. Why?

And what is the fastest/most efficient way to ensure CRUD/FLS security of an app?

1
  • 1
    In regards to why more people don't use ESAPI, it looks like a library that would be most useful in package development, which I have never done any of myself. Just a thought. The github project does have a decent following.
    – Adrian Larson
    Jul 20, 2016 at 15:47

1 Answer 1

12

You could write a helper method for this type of functionality:

public Object flsGet(SObject record, SObjectField field)
{
    return !field.getDescribe().isAccessible() ? null : record.get(field);
}

With this reusable method, you can now just one-line the check:

Contact someRecord = [SELECT Name FROM Contact LIMIT 1];
system.debug(flsGet(someRecord, Contact.Name));

If you're really worried about performance, you could write a caching mechanism. You may do more harm than good though. I certainly haven't profiled it. Your code could be structured something like:

public class FLS
{
    public static Boolean isAccessible(SObjectType sObjectType, SObjectField field)
    {
        return getAccessibleFields(sObjectType).contains(field);
    }

    static Map<SObjectType, Set<SObjectField>> accessible;
    public static Set<SObjectField> getAccessibleFields(SObjectType sObjectType)
    {
        if (accessible == null)
            accessible = new Map<SObjectType, Set<SObjectField>>();
        if (!accessible.containsKey(sObjectType))
            accessible.put(sObjectType, getAccessibleFields(sObjectType));
        return accessible.get(sObjectType);
    }
    static Set<SObjectField> getAccessibleFields(SObjectType sObjectType)
    {
        // implementation should be straightforward
    }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .