KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > snipsnap > container > DefaultSessionService


1 /*
2  * This file is part of "SnipSnap Wiki/Weblog".
3  *
4  * Copyright (c) 2002 Stephan J. Schmidt, Matthias L. Jugel
5  * All Rights Reserved.
6  *
7  * Please visit http://snipsnap.org/ for updates and contact.
8  *
9  * --LICENSE NOTICE--
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23  * --LICENSE NOTICE--
24  */

25
26 package org.snipsnap.container;
27
28 import org.radeox.util.logging.Logger;
29 import org.snipsnap.app.Application;
30 import org.snipsnap.config.Configuration;
31 import org.snipsnap.snip.Snip;
32 import org.snipsnap.snip.SnipSpace;
33 import org.snipsnap.snip.storage.UserStorage;
34 import org.snipsnap.user.AuthenticationService;
35 import org.snipsnap.user.Digest;
36 import org.snipsnap.user.User;
37 import org.snipsnap.util.Base64;
38
39 import javax.servlet.http.Cookie JavaDoc;
40 import javax.servlet.http.HttpServletRequest JavaDoc;
41 import javax.servlet.http.HttpServletResponse JavaDoc;
42 import javax.servlet.http.HttpSession JavaDoc;
43 import java.io.BufferedReader JavaDoc;
44 import java.io.StringReader JavaDoc;
45 import java.net.MalformedURLException JavaDoc;
46 import java.net.URL JavaDoc;
47 import java.util.HashMap JavaDoc;
48 import java.util.Iterator JavaDoc;
49 import java.util.Map JavaDoc;
50
51 public class DefaultSessionService implements SessionService {
52   private final static String JavaDoc COOKIE_NAME = "SnipSnapUser";
53   private final static String JavaDoc ATT_USER = "user";
54   private final static int SECONDS_PER_YEAR = 60 * 60 * 24 * 365;
55   private final static int HTTP_UNAUTHORIZED = 401;
56
57   private Map JavaDoc authHash = new HashMap JavaDoc();
58   private Map JavaDoc robots = new HashMap JavaDoc();
59   private Map JavaDoc robotIds = new HashMap JavaDoc();
60
61   private UserStorage storage;
62   private AuthenticationService authService;
63
64   public DefaultSessionService(SnipSpace space, UserStorage storage, AuthenticationService authService) {
65     this.storage = storage;
66     this.authService = authService;
67
68     try {
69       Snip robots = space.load(Configuration.SNIPSNAP_CONFIG_ROBOTS);
70       if (robots != null) {
71         BufferedReader JavaDoc crawler = new BufferedReader JavaDoc(new StringReader JavaDoc(robots.getContent()));
72         String JavaDoc line = null;
73         int ln = 0;
74         while ((line = crawler.readLine()) != null) {
75           ln++;
76           if (line.length() > 0 && !line.startsWith("#")) {
77             try {
78               String JavaDoc id = line.substring(0, line.indexOf(' '));
79               String JavaDoc url = line.substring(line.indexOf(' ') + 1);
80               if (url.indexOf("IGNORE") != -1) {
81                 robotIds.put(id, "IGNORE");
82               } else {
83                 robotIds.put(id, url);
84               }
85             } catch (Exception JavaDoc e) {
86               Logger.warn("SessionService: " + Configuration.SNIPSNAP_CONFIG_ROBOTS + " line " + ln + ": syntax error", e);
87             }
88           }
89         }
90       }
91     } catch (Exception JavaDoc e) {
92       Logger.warn("SessionService: unable to read " + Configuration.SNIPSNAP_CONFIG_ROBOTS, e);
93     }
94   }
95
96   // update the auth hash by removing all entries and updating from the database
97
private void updateAuthHash() {
98     authHash.clear();
99     Iterator JavaDoc users = storage.storageAll().iterator();
100     while (users.hasNext()) {
101       User user = (User) users.next();
102       authHash.put(getCookieDigest(user), user);
103     }
104   }
105
106   /**
107    * Get a hexadecimal cookie digest from a user.
108    */

109   public static String JavaDoc getCookieDigest(User user) {
110     String JavaDoc tmp = user.getLogin() + user.getPasswd() + user.getLastLogin().toString();
111     return Digest.getDigest(tmp);
112   }
113
114   public void setUser(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, User user) {
115     HttpSession JavaDoc session = request.getSession();
116     session.setAttribute(ATT_USER, user);
117     setCookie(request, response, user);
118   }
119
120   /**
121    * Get user from session or cookie.
122    */

123   public User getUser(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
124     HttpSession JavaDoc session = request.getSession();
125     User user = (User) session.getAttribute(ATT_USER);
126     String JavaDoc appOid = (String JavaDoc)Application.get().getObject(Application.OID);
127     if (null != user && !appOid.equals(user.getApplication())) {
128       user = null;
129     }
130
131     if (null == user) {
132       if ("Cookie".equals(Application.get().getConfiguration().getAuth())) {
133         Cookie JavaDoc cookie = getCookie(request, COOKIE_NAME);
134         if (cookie != null) {
135           String JavaDoc auth = cookie.getValue();
136           if (!authHash.containsKey(auth)) {
137             updateAuthHash();
138           }
139
140           user = (User) authHash.get(auth);
141           if (user != null && appOid.equals(user.getApplication())) {
142             user = authService.authenticate(user.getLogin(), user.getPasswd(), AuthenticationService.ENCRYPTED);
143             if (null != user) {
144               setCookie(request, response, user);
145             }
146           } else {
147             Logger.warn("SessionService: invalid hash: " + auth);
148             user = null;
149           }
150         }
151       } else if ("Basic".equals(Application.get().getConfiguration().getAuth())) {
152         // make sure the user is authorized
153
String JavaDoc auth = request.getHeader("Authorization");
154         String JavaDoc login = "", password = "";
155
156         if (auth != null) {
157           auth = new String JavaDoc(Base64.decode(auth.substring(auth.indexOf(' ') + 1)));
158           login = auth.substring(0, auth.indexOf(':'));
159           password = auth.substring(auth.indexOf(':') + 1);
160         }
161
162         user = authService.authenticate(login, password);
163         if (user == null) {
164           response.setHeader("WWW-Authenticate", "Basic realm=\""+Application.get().getConfiguration().getName()+"\"");
165           response.setStatus(HTTP_UNAUTHORIZED);
166           return null;
167         }
168       }
169
170       if (null == user) {
171         String JavaDoc agent = request.getHeader("User-Agent");
172         Iterator JavaDoc it = robotIds.keySet().iterator();
173         while (agent != null && user == null && it.hasNext()) {
174           String JavaDoc key = (String JavaDoc) it.next();
175           if (agent.toLowerCase().indexOf(key.toLowerCase()) != -1) {
176             user = (User) robots.get(key);
177             if (null == user) {
178               user = new User(key, key, (String JavaDoc) robotIds.get(key));
179               user.setNonUser(true);
180               robots.put(key, user);
181             }
182             break;
183           }
184         }
185
186         if (user != null) {
187           Logger.debug("Found robot: " + user);
188         } else {
189           Logger.debug("User agent of unknown user: '" + agent + "'");
190           user = new User("Guest", "Guest", "");
191           user.setApplication(appOid);
192           user.setGuest(true);
193         }
194         removeCookie(request, response);
195       }
196       session.setAttribute(ATT_USER, user);
197     }
198     return user;
199   }
200
201   /**
202    * Set cookie with has of encoded user/pass and last login time.
203    */

204   public void setCookie(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, User user) {
205     String JavaDoc auth = getCookieDigest(user);
206     // @TODO find better solution by removing by value
207
updateAuthHash();
208
209     authHash.put(auth, user);
210     Cookie JavaDoc cookie = new Cookie JavaDoc(COOKIE_NAME, auth);
211     cookie.setMaxAge(SECONDS_PER_YEAR);
212     cookie.setPath(getCookiePath());
213     cookie.setComment("SnipSnap User");
214     response.addCookie(cookie);
215   }
216
217
218   public void removeCookie(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
219     Cookie JavaDoc cookie = getCookie(request, COOKIE_NAME);
220     if (cookie != null) {
221       cookie.setPath(getCookiePath());
222       cookie.setMaxAge(0);
223       response.addCookie(cookie);
224     }
225   }
226
227   private String JavaDoc getCookiePath() {
228     String JavaDoc path;
229     Configuration config = Application.get().getConfiguration();
230     try {
231       path = new URL JavaDoc(config.getUrl()).getPath();
232       if (path == null || path.length() == 0) {
233         path = "/";
234       }
235     } catch (MalformedURLException JavaDoc e) {
236       Logger.warn("Malformed URL: " + Application.get().getConfiguration().getUrl(), e);
237       path = "/";
238     }
239 // System.out.println("Cookie path: "+path);
240
return path;
241   }
242
243   /**
244    * Helper method for getUser to extract user from request/cookie/session
245    * @param request
246    * @param name
247    * @return
248    */

249   public Cookie JavaDoc getCookie(HttpServletRequest JavaDoc request, String JavaDoc name) {
250     Cookie JavaDoc cookies[] = request.getCookies();
251     for (int i = 0; cookies != null && i < cookies.length; i++) {
252       if (cookies[i].getName().equals(name)) {
253         return cookies[i];
254       }
255     }
256     return null;
257   }
258 }
259
Popular Tags