KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > blandware > atleap > webapp > util > core > TokenUtil


1 /*
2  * Copyright 2004 Blandware (http://www.blandware.com)
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package com.blandware.atleap.webapp.util.core;
17
18 import org.apache.commons.logging.Log;
19 import org.apache.commons.logging.LogFactory;
20 import org.apache.struts.action.ActionMapping;
21 import org.apache.struts.Globals;
22 import org.apache.struts.util.TokenProcessor;
23
24 import javax.servlet.http.HttpServletRequest JavaDoc;
25 import javax.servlet.http.HttpSession JavaDoc;
26 import java.util.HashMap JavaDoc;
27 import java.util.Iterator JavaDoc;
28
29 /**
30  * <p>This class provides functionality to restrict access to actions if the http-session is over or some action is called from wrong page </p>
31  * <p/>
32  * <p><a HREF="TokenUtil.java.htm"><i>View Source</i></a></p>
33  *
34  * @author Andrey Grebnev <a HREF="mailto:andrey.grebnev@blandware.com">&lt;andrey.grebnev@blandware.com&gt;</a>
35  * @version $Revision: 1.2 $ $Date: 2006/03/16 11:09:44 $
36  */

37 public class TokenUtil {
38
39     /**
40      * Key to store HashMap in the session with key: String token scope and value: String token
41      */

42     public static final String JavaDoc TOKENS_KEY = "com.blandware.atleap.webapp.action.core.TOKENS";
43
44     /**
45      * Commons Logging instance.
46      */

47     protected transient final Log log = LogFactory.getLog(TokenUtil.class);
48
49     /**
50      * The singleton instance of this class.
51      */

52     private static TokenUtil instance = new TokenUtil();
53
54     /**
55      * Retrieves the singleton instance of this class.
56      *
57      * @return singleton instance
58      */

59     public static TokenUtil getInstance() {
60         return instance;
61     }
62
63     /**
64      * Protected constructor for TokenUtil. Use TokenUtil.getInstance()
65      * to obtain a reference to this class.
66      */

67     protected TokenUtil() {
68         super();
69     }
70
71     /**
72      * <p>Determines token scope basing on current performed action path
73      *
74      * @param request request
75      * @return the action path from the beginning to the last slash
76      */

77     protected String JavaDoc getDefaultTokenScope(HttpServletRequest JavaDoc request) {
78         ActionMapping mapping = (ActionMapping) request.getAttribute(Globals.MAPPING_KEY);
79         String JavaDoc path = mapping.getPath();
80         int slash = path.lastIndexOf("/");
81         if (slash != -1) {
82             return path.substring(0, slash + 1);
83         } else {
84             return path;
85         }
86     }
87
88     /**
89      * <p>Returns <code>true</code> if there is a transaction token stored in
90      * the user's current session in all scopes beginning from default, and the
91      * value submitted as a request parameter with this action matches it.
92      * Returns <code>false</code> under any of the following circumstances:</p>
93      * <ul>
94      * <li>No session associated with this request</li>
95      * <li>No transaction token saved in the session</li>
96      * <li>No transaction token included as a request parameter</li>
97      * <li>The included transaction token value does not match the
98      * transaction token in the user's session</li>
99      * </ul>
100      *
101      * @param request The servlet request we are processing
102      * @param reset Should we reset the token after checking it?
103      * @return whether token exists and valid
104      */

105     public synchronized boolean isTokenValid(HttpServletRequest JavaDoc request, boolean reset) {
106         return isTokenValid(null, request, reset);
107     }
108
109     /**
110      * <p>Returns <code>true</code> if there is a transaction token stored in
111      * the user's current session in all scopes beginning from default, and the
112      * value submitted as a request parameter with this action matches it.
113      * Returns <code>false</code> under any of the following circumstances:</p>
114      * <ul>
115      * <li>No session associated with this request</li>
116      * <li>No transaction token saved in the session</li>
117      * <li>No transaction token included as a request parameter</li>
118      * <li>The included transaction token value does not match the
119      * transaction token in the user's session</li>
120      * </ul>
121      *
122      * @param request The servlet request we are processing
123      * @return whether token exists and valid
124      */

125     public synchronized boolean isTokenValid(HttpServletRequest JavaDoc request) {
126         return isTokenValid(null, request, false);
127     }
128
129
130     /**
131      * <p>Returns <code>true</code> if there is a transaction token stored in
132      * the user's current session in specified scopes, and the value submitted
133      * as a request parameter with this action matches it. Returns
134      * <code>false</code> under any of the following circumstances:</p>
135      * <ul>
136      * <li>No session associated with this request</li>
137      * <li>No transaction token saved in the session</li>
138      * <li>No transaction token included as a request parameter</li>
139      * <li>The included transaction token value does not match the
140      * transaction token in the user's session</li>
141      * </ul>
142      *
143      * @param scopes array of scope names, if null check all scopes begin from default
144      * @param request The servlet request we are processing
145      * @return whether token exists and valid
146      */

147     public synchronized boolean isTokenValid(String JavaDoc[] scopes, HttpServletRequest JavaDoc request) {
148         return isTokenValid(scopes, request, false);
149     }
150
151     /**
152      * <p>Returns <code>true</code> if there is a transaction token stored in
153      * the user's current session in specified scopes, and the value submitted
154      * as a request parameter with this action matches it. Returns
155      * <code>false</code> if:</p>
156      * <ul>
157      * <li>No session associated with this request</li>
158      * <li>No transaction token saved in the session</li>
159      * <li>No transaction token included as a request parameter</li>
160      * <li>The included transaction token value does not match the
161      * transaction token in the user's session</li>
162      * </ul>
163      *
164      * @param scopes array of scope names, if null check all scopes begin from default
165      * @param request The servlet request we are processing
166      * @param reset Should we reset the token after checking it?
167      * @return whether token exists and valid
168      */

169     public synchronized boolean isTokenValid(String JavaDoc[] scopes, HttpServletRequest JavaDoc request, boolean reset) {
170         // Retrieve the current session for this request
171
HttpSession JavaDoc session = request.getSession(false);
172         if (session == null) {
173             return false;
174         }
175
176         // Retrieve the transaction token included in this request
177
String JavaDoc requestToken = request.getParameter(org.apache.struts.taglib.html.Constants.TOKEN_KEY);
178         if (requestToken == null) {
179             return false;
180         }
181
182         // Retrieve the transaction token from this session
183
String JavaDoc sessionToken = (String JavaDoc) session.getAttribute(Globals.TRANSACTION_TOKEN_KEY);
184
185         if (requestToken.equals(sessionToken)) {
186             if (reset) {
187                 resetTokenByToken(requestToken, request);
188             }
189             return true;
190         }
191
192         HashMap JavaDoc tokens = (HashMap JavaDoc) session.getAttribute(TOKENS_KEY);
193         if (tokens == null) {
194             tokens = new HashMap JavaDoc();
195         }
196
197         if (scopes != null && scopes.length > 0) {
198             //check only in specified scopes
199
for (int i = 0; i < scopes.length; i++) {
200                 String JavaDoc scope = scopes[i];
201                 String JavaDoc scopeToken = (String JavaDoc) tokens.get(scope);
202                 if (requestToken.equals(scopeToken)) {
203                     if (reset) {
204                         resetToken(scope, request);
205                     }
206                     return true;
207                 }
208             }
209         } else {
210             //check in all scopes begin from default
211

212             //check default
213
String JavaDoc defaultScope = getDefaultTokenScope(request);
214             String JavaDoc token = (String JavaDoc) tokens.get(defaultScope);
215             if (requestToken.equals(token)) {
216                 if (reset) {
217                     resetToken(defaultScope, request);
218                 }
219                 return true;
220             }
221
222             //check all
223
for (Iterator JavaDoc iterator = tokens.keySet().iterator(); iterator.hasNext();) {
224                 String JavaDoc scope = (String JavaDoc) iterator.next();
225                 if (requestToken.equals(tokens.get(scope))) {
226                     if (reset) {
227                         resetToken(scope, request);
228                     }
229                     return true;
230                 }
231             }
232         }
233
234         return false;
235     }
236
237     /**
238      * <p>Resets the saved transaction token in the user's session. This
239      * indicates that transactional token checking will not be needed
240      * on the next request that is submitted.</p>
241      *
242      * @param tokenScope name of token scope
243      * @param request The servlet request we are processing
244      */

245     public synchronized void resetToken(String JavaDoc tokenScope, HttpServletRequest JavaDoc request) {
246         HttpSession JavaDoc session = request.getSession(false);
247         if (session == null) {
248             return;
249         }
250         if (tokenScope == null) {
251             tokenScope = getDefaultTokenScope(request);
252         }
253         session.removeAttribute(Globals.TRANSACTION_TOKEN_KEY);
254         HashMap JavaDoc tokens = (HashMap JavaDoc) session.getAttribute(TOKENS_KEY);
255         if (tokens == null) {
256             tokens = new HashMap JavaDoc();
257         }
258         tokens.remove(tokenScope);
259         session.setAttribute(TOKENS_KEY, tokens);
260     }
261
262     /**
263      * <p>Resets the saved transaction token in the user's session. This
264      * indicates that transactional token checking will not be needed
265      * on the next request that is submitted.</p>
266      *
267      * @param token token value
268      * @param request The servlet request we are processing
269      */

270     protected synchronized void resetTokenByToken(String JavaDoc token, HttpServletRequest JavaDoc request) {
271         HttpSession JavaDoc session = request.getSession(false);
272         if (session == null) {
273             return;
274         }
275         session.removeAttribute(Globals.TRANSACTION_TOKEN_KEY);
276         HashMap JavaDoc tokens = (HashMap JavaDoc) session.getAttribute(TOKENS_KEY);
277         if (tokens == null) {
278             tokens = new HashMap JavaDoc();
279         }
280
281         String JavaDoc origScope = null;
282         for (Iterator JavaDoc iterator = tokens.keySet().iterator(); iterator.hasNext();) {
283             String JavaDoc scope = (String JavaDoc) iterator.next();
284             if (token.equals(tokens.get(scope))) {
285                 origScope = scope;
286                 break;
287             }
288         }
289         if (origScope != null) {
290             tokens.remove(origScope);
291             session.setAttribute(TOKENS_KEY, tokens);
292         }
293     }
294
295
296     /**
297      * <p>Resets the saved transaction token in the user's session. This
298      * indicates that transactional token checking will not be needed
299      * on the next request that is submitted.</p>
300      *
301      * @param request The servlet request we are processing
302      */

303     public synchronized void resetToken(HttpServletRequest JavaDoc request) {
304         resetToken(null, request);
305     }
306
307     /**
308      * <p>Saves a new transaction token in the user's current session, creating
309      * a new session if necessary.</p>
310      *
311      * @param tokenScope name of token scope, if null uses default
312      * @param request The servlet request we are processing
313      */

314     public synchronized void saveToken(String JavaDoc tokenScope, HttpServletRequest JavaDoc request) {
315         String JavaDoc token = TokenProcessor.getInstance().generateToken(request);
316         if (token != null) {
317             if (tokenScope == null) {
318                 tokenScope = getDefaultTokenScope(request);
319             }
320
321             HttpSession JavaDoc session = request.getSession();
322             session.setAttribute(Globals.TRANSACTION_TOKEN_KEY, token);
323
324             HashMap JavaDoc tokens = (HashMap JavaDoc) session.getAttribute(TOKENS_KEY);
325             if (tokens == null) {
326                 tokens = new HashMap JavaDoc();
327             }
328             tokens.put(tokenScope, token);
329             session.setAttribute(TOKENS_KEY, tokens);
330         }
331     }
332
333     /**
334      * <p>Saves a new transaction token in the user's current session, creating
335      * a new session if necessary.</p>
336      *
337      * @param request The servlet request we are processing
338      */

339     public synchronized void saveToken(HttpServletRequest JavaDoc request) {
340         saveToken(null, request);
341     }
342
343 }
344
Popular Tags