Forum Discussion
diptikaushikkar
Guide
Is there any way where i can avoid making this rest call to fetch roles?? Some predefined function which returns me roles??
jeffshurtliff
5 years agoBoss
diptikaushikkar wrote:Is there any way where i can avoid making this rest call to fetch roles?? Some predefined function which returns me roles??
What I do in our environment (which I tailored from the sample code in the blog post How We Built It: Atlas Custom Header by SuzieH) is store our users' roles in the user cache so I only have to perform the REST query every once in a while and then can just reference the user cache going forward.
For example:
<#-------------------- Function: getUserInfo -------------------->
<#-- This function aggregates frequently needed user information and stores it in the user cache -->
<#function getUserInfo force=false refresh=false>
<#-- Initially define the userInfo data -->
<#if refresh>
<#local userInfo = {} />
<#else>
<#local userInfo = usercache.get("userInfo")!{} />
</#if>
<#-- Check to see if there is already valid user info cached -->
<#if userInfo["valid"]?? && userInfo["valid"] && !force && !refresh>
<#return userInfo />
<#else>
<#-- Get the roles for the user -->
<#local userRoles = getUserRoles() />
<#-- Add the roles to the userInfo data -->
<#local userInfo = userInfo + {"roles": userRoles} />
<#-- SNIP -->
<#-- Add the valid flag -->
<#local userInfo = userInfo + {"valid": true} />
<#-- Return the userInfo data -->
<#return usercache.put("userInfo", userInfo) />
</#if>
</#function>
<#-------------------- Function: getUserRoles -------------------->
<#-- This function retrieves the roles associated with the user via the API -->
<#function getUserRoles>
<#if !user.anonymous>
<#return restadmin("/users/id/${user.id?c}/roles").roles.role />
<#else>
<#return [] />
</#if>
</#function>
Then it's pretty easy to just recall the user cache in other components as needed. For example:
<#-- Import the user cache functions -->
<#include "custom.macro.cache.user.ftl" />
<#-- Retrieve the userInfo data -->
<#assign userInfo = getUserInfo() />
<#-- Ensure that the user is an employee -->
<#if userInfo["roles"]?? && userInfo["roles"]?seq_contains("employee")>
<#-- Do cool stuff here -->
</#if>
Hope this helps!
Related Content
- 4 years ago