Solved
Forum Discussion
luk
3 years agoBoss
Here's a more efficient way of checking if a user has at least one of the specified roles (had to rewrite it a bit as the one i use depends on other functions, so this is untested, but should make the idea clear):
<#function hasRoles roles = '' id = ''>
<#local hasroles = false />
<#if ( roles?has_content && id?has_content )>
<#-- API v2 is much more efficient checking for roles than v1 -->
<#local query = "SELECT id FROM users WHERE roles.name IN ('" + roles?replace("\\s*,\\s*", "','", 'rmi') + "') AND id = '${id}'" />
<#-- alternatively use count(*), although official best practises recommend against it, real performance results lack evidence though -->
<#-- <#local query = "SELECT count(*) FROM users WHERE roles.name IN ('" + roles?replace("\\s*,\\s*", "','", 'rmi') + "') AND id = '${id}'" /> -->
<#local response = restBuilder().admin(true).liql(query) />
<#if (response.status == 'success') && (response.data.size > 0)>
<#-- alternatively with count(*) -->
<#-- <#if (response.status == 'success') && (response.data.count > 0)> -->
<#local hasroles = true />
<#else>
<#local hasroles = false />
</#if>
</#if>
<#return hasroles>
</#function>
<#-- test it with messy whitespace -->
${hasRoles('Administrator, Moderator , Somethingelse,Whatever', '203')?c}
Note that this function just checks if a user has one of the specified (comma separated) roles, not if he/she has all of them, that could of course be added. Also, it does not return the user's roles (names), just a boolean, but code is here to be modified if that is what you need ;).