When working on DML operation in salesforce from Apex class developer might miss the security permissions that are assigned to different users through profiles, permission sets, sharing rules etc. This can lead to an exception. In this blog we will just see the solution for trailhead module for PD-1 certification. I will cover more details about stripInaccessible feature in a separate blog.
Get Hands-on With Field- and Object-Level Security and Safe Navigation Operator
@RestResource(urlMapping='/apexSecurityRest')
global with sharing class ApexSecurityRest {
@HttpGet
global static Contact doGet() {
Id recordId = RestContext.request.params.get('id');
Contact result;
if (recordId == null) {
throw new FunctionalException('Id parameter is required');
}
//Refactored
List<Contact> results = [SELECT id, Name, Title, Account.Name FROM Contact WHERE Id = :recordId];
SObjectAccessDecision securityDecision = Security.stripInaccessible(AccessType.READABLE, results);
if(!results.isEmpty()){
result = (Contact)securityDecision?.getRecords()[0];
result.Description = result?.Account?.Name;
}else{
throw new SecurityException('You don\'t have access to all contact fields required to use this API');
}
return result;
}
public class FunctionalException extends Exception{}
public class SecurityException extends Exception{}
}
Yea its working
LikeLike
The solution looks wrong. PFB probably the better one that the above mentioned.
@RestResource(urlMapping=’/apexSecurityRest’)
global with sharing class ApexSecurityRest {
@HttpGet
global static Contact doGet() {
Id recordId = RestContext.request.params.get(‘id’);
Contact result;
if (recordId == null) {
throw new FunctionalException(‘Id parameter is required’);
}
SObjectAccessDecision securityDecision = Security.stripInaccessible(AccessType.READABLE,[SELECT id, Name, Title, Top_Secret__c, Account.Name FROM Contact WHERE Id = :recordId]);
List results = securityDecision.getRecords();
if (!results.isEmpty()) {
result = results[0];
if (Schema.sObjectType.Contact.fields.Description.isUpdateable()){
result.Description = result.Account?.Name;
}
}
return result;
}
public class FunctionalException extends Exception{}
public class SecurityException extends Exception{}
}
LikeLiked by 1 person
The above solution which I have posted is a tested one. I tried the solution. Once it worked i have created the post.
User can also check your solution as well.
Happy Coding. 🙂
Thank you,
LikeLike