Field-Level Security (FLS) in Lightning Components
Since Winter 20 release, we have Security.stripInaccessible()
method which strips the fields that the current user can’t access from query and subquery results.
Since Spring 20 release Security.stripInaccessible()
method is Generally Available.
You can use it to remove inaccessible fields from sObjects before a DML operation to avoid exceptions. You can also use the method to sanitize sObjects that have been deserialized from an untrusted source.
For example (taken from apexdocs) the user doesn’t have permission to read the ActualCost
field of a Campaign
:
List<Campaign> campaigns = new List<Campaign>{
new Campaign(Name='Campaign1', BudgetedCost=1000, ActualCost=2000),
new Campaign(Name='Campaign2', BudgetedCost=4000, ActualCost=1500)
};
insert campaigns;
// Strip fields that are not readable
SObjectAccessDecision decision = Security.stripInaccessible(
AccessType.READABLE,
[SELECT Name, BudgetedCost, ActualCost FROM Campaign]
);
// Print stripped records
for (SObject strippedCampaign : decision.getRecords()) {
System.debug(strippedCampaign); // Does not display ActualCost
}
// Print modified indexes
System.debug(decision.getModifiedIndexes());
// Print removed fields
System.debug(decision.getRemovedFields());
//Lines from output log
//|DEBUG|Campaign:{Name=Campaign1, BudgetedCost=1000, Id=701xx00000011nhAAA}
//|DEBUG|Campaign:{Name=Campaign2, BudgetedCost=4000, Id=701xx00000011niAAA}
//|DEBUG|{0, 1}
//|DEBUG|{Campaign={ActualCost}}
The ultimate goal depends on the business needs .One of below can be adopted
1.You can collect only those fields that user has and ignore the other fields user does not have access to
2.You can throw exception and asking user to reach out to admin to explicitly assign permission set
To manage CRUD FLS you can use some library to reduce code rewrite
The one that's commonly used and open source is ESAPI
https://code.google.com/archive/p/force-dot-com-esapi/wikis/GettingStarted.wiki