Search code examples
spring-bootthymeleafstormpath

Use Thymeleaf to check for specific Stormpath group membership


I'm trying to determine if the logged in user is a member of a specific Stormpath group.

The following works but it is based on the wrong attribute (groups.href)

<div th:text="${#lists.contains(account.groups.href, 'https://api.stormpath.com/v1/accounts/eXaMpLe12345/groups')}" />

whereas I am trying to find (pseudo code) groups.isMemberOf('https://api.stormpath.com/v1/accounts/mYgRrOuP1234/groups')

I know how to iterate over the groups and print out all their data and I can see the href of the group that I am trying to find, but I don't know how to access it by its href.

<div th:if="${account.groups != null}">
    <ul>
       <li th:each="group : ${account.groups}" th:text="${group.href}">group details...</li>
    </ul>
</div>

Solution

  • Typically, you would want to let the server side (controller) do the heavy lifting.

    So, in the controller, you might have something like this:

    @RequestMapping("/")
    public String home(HttpServletRequest request, Model model) {
    
        Account account = AccountResolver.INSTANCE.getAccount(request);
    
        Group group = client.getResource("https://api.stormpath.com/v1/groups/qjWFpHyC5q6NdakGFCfrb", Group.class);
    
        if (account != null) {
            model.addAttribute("account", account);
            model.addAttribute("group", group);
            model.addAttribute("isMemberOfGroup", account.isMemberOfGroup(group.getHref()));
        }
    
        return "hello";
    }
    

    Then, in your thymeleaf view you could have:

        <div th:if="${account}">
            <h4 th:if="${isMemberOfGroup}" th:text="${account.fullName} + ' is a member of the ' + ${group.name} + ' group.'"></h4>
            <h4 th:text="'Account Store: ' + ${account.Directory.Name}"></h4>
            <h4 th:text="'Provider: ' + ${account.ProviderData.ProviderId}"></h4>
        </div>
    

    Result:

    enter image description here

    Full Disclosure: I am Stormapth's Java Developer Evangelist