Saving User last login Time in Grails

Posted By : Pankaj Kumar Yadav | 17-Aug-2015

User Last Login in Grails

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

 

About Author

Author Image
Pankaj Kumar Yadav

Pankaj has been working as a Grails developer expertise in struts, spring, ejb, hibernate and angularjs framework.

Request for Proposal

Name is required

Comment is required

Sending message..