Thursday, May 13, 2010

Grails Acegi change locale after user login

In Acegi and Grails application, I would like to set the locale to the users preferred language after they log in. Here comes some steps I made:

In config file: conf/security.groovy. Add the following line:

security {
active = true
loginUserDomainClass = "User"
authorityDomainClass = "Role"
requestMapClass = "Requestmap"
security.defaultRole="ROLE_USER"

useSecurityEventListener = true
onInteractiveAuthenticationSuccessEvent = { e, appCtx ->
// handle AuthenticationSuccessEvent
def autservice = appCtx.authenticateService
def domain = autservice.userDomain()
def request = org.codehaus.groovy.grails.plugins.springsecurity.SecurityRequestHolder.getRequest()
def session = request.getSession(false)

// ok set session information for lang file - tested and ok
if (domain) {
def person = User.get(domain.id)
def userSetting = UserSetting.findByAuthor(person)
def lang = 'en'
if (session && userSetting && userSetting.language != null) {
session.lang = userSetting.language
}
}
}
}

And I have a table called userSetting which hold the user setting information, you need change it as your table information.

Ok, now we need call this function in any controller you want to change locale, maybe you'd better create a new general controller which will be extended by any controller:

// this is for locale change ...
def localeChangeCheck = {
def locale;
if (session.lang != null) {
locale = new Locale(session.lang)
RCU.getLocaleResolver(request).setLocale(request,response,locale)
}
if (locale == null) {
locale = RCU.getLocale(request)
}
}

Now you are on fly. To see running example, you can try @

www.feyasoft.com

Ok, do not forget to change properties file under your i18n folder.

No comments: