KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > jcorporate > expresso > core > servlet > CheckLogin


1 /* ====================================================================
2  * The Jcorporate Apache Style Software License, Version 1.2 05-07-2002
3  *
4  * Copyright (c) 1995-2002 Jcorporate Ltd. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  * notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  * notice, this list of conditions and the following disclaimer in
15  * the documentation and/or other materials provided with the
16  * distribution.
17  *
18  * 3. The end-user documentation included with the redistribution,
19  * if any, must include the following acknowledgment:
20  * "This product includes software developed by Jcorporate Ltd.
21  * (http://www.jcorporate.com/)."
22  * Alternately, this acknowledgment may appear in the software itself,
23  * if and wherever such third-party acknowledgments normally appear.
24  *
25  * 4. "Jcorporate" and product names such as "Expresso" must
26  * not be used to endorse or promote products derived from this
27  * software without prior written permission. For written permission,
28  * please contact info@jcorporate.com.
29  *
30  * 5. Products derived from this software may not be called "Expresso",
31  * or other Jcorporate product names; nor may "Expresso" or other
32  * Jcorporate product names appear in their name, without prior
33  * written permission of Jcorporate Ltd.
34  *
35  * 6. No product derived from this software may compete in the same
36  * market space, i.e. framework, without prior written permission
37  * of Jcorporate Ltd. For written permission, please contact
38  * partners@jcorporate.com.
39  *
40  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
41  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
42  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
43  * DISCLAIMED. IN NO EVENT SHALL JCORPORATE LTD OR ITS CONTRIBUTORS
44  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
45  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
46  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
47  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
48  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
49  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
50  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * ====================================================================
53  *
54  * This software consists of voluntary contributions made by many
55  * individuals on behalf of the Jcorporate Ltd. Contributions back
56  * to the project(s) are encouraged when you make modifications.
57  * Please send them to support@jcorporate.com. For more information
58  * on Jcorporate Ltd. and its products, please see
59  * <http://www.jcorporate.com/>.
60  *
61  * Portions of this software are based upon other open source
62  * products and are subject to their respective licenses.
63  */

64
65 package com.jcorporate.expresso.core.servlet;
66
67 import com.jcorporate.expresso.core.controller.NonHandleableException;
68 import com.jcorporate.expresso.core.db.DBException;
69 import com.jcorporate.expresso.core.i18n.Messages;
70 import com.jcorporate.expresso.core.jsdkapi.GenericSession;
71 import com.jcorporate.expresso.core.logging.LogException;
72 import com.jcorporate.expresso.core.misc.ConfigManager;
73 import com.jcorporate.expresso.core.misc.CookieUtil;
74 import com.jcorporate.expresso.core.misc.CurrentLogin;
75 import com.jcorporate.expresso.core.misc.StringUtil;
76 import com.jcorporate.expresso.core.misc.SystemMacros;
77 import com.jcorporate.expresso.core.registry.MutableRequestRegistry;
78 import com.jcorporate.expresso.core.security.User;
79 import org.apache.log4j.Logger;
80
81 import javax.servlet.ServletConfig JavaDoc;
82 import javax.servlet.ServletException JavaDoc;
83 import javax.servlet.http.Cookie JavaDoc;
84 import javax.servlet.http.HttpServletRequest JavaDoc;
85 import javax.servlet.http.HttpServletResponse JavaDoc;
86 import java.util.Enumeration JavaDoc;
87
88
89 /**
90  * CheckLogin accepts an HttpServletRequest and HttpServletResponse object
91  * pair, and attempts to check if the user is logged in.
92  * If not, CheckLogin tries to log the user in via a cookie from the
93  * client. If this is not possible, the user is logged in as "NONE".
94  * <p/>
95  * It has now been modified to be a Singleton Object rather than having a new
96  * object allocated with each request.
97  * <p/>
98  * Example Usage:<br />
99  * <code>CheckLogin.getInstance().checkLogin(request,response);</code><br />
100  *
101  * @author Michael Nash, Singleton Modification by Michael Rimov
102  */

103 final public class CheckLogin {
104     private static Logger log = Logger.getLogger(CheckLogin.class);
105     static CheckLogin theInstance = new CheckLogin();
106
107     /**
108      * Default Constructor.... Simply sets up the Log It should not be called
109      * anymore directly. Use getInstance() instead.
110      */

111     protected CheckLogin() {
112     }
113
114     public static CheckLogin getInstance() {
115         return theInstance;
116     }
117
118     /**
119      * see if login is legitimate
120      *
121      * @param request Standard request object
122      * @param response Standard response object
123      * @param c ServletConfig object of the calling servlet
124      * @param forceDB the db to force a login to
125      * @throws ServletException If an uncaught exception occurs
126      * @throws NonHandleableException upon fatal error
127      * @deprecated use other checkLogin(request, forcedb); 9/04 v.5.5+
128      */

129     public void checkLogin(HttpServletRequest JavaDoc request,
130                            HttpServletResponse JavaDoc response, ServletConfig JavaDoc c,
131                            String JavaDoc forceDB)
132             throws ServletException JavaDoc, NonHandleableException {
133         if (request == null) {
134             throw new ServletException JavaDoc("No request - cannot log in");
135         }
136
137         check(request, forceDB);
138     } /* CheckLogin(HttpServletRequest, HttpServletResponse, ServletConfig) */
139
140
141     /**
142      * see if login is legitimate
143      *
144      * @param request Standard request object
145      * @param forceDB the db to force a login to
146      * @throws ServletException If an uncaught exception occurs
147      * @throws NonHandleableException upon fatal error
148      */

149     public void checkLogin(HttpServletRequest JavaDoc request, String JavaDoc forceDB)
150             throws ServletException JavaDoc, NonHandleableException {
151         if (request == null) {
152             throw new ServletException JavaDoc("No request, response or ServletConfig " +
153                     "- cannot log in");
154         }
155
156         check(request, forceDB);
157     }
158
159     /**
160      * see if login is legitimate
161      *
162      * @param request Standard request object
163      * @throws ServletException If an uncaught exception occurs
164      * @throws NonHandleableException upon fatal error
165      */

166     public void checkLogin(HttpServletRequest JavaDoc request)
167             throws ServletException JavaDoc, NonHandleableException {
168         if (request == null) {
169             throw new ServletException JavaDoc("No request, response or ServletConfig " +
170                     "- cannot log in");
171         }
172
173         check(request, null);
174     }
175
176
177     /**
178      * see if login is legitimate
179      *
180      * @param request Standard request object
181      * @param response Standard response object
182      * @param c ServletConfig object of the calling servlet
183      * @throws ServletException If an uncaught exception occurs
184      * @throws NonHandleableException upon fatal error
185      * @deprecated use other checkLogin(request, forcedb); 9/04 v.5.5+
186      */

187     public void checkLogin(HttpServletRequest JavaDoc request,
188                            HttpServletResponse JavaDoc response, ServletConfig JavaDoc c)
189             throws ServletException JavaDoc, NonHandleableException {
190         if (request == null) {
191             throw new ServletException JavaDoc("No request, response or ServletConfig " +
192                     "- cannot log in");
193         }
194
195         check(request, null);
196     } /* CheckLogin(HttpServletRequest, HttpServletResponse, ServletConfig) */
197
198
199     /**
200      * see if login is legitimate
201      *
202      * @param request Standard request object
203      * @param response Standard response object
204      * @throws NonHandleableException upon fatal error
205      * @deprecated use other checkLogin(request, forcedb); 9/04 v.5.5+
206      */

207     public void checkLogin(HttpServletRequest JavaDoc request,
208                            HttpServletResponse JavaDoc response)
209             throws NonHandleableException {
210         if (request == null) {
211             if (log.isDebugEnabled()) {
212                 log.debug("No request - cannot checklogin");
213             }
214
215             return;
216         }
217
218         check(request, null);
219     } /* CheckLogin(HttpServletRequest, HttpServletResponse) */
220
221
222     /**
223      * actaully do the work of checking login
224      *
225      * @param request The servlet request object
226      * @param forceDB the db to force a login to
227      * @throws NonHandleableException upon fatal error
228      */

229     private void check(HttpServletRequest JavaDoc request,
230                        String JavaDoc forceDB)
231             throws NonHandleableException {
232         try {
233
234             if (SystemMacros.getInstance().getServerPrefix() == null) {
235                 SystemMacros.getInstance().setServerPrefix(request.getServerName()
236                         + ":" + request.getServerPort());
237             }
238
239             ConfigManager.setRequest(request);
240             Object JavaDoc o = GenericSession.getAttribute(request, "CurrentLogin");
241             String JavaDoc currentUserName = User.UNKNOWN_USER;
242             String JavaDoc currentDB = "";
243             CurrentLogin cl = null;
244
245             if (o != null) {
246                 cl = (CurrentLogin) o;
247                 currentUserName = cl.getUserName();
248                 currentDB = cl.getDBName();
249
250                 //There should never be UID zero. So if there is, treat it
251
//as user NONE.
252
if (cl.getUid() == 0) {
253                     if (log.isDebugEnabled()) {
254                         log.debug("Got uid 0 for current login: " + cl.toString());
255                     }
256                     logInAsNone(request, forceDB);
257                 }
258
259                 if (log.isDebugEnabled()) {
260                     log.debug("UserName '" + currentUserName + "', db '" +
261                             currentDB + "' in session");
262                 }
263
264                 boolean isInSesson = false;
265                 if (forceDB == null) {
266                     isInSesson = true;
267                 } else if (forceDB.equals(currentDB)) {
268                     isInSesson = true;
269                 }
270
271                 if (isInSesson) {
272                     User user = new User();
273                     user.setDBName(currentDB);
274                     user.setUid(cl.getUid());
275                     if (user.find()) {
276                         //The following line sets the particular instance of requestRegistry
277
//into the threadlocal context.
278
new MutableRequestRegistry(currentDB, user);
279                         return;
280                     }
281                 }
282             }
283
284             if (log.isDebugEnabled()) {
285                 log.debug("No login in current session (or in wrong db)");
286             }
287
288             if (loginViaContainer(request, forceDB)) {
289                 return;
290             }
291
292             if (loginViaCookie(request, forceDB)) {
293                 return;
294             }
295
296             if (log.isDebugEnabled()) {
297                 log.debug("No other login methods completed logging in as NONE");
298             }
299             logInAsNone(request, forceDB);
300         } catch (Exception JavaDoc de) {
301             de.printStackTrace();
302             log.error(de);
303             throw new NonHandleableException(de);
304         }
305     } /* init(HttpServletRequest, HttpServletResponse) */
306
307
308     /**
309      * For some reason a login session could not be established,
310      * so log the user in as the "unknown" user "NONE"
311      *
312      * @param request the servlet request object
313      * @param forceDB the data context to log into
314      */

315     public void logInAsNone(HttpServletRequest JavaDoc request, String JavaDoc forceDB)
316             throws ServletException JavaDoc {
317
318         /* If no db is established, set as default */
319         String JavaDoc dbToLogin = "default";
320
321         if (forceDB != null) {
322             dbToLogin = forceDB;
323         }
324
325         int uid = 0;
326
327         User userNone = null;
328         try {
329             userNone = new User();
330             userNone.setDataContext(dbToLogin);
331             userNone.setLoginName(User.UNKNOWN_USER);
332
333             if (userNone.find()) {
334                 uid = userNone.getUid();
335             }
336         } catch (DBException de) {
337             log.error(de);
338         }
339
340         ConfigManager.removeSession(GenericSession.getId(request));
341
342         CurrentLogin myLogin = CurrentLogin.newInstance(User.UNKNOWN_USER,
343                 request.getRemoteAddr(),
344                 dbToLogin,
345                 uid);
346         GenericSession.setAttribute(request, "CurrentLogin", myLogin);
347
348         //The following line sets the particular instance of requestRegistry
349
//into the threadlocal context.
350
new MutableRequestRegistry(dbToLogin, userNone);
351
352
353         Messages.establishLocale(request);
354     } /* logInAsNone(HttpServletRequest) */
355
356
357     /**
358      * Try to log in with a user name obtained from the container. This
359      * function assumes that the container has already authenticated the user's
360      * ID and password, thus no password checking is performed.
361      * <p/>
362      * This is intended to allow more fine-grained access control via Expresso's
363      * built-in mechanisms.
364      * <p/>
365      * If successful, return true. If not, return false.
366      *
367      * @param request The request object
368      * @param forceDB Name of default database to set
369      * @return true if successfull
370      * @throws Exception upon error
371      */

372     public boolean loginViaContainer(HttpServletRequest JavaDoc request, String JavaDoc forceDB)
373             throws Exception JavaDoc {
374
375         /* Obtain user name from container. Abort if null. */
376         String JavaDoc userName = request.getRemoteUser();
377         if (userName == null) {
378             return false;
379         }
380
381         /* If no db is established, set to default */
382         String JavaDoc dbToLogin = "default";
383
384         if (forceDB != null) {
385             dbToLogin = forceDB;
386         }
387
388         User thisUser = new User();
389         thisUser.setDataContext(dbToLogin);
390         thisUser.setLoginName(userName);
391
392         if (!thisUser.find()) {
393             return false;
394         }
395
396         if (!thisUser.getAccountStatus().equals("A")) {
397             throw new ServletException JavaDoc("Access denied: Expresso account '" + userName
398                     + "' is not active.");
399         }
400
401         if (log.isInfoEnabled()) {
402             log.info("User " + thisUser.getDisplayName() + " logged in via the container");
403         }
404
405         doSuccessfulAuth(request, userName, dbToLogin, thisUser);
406         return true;
407     }
408
409
410     /**
411      * Try to log in via the cookie from the client - if successful, return
412      * true. If not, return false
413      *
414      * @param request the servlet request object
415      * @param forceDB the data context to login to
416      * @return true if successfull
417      * @throws Exception upon error
418      */

419     public boolean loginViaCookie(HttpServletRequest JavaDoc request, String JavaDoc forceDB)
420             throws Exception JavaDoc {
421
422         /* otherwise, try the cookie */
423         String JavaDoc userName = null;
424         String JavaDoc password = null;
425         String JavaDoc db = ("");
426         Cookie JavaDoc[] cookies = request.getCookies();
427
428         if (cookies == null) {
429             if (log.isDebugEnabled()) {
430                 log.debug("No cookies present");
431             }
432
433             return false;
434         }
435         for (int i = 0; i < cookies.length; i++) {
436             String JavaDoc name = StringUtil.notNull(cookies[i].getName());
437             String JavaDoc value = StringUtil.notNull(cookies[i].getValue());
438
439             if (name.equalsIgnoreCase("UserName")) {
440                 userName = CookieUtil.cookieDecode(value);
441             } else if (name.equalsIgnoreCase("Password")) {
442                 password = CookieUtil.cookieDecode(value);
443             } else if (name.equalsIgnoreCase("db")) {
444                 db = CookieUtil.cookieDecode(value);
445             }
446         } /* for */
447
448         if (forceDB != null) {
449             db = forceDB;
450         }
451
452         /* Check if this is a valid config key */
453         String JavaDoc oneKey = null;
454         boolean keyOk = false;
455
456         if (db != null && db.length() > 0) {
457             for (Enumeration JavaDoc eck = ConfigManager.getAllConfigKeys();
458                  eck.hasMoreElements();) {
459                 oneKey = (String JavaDoc) eck.nextElement();
460
461                 if (oneKey.equals(db)) {
462                     keyOk = true;
463                     break;
464                 }
465             }
466             if (!keyOk) {
467                 log.warn("'db' in cookie with value '" + db +
468                         "' was not a valid config key.");
469
470                 return false;
471             }
472             if (log.isDebugEnabled()) {
473                 log.debug("db cookie '" + db + "'");
474             }
475         }
476
477         if (((userName == null) || (password == null) || (db == null)) ||
478                 ((userName.length() == 0) || (db.length() == 0))) {
479             if (log.isDebugEnabled()) {
480                 log.debug("Didn't get all 3 cookies");
481             }
482
483             return false;
484         }
485
486         if (userName.equalsIgnoreCase("NONE")) {
487             logInAsNone(request, db);
488         }
489
490         User myUser = new User();
491         myUser.setDataContext(db);
492         myUser.setLoginName(userName);
493
494         if (!myUser.find()) {
495             if (log.isDebugEnabled()) {
496                 log.debug("Cookie username '" + userName +
497                         "' not found in db '" + db +
498                         "'. User logged in as 'NONE'");
499             }
500
501             return false;
502         } /* if user not found */
503
504         if (!myUser.getAccountStatus().equals(User.ACTIVE_ACCOUNT_STATUS)) {
505             log.warn("Attempted login to an inactive account. Client i.p. "
506                     + request.getRemoteAddr() + " Account status: " + myUser.getAccountStatus()
507                     + " Login Name: " + userName + " passwd: " + password + " DB" + db);
508             return false; // no need to throw exception here; just do not give auth
509
}
510
511         if (!myUser.passwordEquals(StringUtil.notNull(password))) {
512             if (log.isDebugEnabled()) {
513                 log.debug("Cookie password didn't match, User logged in as 'NONE'");
514             }
515
516             return false;
517         }
518
519         if (log.isInfoEnabled()) {
520             log.info("User " + myUser.getDisplayName() + " (" + userName +
521                     ") logged in via cookie as '" + userName + "'");
522         }
523
524         doSuccessfulAuth(request, userName, db, myUser);
525         return true;
526     }
527
528     private void doSuccessfulAuth(HttpServletRequest JavaDoc request, String JavaDoc userName, String JavaDoc db, User myUser) throws ServletException JavaDoc,
529             DBException, LogException {
530
531         GenericSession.removeAttribute(request, CurrentLogin.LOGIN_KEY);
532
533         // Remove the existing login record, if there is one for this session already
534
ConfigManager.removeSession(GenericSession.getId(request));
535
536         CurrentLogin myLogin = CurrentLogin.newInstance(userName,
537                 request.getRemoteAddr(),
538                 db,
539                 myUser.getUid());
540         GenericSession.setAttribute(request, CurrentLogin.LOGIN_KEY, myLogin);
541
542         //The following line sets the particular instance of requestRegistry
543
//into the threadlocal context.
544
new MutableRequestRegistry(db, myUser);
545
546         try {
547             myUser.postLogin();
548             Messages.establishLocale(request);
549         } catch (DBException de) {
550             log.warn("Post-login processing did not complete successfully", de);
551         }
552     }
553 } /* CheckLogin */
554
Popular Tags