Monday 1 October 2007

Saving the last time login with Acegi Security

This time, I'm going to explain how to save the last login time of user with Acegi Security for Spring.
It's really easy, due to Acegi publishes an autentication event in the Spring ApplicationContext (documentation about publish/suscribe events).

I have to create a simple class that implements ApplicationListener.

public class LastLoginListener implements ApplicationListener {

private UserManager userManager;

// getter and setter ...

public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof AbstractAuthenticationEvent) {

if (event instanceof AbstractAuthenticationFailureEvent) {
// log or similar
}

if ( event instanceof AuthenticationSuccessEvent ){
AuthenticationSuccessEvent authenticationSuccessEvent = ( AuthenticationSuccessEvent ) event;
String username = authenticationSuccessEvent.getAuthentication().getName();
User user = userManager.getUserByUsername(username);
user.setLastLogin(new Date());
userManager.saveUser(user);
}

}
}

}


In the method "onApplicationEvent" I listen the event AbstractAuthenticationEvent, that Acegi publishes.
Next, I update the last login time, with the userManager.

The last step is setup my LastLoginListener in security.xml with the other Acegi beans.

<bean id="lastLoginListener" class="net.dahernan.common.security.LastLoginListener">
<property name="userManager" ref="userManager"/>
</bean>