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
006package fc.web.servlet;
007
008import java.io.*;
009import java.net.*;
010import java.sql.*;
011import javax.servlet.*;
012import javax.servlet.http.*;
013
014import java.util.*;
015
016import fc.io.*;
017import fc.jdbc.*;
018import fc.web.*;
019import fc.util.*;
020
021/** 
022Implements a simple jdbc based authentication filter. Uses {@link
023JDBCSession} to check for the valid existence of the session ID. The
024session ID itself is expected to be inside a cookie (the presence of a
025cookie is checked by invoking {@link LoginServlet#getSIDCookie}
026<p>
027Uses the default database as specified in web.xml and requires
028{@link JDBCSession} to work against that database.
029
030@author hursh jain
031**/
032public class JDBCAuthFilter extends AuthFilter 
033{
034private final   static boolean      dbg = false;
035private     static ConnectionMgr  cmgr;
036private     static JDBCSession    session;
037
038public 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/**
051Checks to see if the session id (<tt>sid</tt>) exists in the cookie and it that
052points to a valid (non-expired) database session.
053*/
054public boolean isUserLoggedIn(HttpServletRequest req, HttpServletResponse res)
055throws 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