Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Decode the PLAY_SESSION cookie in a functional test
static Pattern sessionParser = Pattern.compile("\u0000([^:]*):([^\u0000]*)\u0000");
static final String TS_KEY = "___TS";
private Scope.Session parseSession(String sessionCookieValue) throws UnsupportedEncodingException
{
Scope.Session session = new Scope.Session();
if (sessionCookieValue != null && !sessionCookieValue.trim().equals(""))
{
String sign = sessionCookieValue.substring(0, sessionCookieValue.indexOf("-"));
String data = sessionCookieValue.substring(sessionCookieValue.indexOf("-") + 1);
if (sign.equals(Crypto.sign(data, Play.secretKey.getBytes())))
{
String sessionData = URLDecoder.decode(data, "utf-8");
Matcher matcher = sessionParser.matcher(sessionData);
while (matcher.find())
{
session.put(matcher.group(1), matcher.group(2));
}
}
if (Scope.COOKIE_EXPIRE != null)
{
// Verify that the session contains a timestamp, and that it's not expired
if (!session.contains(TS_KEY))
{
session = new Scope.Session();
}
else
{
if (Long.parseLong(session.get(TS_KEY)) < System.currentTimeMillis())
{
// Session expired
session = new Scope.Session();
}
}
session.put(TS_KEY, System.currentTimeMillis() + (Time.parseDuration(Scope.COOKIE_EXPIRE) * 1000));
}
}
else
{
// no previous cookie to restore; but we may have to set the timestamp in the new cookie
if (Scope.COOKIE_EXPIRE != null)
{
session.put(TS_KEY, System.currentTimeMillis() + (Time.parseDuration(Scope.COOKIE_EXPIRE) * 1000));
}
}
return session;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment