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