Add logged in user to context for all GSP pages

2019-07-21 22:22发布

I want to always have access to the current user domain instance in grails. I am currently using spring security. How do I go about adding current user to the context for all GSP pages? I was using request.user but thats not always populated.

For instance I want to be able to always access

${_currentUser.messages}

I know about the UserDetails service, but that is for static data. I am going to be accessing things that could be changing.

2条回答
Emotional °昔
2楼-- · 2019-07-21 22:45

Spring Security have a service class to get the current user. You can use this in a TagLib. For example:

class MyTagLib {
  def springSecurityService
  def messages = { attrs ->
    def messages = springSecurityService.currentUser.messages
    ...
  }
}
查看更多
我命由我不由天
3楼-- · 2019-07-21 23:00

Use filters, add to grails-app/conf:

package my.project

class UserFilters {

    def springSecurityService

    // add user to params object always
    def filters = {
        addUser(controller: '*', action: '*') {
            before = {
                params.myAddedUser = springSecurityService.currentUser
            }
        }
    }

    // add user to model if it is defined
    after = { Map model ->

        if(!model) model = [:]

        if ( params && params['myAddedUser']) model.myAddedUser = params.myAddedUser
    }

}

Then you will be able to retrieve it in all view/controllers. In views they will be accessible either through params or through model if model was defined in controller(any model) and in controllers it will be accessed through params object.

But be aware as it will be applied to images also. So use docs to apply filters to what you need http://grails.org/doc/2.2.1/ref/Plug-ins/filters.html

查看更多
登录 后发表回答