Forum Discussion

elbranscomb's avatar
elbranscomb
Executive
2 years ago

Multiple roles in a custom component using userHasrole

We have a custom component that checks for the user's assigned role before allowing them to see the feature. Currently it is set to check if the user has the 'Administrator' Role.  We would like to ...
  • Drew_C's avatar
    2 years ago

    It depends on your function, but I'm betting you can't just add more to the same call. Just call it twice, like this. I've added an initialization to set that variable to false, if you're not doing it elsewhere.

    <#assign showOption = false />
    <#if user.registered>
     <#if commonFuncs.userHasRole(user.id,'Administrator') || commonFuncs.userHasRole(user.id,'Moderator')>
     <#assign messageId = env.context.message.uniqueId />
     <#assign threadId = page.context.thread.topicMessage.uniqueId />
     <#assign showOption = true />
     </#if>
    </#if>

     

    Here's another option, done in the component (sans-function) and used to display content differently based on roles. Just get all of the user's roles and then check them. Computationally, this is probably slightly less expensive, but I'm not sure.

    <#-- if the user is anonymous -->
    <#assign hasCategoryAccess = false />
    <#assign isABCXYZuser = false />
    <#if !user.anonymous>
      <#-- REST call to get the user's roles -->
      <#list restadmin("/users/id/${user.id?c}/roles").roles.role as role>
          <#-- If user is assigned these roles or is an employee -->
          <#if role.name?? && (role.name == "CategoryABC-Mod") || (role.name == "CategoryABC-User") || (role.name == "Employee")>
              <#assign hasCategoryAccess = true />
          <#-- If not employee, check if role is ABCXYZ -->
          <#elseif role.name?? && (role.name == "ABCXYZ")>
              <#assign isABCXYZuser = true />
          </#if>
      </#list>
    </#if>

     Based on the True/False results, the component displays the intended info.