1 package be
.nikiroo
.utils
;
6 * Some utilities for cookie management.
10 public class CookieUtils
{
12 * The number of seconds for the period (we accept the current or the
13 * previous period as valid for a cookie, via "offset").
15 static public int GRACE_PERIOD
= 3600 * 1000; // between 1 and 2h
18 * Generate a new cookie value from the user (email) and an offset.
20 * You should use an offset of "0" when creating the cookie, and an offset
21 * of "0" or "-1" if required when checking for the value (the idea is to
22 * allow a cookie to persist across two timespans; if not, the cookie will
23 * be expired the very second we switch to a new timespan).
26 * the value to generate a cookie for -- you must be able to
27 * regenerate it in order to check it later
29 * the offset (should be 0 for creating, 0 then -1 if needed for
32 * @return the new cookie
34 static public String
generateCookie(String value
, int offset
) {
35 long unixTime
= (long) Math
.floor(new Date().getTime() / GRACE_PERIOD
)
37 return HashUtils
.sha512(value
+ Long
.toString(unixTime
));
41 * Check the given cookie.
44 * the value to generate a cookie for -- you must be able to
45 * regenerate it in order to check it later
47 * the cookie to validate
49 * @return TRUE if it is correct
51 static public boolean validateCookie(String value
, String cookie
) {
53 cookie
= cookie
.trim();
55 String newCookie
= generateCookie(value
, 0);
56 if (!newCookie
.equals(cookie
)) {
57 newCookie
= generateCookie(value
, -1);
60 return newCookie
.equals(cookie
);