Sample Code With Sharing: Give Guest Users Access to Read Records
In this collection of code samples, the guest user enters a date range and then views events within that range. The guest user has read access to the records via sharing rules.
This sample Aura component displays two lightning:input components, where the user enters a start and end date to view events. The lightning:card component displays each event’s StartDateTime, EndDateTime, Subject, and Location.
This JavaScript helper creates an asynchronous request to find events within the two timestamps that the user submitted and defines the actions to take when the request completes.
1({2 doSearch : function(component, event, helper){3 var start_date = component.find("StartDate").get("v.value");4 var end_date = component.find("EndDate").get("v.value");5 var action = component.get("c.searchEvents");6 action.setParams({7 "start_date": start_date,8 "end_date": end_date9});10 action.setCallback(this, function(response){11 component.set("v.events", response.getReturnValue());12});13 $A.enqueueAction(action);14}15})
This sample Apex controller receives the call to find records from the JavaScript helper. It selects events that match these criteria:
The event’s StartDateTime is greater than the Start_Date parameter.
The event’s EndDateTime is less than the End_Date parameter.
The event’s isPrivate value is False.
The event’s isArchived value is False.
The query returns these fields for each of the events:
StartDateTime
EndDateTime
Location
Subject
Id
Because the guest users don’t need the record ID, a for loop copies all the other fields to a new Event object. Then, we add the new objects to a new list and return that list to the client.
The guest user has access to the records with sharing rules, so we define the class with the with sharing keyword.
Any system or individual on the internet can invoke @AuraEnabled methods. Protect the execution of the method by implementing procedural access checks. Make sure that the query selects only the desired records and only the required fields.
Note
1public with sharing class GuestUserEventsAuraController {23 @AuraEnabled4 public static List<Event> searchEvents(Datetime start_date, Datetime end_date){5 List<Event> results = [SELECT Event.Subject,6 Event.StartDateTime,7 Event.EndDateTime,8 Event.Location9 FROM Event 10 WHERE Event.EndDateTime<:end_date AND 11 Event.StartDateTime>:start_date AND 12 Event.isPrivate=False AND 13 Event.isArchived=False];1415 List<Event> filtered_events = new List<Event>();16 for (Event event : results) {17 Event new_event = new Event(Subject = event.Subject, 18 StartDateTime = event.StartDateTime, 19 EndDateTime = event.EndDateTime,20 Location = event.Location);21 filtered_events.add(new_event);22 }23 return filtered_events;24 }25}