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
042 //We use the default connection manager. If need be, this can
043 //be changed so that we use the connection manager to a property
044 //file specified database instead.
045
046 cmgr = WebApp.getInstance(appName).getConnectionMgr();
047 session = JDBCSession.getInstance();
048 }
049
050 /**
051 Checks to see if the session id (<tt>sid</tt>) exists in the cookie and it that
052 points to a valid (non-expired) database session.
053 */
054 public boolean isUserLoggedIn(HttpServletRequest req, HttpServletResponse res)
055 throws SQLException
056 {
057 Cookie c = LoginServlet.getSIDCookie(req);
058 if (c == null)
059 return false;
060
061 boolean loggedin = false;
062 Connection con = null;
063
064 try {
065 con = cmgr.getConnection();
066 loggedin = session.exists(con, c.getValue());
067 if (dbg) System.out.println("JDBCAuthFilter.isUserLoggedIn(): (2) sid points to valid session=" + loggedin);
068 }
069 finally {
070 con.close();
071 }
072
073 return loggedin;
074 }
075
076 } //~class JDBCAuthFilter
077