Merge commit 'b459e462a5c3447d0693674253c40bc7385a4f66'
[nikiroo-utils.git] / CookieUtils.java
CommitLineData
091c6af2
NR
1package be.nikiroo.utils;
2
3import java.util.Date;
4
5public class CookieUtils {
6 /**
7 * The number of seconds for the period (we accept the current or the
8 * previous period as valid for a cookie, via "offset").
9 */
10 static public int GRACE_PERIOD = 3600 * 1000; // between 1 and 2h
11
12 /**
13 * Generate a new cookie value from the user (email) and an offset.
14 * <p>
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).
19 *
20 * @param value
21 * the value to generate a cookie for -- you must be able to
22 * regenerate it in order to check it later
23 * @param offset
24 * the offset (should be 0 for creating, 0 then -1 if needed for
25 * checking)
26 *
27 * @return the new cookie
28 */
29 static public String generateCookie(String value, int offset) {
30 long unixTime = (long) Math.floor(new Date().getTime() / GRACE_PERIOD)
31 + offset;
32 return HashUtils.sha512(value + Long.toString(unixTime));
33 }
34
35 /**
36 * Check the given cookie.
37 *
38 * @param value
39 * the value to generate a cookie for -- you must be able to
40 * regenerate it in order to check it later
41 * @param cookie
42 * the cookie to validate
43 *
44 * @return TRUE if it is correct
45 */
46 static public boolean validateCookie(String value, String cookie) {
47 if (cookie != null)
48 cookie = cookie.trim();
49
50 String newCookie = generateCookie(value, 0);
51 if (!newCookie.equals(cookie)) {
52 newCookie = generateCookie(value, -1);
53 }
54
55 return newCookie.equals(cookie);
56 }
57}