tags:

views:

89

answers:

2

I am trying to set a variable for the current user (a POJO) in all views so I can get things like the user name and check their role on every view (including the default layout). How can I setup something (e.g. currentUser) in grails so that it is accessible in every grails view like so:

<div>${currentUser.name}</div>

or like this:

<g:if test="${currentUser.admin}">ADMIN</g:if>
+1  A: 

You can use the session scope to store the variable. Your calls would change to:

<div>${session.currentUser.name}</div>

and

<g:if test="${session.currentUser.admin}">ADMIN</g:if>

And you would set the variable like so in a controller:

session.currentUser = XXXXX
Matt Lachman
+2  A: 

You want to use a grails filter. Using a filter, you can specify which controllers and methods (using wild cards) you want to intercept using before/after and afterView methods.

This makes it easy to stuff a new variable into the model so it's available in a view. Here's an example that uses the acegi plugin authenticateService:

class SecurityFilters {

    def authenticateService

    def filters = {
        all(controller:'*', action:'*') {
            after = { model ->
                def principal = authenticateService.principal()
             if (principal != null && principal != 'anonymousUser') {
        model?.loggedInUser = principal?.domainClass
                    log.debug("SecurityFilter: adding current user to model = $model")
                } else {
                    log.debug("SecurityFilter: anonymous user, model = $model")
                }
            }
        }
    }    
}
Ted Naleid