Question

I'm sure there must be a more elegant way of implementing if/else logic blocks in a GSP based on user info.

Consider the following:

<g:if test="(user logged in) && (this users post) && (post replied to)">
    Show options for this post if replied to
</g:if>
<g:elseif test="(user logged in) && (this users post)">
    show options if this users post
</g:elseif>
<g:elseif test="(user logged in)">
    show options if not this users post
</g:elseif>
<g:else>
    show options if no one is logged in
</g:else>

I'm having to use the following to determine if a user is logged in (sec.loggedInUserInfo(field: 'id') != "") I know, I hate it! I cannot use the nice Spring Security tags as they do not satisfy my requirements and I was trying to implement custom tags but would not be able to implement if/else functionality (or could I)? Any help would be much appreciated.

EDITED:

The tag I've created:

<g:isOwnerAndStatusEquals post="${post}" status="${Post.REPLIED_TO}">
     My post and is replied to
</g:isOwnerAndStatusEquals>

The Tag lib implementation:

 class AuthTagLib {

     def springSecurityService

     def isOwnerAndStatusEquals = { attrs, body ->
         def loggedInUser = springSecurityService.currentUser
         def post = attrs?.post
         def postUser = post?.user
         def postStatus = attrs?.status


         if(loggedInUser?.id == postUser?.id && job?.status?.equals(thisStatus)) {
             out << body()
         }
     }
}

This above is all fine, but I've no idea, at a high level, how to add if/else to the same tag?

Was it helpful?

Solution

The following appears to be equivalent to your GSP code and does not require you to write any custom tags:

<sec:ifLoggedIn>
  <g:if test="(this users post) && (post replied to)">
    Show options for this post if replied to
  </g:if>
  <g:elseif test="(this users post)">
    show options if this users post
  </g:elseif>
  <g:else>
    show options if not this users post
  </g:else>
</sec:ifLoggedIn>
<sec:ifNotLoggedIn>
  show options if no one is logged in
</sec:ifNotLoggedIn>

OTHER TIPS

You can use the SpringSecurityUtils inside the test criteria of the g:if tag. Like this:

<g:if test="${grails.plugin.springsecurity.SpringSecurityUtils.ifAllGranted('ROLE_MYROLE')}"

It will solve the problem since you can combine it with other test. The down-side is that the code becomes somewhat bloated. You can make it look a little bit nicer by adding an import for grails.plugin.springsecurity.SpringSecurityUtils if you use it at multiple places.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top