views:

642

answers:

1

I'm using the layout support (sitemesh) in Grails which works fine. I'd like to adjust my layout to have it depend on whether or not a user is logged in or not.

My grails-app/views/layouts/main.gsp contains the following code:

<g:if test="${user}">
  Username: ${user.username}
</g:if>

However, it appears as if the layout-GSP:s are unable to access the model and hence the user variable (I get a "No session" exception when trying). What would be the recommended way to make my layout depend on whether or not a user is logged in or not?

Thanks in advance!

+6  A: 

I would suggest to use either the request or the session scope for that purpose. Probably the most DRY way is to populate the scope is a filter. For example in the file grails-app/conf/SecurityFilters.groovy (you'll need to create it):

class SecurityFilters {

    def filters = {
        populateCurrentUser(controller: '*', action: '*') {
            before = {
                 request.user = User.get(session.userId)
            }
        }
    }
}

The example assumes that you store the id of the current user in the session attribute "userId" and that you have a Domain class "User". Using it in the layout is as simple as this:

<g:if test="${request.user}">
   Current User: ${request.user.username}
</g:if>
Siegfried Puchbauer