Get Hands-on With Field- and Object-Level Security and Safe Navigation Operator

Hands-on challenge solution for Platform Developer I Certification Maintenance (Winter ‘21)


@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, Top_Secret__c, 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{}
}

Note: Use the code snippet only for reference. Do not copy and paste it just for an example for complete challenges. 

Comments

  1. @RestResource(urlMapping='/apexSecurityRest')
    global with sharing class ApexSecurityRest {
    @HttpGet
    global static Contact doGet() {
    Id recordId = RestContext.request.params?.get('id');
    Contact result;

    List results = [SELECT id, Name, Title, Top_Secret__c, Account.Name FROM Contact WHERE Id = : recordId];
    SObjectAccessDecision securityDecision = Security.stripInaccessible(AccessType.READABLE, results);
    if (!results.isEmpty()) {
    result = results[0];
    result.Description = result?.Account?.Name;

    }

    return result;
    }
    public class FunctionalException extends Exception{}
    public class SecurityException extends Exception{}
    }

    ReplyDelete

Post a Comment

Popular posts from this blog

Adding a red asterisk to required fields using label in LWC

The Developer Console didn't set the DEVELOPER_LOG trace flag on your user. Having an active trace flag triggers debug logging. You have 1,978 MB of the maximum 1,000 MB of debug logs. Before you can edit trace flags, delete some debug logs.

Salesforce: Serial and Parallel Approval