Created
April 1, 2014 19:36
-
-
Save poornerd/9921407 to your computer and use it in GitHub Desktop.
Implementing a session timeout in Play Framework 2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* How to implement a session timeout in Play Framework 2 | |
* http://www.poornerd.com/2014/04/01/how-to-implement-a-session-timeout-in-play-framework-2/ | |
* | |
*/ | |
public class Secured extends Security.Authenticator { | |
public static final String UNAUTHENTICATED = "unauthenticated"; | |
public static User getLoggedInUser() { | |
if (session("userId") == null) | |
return null; | |
return User.findById(Long.parseLong(session("userId"))); | |
} | |
public static String getLoggedInUsername() { | |
if (session("userId") == null) | |
return null; | |
return User.findById(Long.parseLong(session("userId"))).getUsername(); | |
} | |
@Override | |
public String getUsername(Http.Context ctx) { | |
// see if user is logged in | |
if (session("userId") == null) | |
return null; | |
// 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); | |
return User.findById(Long.parseLong(session("userId"))).getUsername(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment