1 package be
.nikiroo
.utils
;
5 public class CookieUtils
{
7 * The number of seconds for the period (we accept the current or the
8 * previous period as valid for a cookie, via "offset").
10 static public int GRACE_PERIOD
= 3600 * 1000; // between 1 and 2h
13 * Generate a new cookie value from the user (email) and an offset.
15 * You should use an offset of "0" when creating the cookie, and an offset
16 * of "0" or "-1" if required when checking for the value (the idea is to
17 * allow a cookie to persist across two timespans; if not, the cookie will
18 * be expired the very second we switch to a new timespan).
21 * the value to generate a cookie for -- you must be able to
22 * regenerate it in order to check it later
24 * the offset (should be 0 for creating, 0 then -1 if needed for
27 * @return the new cookie
29 static public String
generateCookie(String value
, int offset
) {
30 long unixTime
= (long) Math
.floor(new Date().getTime() / GRACE_PERIOD
)
32 return HashUtils
.sha512(value
+ Long
.toString(unixTime
));
36 * Check the given cookie.
39 * the value to generate a cookie for -- you must be able to
40 * regenerate it in order to check it later
42 * the cookie to validate
44 * @return TRUE if it is correct
46 static public boolean validateCookie(String value
, String cookie
) {
48 cookie
= cookie
.trim();
50 String newCookie
= generateCookie(value
, 0);
51 if (!newCookie
.equals(cookie
)) {
52 newCookie
= generateCookie(value
, -1);
55 return newCookie
.equals(cookie
);