1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.seasar.cubby.internal.util;
17
18 import static org.seasar.cubby.CubbyConstants.ATTR_TOKEN;
19
20 import java.math.BigInteger;
21 import java.util.Map;
22 import java.util.Random;
23
24 import javax.servlet.http.HttpSession;
25
26
27
28
29
30
31
32
33 public class TokenHelper {
34
35
36
37
38 private static final int TOKEN_HISTORY_SIZE = 16;
39
40
41
42
43 public static final String DEFAULT_TOKEN_NAME = "cubby.token";
44
45
46
47
48 private static final Random RANDOM = new Random();
49
50
51
52
53
54
55 public static String generateGUID() {
56 return new BigInteger(165, RANDOM).toString(36).toUpperCase();
57 }
58
59
60
61
62
63
64
65
66
67
68
69
70 @SuppressWarnings("unchecked")
71 public static Map<String, String> getTokenMap(final HttpSession session) {
72 Map<String, String> tokenMap = (Map<String, String>) session
73 .getAttribute(ATTR_TOKEN);
74 if (tokenMap == null) {
75 tokenMap = new LruHashMap<String, String>(TOKEN_HISTORY_SIZE);
76 session.setAttribute(ATTR_TOKEN, tokenMap);
77 }
78 return tokenMap;
79 }
80
81
82
83
84
85
86
87
88
89 public static void setToken(final HttpSession session, final String token) {
90 final Map<String, String> tokenMap = getTokenMap(session);
91 synchronized (tokenMap) {
92 tokenMap.put(token, null);
93 }
94 }
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110 public static boolean validateToken(final HttpSession session,
111 final String token) {
112 final Map<String, String> tokenMap = getTokenMap(session);
113 synchronized (tokenMap) {
114 final boolean success = tokenMap.containsKey(token);
115 tokenMap.remove(token);
116 return success;
117 }
118 }
119
120 }