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