Sample Code Without Sharing: Give Guest Users Access to Create and Read Records in the Same Transaction
In this collection of code samples, the guest user enters details to report a support issue and Apex code creates a case. An Apex method retrieves the new record and Aura components display parts of the record to the guest user after creation. The Apex code runs without sharing because we aren’t relying on object permissions and platform sharing to allow the guest user to access the record.
Aura Component: CreateCase.cmp
This sample Aura component displays several components where the user enters details about the case. After creation, the lightning:card component displays the new case’s case number and status.
This JavaScript helper creates an asynchronous request to create a case with the submitted data. When the request completes, the callback stores the case number and case status in variables used by the Aura component.
1({2 makeCase : function(component, event, helper){3 var subject = component.get("v.subject");4 var description = component.get("v.description");5 var email = component.get("v.email");6 var name = component.get("v.name");7 var reason = component.get("v.reason");8 var type = component.get("v.type");91011 var action = component.get("c.CreateCase");12 action.setParams({13 "subject": subject,14 "description": description,15 "email": email,16 "name": name,17 "reason": reason,18 "caseType": type19});20 action.setCallback(this, function(response){21 component.set("v.caseNumber", response.getReturnValue()[0]);22 component.set("v.status", response.getReturnValue()[1]);23});24 $A.enqueueAction(action);25}26})
Apex Controller: GuestUserCreateCase.apxc
This sample Apex controller creates the record, retrieves the new record, and returns the required fields from the new record to the client. Because object permissions and platform sharing aren’t used, this controller runs without sharing.
To avoid unintended exposure of record data, the CreateCase method returns only the CaseNumber and Status fields.
Any system or individual on the internet can invoke @AuraEnabled classes. Make sure that the method returns only the required fields from the new record.
Note
1public without sharing class GuestUserCreateCase {23 @AuraEnabled4 public static List<String> CreateCase(String subject, 5 String description, 6 String email,7 String name,8 String reason,9 String caseType,10 String phone){11 Case new_case = new Case(Subject=subject, 12 Description=description,13 SuppliedEmail=email,14 SuppliedName=name,15 Reason=reason,16 Type=caseType,17 SuppliedPhone=phone);18 insert new_case;1920 List<Case> results = getCase(new_case.Id);2122 List<String> response = new List<String>();23 response.add(results[0].CaseNumber);24 response.add(results[0].Status);25 return response;2627 }2829private static List<Case> getCase(String caseID)30{31 List<Case> results = [SELECT CaseNumber, Status 32 FROM Case 33 WHERE Case.Id=:caseID];34 return results;35}3637}