001 // Copyright (c) 2001 Hursh Jain (http://www.mollypages.org)
002 // The Molly framework is freely distributable under the terms of an
003 // MIT-style license. For details, see the molly pages web site at:
004 // http://www.mollypages.org/. Use, modify, have fun !
005
006 package fc.web.servlet;
007
008 import java.io.*;
009 import java.net.*;
010 import java.sql.*;
011 import javax.servlet.*;
012 import javax.servlet.http.*;
013
014 import java.util.*;
015
016 import fc.io.*;
017 import fc.jdbc.*;
018 import fc.web.*;
019 import fc.util.*;
020
021 /**
022 Implements a simple jdbc based authentication filter. Uses {@link
023 JDBCSession} to check for the valid existence of the session ID. The
024 session ID itself is expected to be inside a cookie (the presence of a
025 cookie is checked by invoking {@link LoginServlet#getSIDCookie}
026 <p>
027 Uses the default database as specified in web.xml and requires
028 {@link JDBCSession} to work against that database.
029
030 @author hursh jain
031 **/
032 public class JDBCAuthFilter extends AuthFilter
033 {
034 private final static boolean dbg = false;
035 private static ConnectionMgr cmgr;
036 private static JDBCSession session;
037
038 public void init(FilterConfig config) throws ServletException
039 {
040 super.init(config);
041 //We use the default connection manager. If need be, this can
042 //be changed so that we use the connection manager to a property
043 //file specified database instead.
044 cmgr = WebApp.getConnectionMgr();
045 session = JDBCSession.getInstance();
046 }
047
048 /**
049 Checks to see if the session id (<tt>sid</tt>) exists in the cookie and it that
050 points to a valid (non-expired) database session.
051 */
052 public boolean isUserLoggedIn(HttpServletRequest req, HttpServletResponse res)
053 throws SQLException
054 {
055 Cookie c = LoginServlet.getSIDCookie(req);
056 if (c == null)
057 return false;
058
059 boolean loggedin = false;
060 Connection con = null;
061
062 try {
063 con = cmgr.getConnection();
064 loggedin = session.exists(con, c.getValue());
065 if (dbg) System.out.println("JDBCAuthFilter.isUserLoggedIn(): (2) sid points to valid session=" + loggedin);
066 }
067 finally {
068 con.close();
069 }
070
071 return loggedin;
072 }
073
074 } //~class JDBCAuthFilter
075