Andrea
Andrea

Reputation: 436

Play framework 2 identify users with timed out session

I have my Play Framework 2.1.2 application and I need to execute clean up instructions after the user logs out or closes the browser. Since in my other question I asked how to intercept the closing action and I was told it's not reliable to stick with javascript in browser, I would like to use its server side session timeout event to acknowledge the user is gone.

So the flow I would like to obtain is similar to this one:

  1. the user logs in
  2. its session is created
  3. the user works with my web application
  4. the user logs out / closes his browser ---> the session expires
  5. he is not on the platform anymore so I can perform some operations on the db about what he has done

I couln't find any method to override when the session expires. Can someone point me towards a solution?

Eventually another acceptable solution would be some timed event that repeatedly checks which users are not connected anymore and performs bulk operations on that pool of users no longer connected. How to achieve this?

Upvotes: 0

Views: 509

Answers (1)

Brian Porter
Brian Porter

Reputation: 529

I also needed a session timeout, so I added a timestamp (tick) to the session and updated it with each request after checking for a timeout.

Something like this:

// see if the session is expired
String previousTick = session("userTime");
if (previousTick != null && !previousTick.equals("")) {
  long previousT = Long.valueOf(previousTick);
  long currentT = new Date().getTime();
  long timeout = Long.valueOf(Play.application().configuration().getString("sessionTimeout")) * 1000 * 60;
  if ((currentT - previousT) > timeout) {
    // session expired
    session().clear();
    return null;
  } 
}
// update time in session
String tickString = Long.toString(new Date().getTime());
session("userTime", tickString);

http://www.poornerd.com/2014/04/01/how-to-implement-a-session-timeout-in-play-framework-2/

Upvotes: 2

Related Questions