Adding a variable to all views in grails

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

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

or like this:

 <g:if test="${currentUser.admin}">ADMIN</g:if> 
+4
source share
2 answers

You want to use the grails filter. Using the filter, you can specify which controllers and methods (using wildcards) you want to intercept using the methods before / after and after View.

This makes it easy to populate a new variable in the model, so it is available in the view. Here is an example that uses the acegi authenticateService plugin:

 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") } } } } } 
+11
source

You can use the session area 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 should set such a variable in the controller:

 session.currentUser = XXXXX 
+4
source

All Articles