How to Add Security to Grails Links / Override Existing Taglib

I wanted to add a parameter to tag so I can have it optionally have it render depending on a user’s security. I wanted to say something like

I thought that since my site is already sprinkled with g:link tags, the easiest way would be to override the original taglib. However, since the TagLibs are defined as closures, I couldn’t just subclass the original ApplicationTagLib.

I have already been able to override existing tags from before by bringing the implementation into the new Tag – grails gives you a message when it sees two tags with the same name defined, but picks the one from your application, correctly assuming that you are overriding the original implementation.

I found from this thread that to get a reference to the original taglib, I had to go through Spring applicationContext. In my initial implementation, I got a reference to the original taglib, and tried to call the closure. However, that caused a StackOverFlowException.

Thanks to the Grails User list, and more precisely Ian Roberts (post here), I got help, so here is my final code (as you can see, I am using Shiro).

import org.codehaus.groovy.grails.plugins.web.taglib.*
import org.apache.shiro.SecurityUtils

class ModifiedLinkTagLib {

static namespace = "g"

def link = { attrs, body ->
   if (attrs.role=="edit" && (!SecurityUtils.subject.hasRole(EDIT_ROLE))) {
     return
   }
   def applicationTagLib = grailsApplication.mainContext.getBean('org.codehaus.groovy.grails.plugins.web.taglib.ApplicationTagLib')
   applicationTagLib.link.call(attrs, body)
  }
}

Advertisement

3 Responses to How to Add Security to Grails Links / Override Existing Taglib

  1. Doesn’t work. I still get a stackoverflow.

    I’m doing this:
    def javascript = { attrs, body ->
    def applicationTagLib = grailsApplication.mainContext.getBean(‘org.codehaus.groovy.grails.plugins.web.taglib.ApplicationTagLib’)
    return applicationTagLib.javascript.call(attrs) {
    out << "//<![CDATA["
    out << body
    out <”
    }
    }

    No idea whether this is the correct way to modify the body, but the error is clearly an infinite loop.

  2. This is awesome, thanks so much.

  3. Maybe its a grails 2 feature but you can just do:
    g.link(attrs, body)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s