Saving User last login Time in Grails
Posted By : Pankaj Kumar Yadav | 17-Aug-2015

Hi All,
It is very simple to save user's login time into database. Just follow the bellow steps -
First of all we need to add a field lastLoginTime (to save user login time) in User domain
Class User{
.....
.....
Date lastLoginTime
......
}
Now we need to enable springsecurity events by setting grails.plugin.springsecurity.useSecurityEventListener to true.
Now add the following codes in Config.groovy
grails.plugin.springsecurity.useSecurityEventListener = true // enable events
grails.plugin.springsecurity.onInteractiveAuthenticationSuccessEvent = { e, appCtx ->
User.withTransaction {
def user = User.findById(appCtx.springSecurityService.principal.id)
if(!user.isAttached())
user.attach()
user.lastLoginTime = new Date() // update login time
user.save(flush: true, failOnError: true)
}
}
The above code will update user lastLoginTime field in DB every time whenever user logged.
THANKS
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Pankaj Kumar Yadav
Pankaj has been working as a Grails developer expertise in struts, spring, ejb, hibernate and angularjs framework.