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{} }