We're in doomed 2020 but still we have few good things in Salesforce. Now, Salesforce has provided out of the box features to enforce the security:
Use the stripInaccessible method to enforce field- and object-level data protection. This method can be used to strip the fields from query and subquery results that the user can’t access. The method can also be used to remove inaccessible sObject fields before DML operations to avoid exceptions and to sanitize sObjects that have been deserialized from an untrusted source. https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_with_security_stripInaccessible.htm
Security.SObjectAccessDecision securityDecision = Security.stripInaccessible(AccessType.READABLE, [SELECT Name, BudgetedCost, ActualCost FROM Campaign]; );
// Construct the output table
if (securityDecision.getRemovedFields().get('Campaign').contains('ActualCost')) {
for (Campaign c : securityDecision.getRecords()) {
//System.debug Output: Name, BudgetedCost
}
} else {
for (Campaign c : securityDecision.getRecords()) {
//System.debug Output: Name, BudgetedCost, ActualCost
}
}
Apart from that if you just want to query fields having current user access WITH_SECURITY KEYWORD"WITH SECURITY_ENFORCED" keyword as below: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_with_security_enforced.htm
List<Account> accounts = [SELECT Type, Name, Website FROM Account WITH_SECURITY_ENFORCED];WITH SECURITY_ENFORCED];