package gov.va.med.authentication.kernel.ccow;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.*;

import org.apache.log4j.Logger;
import org.apache.log4j.Level;

/**
 * @author VHIT Security and Other Common Services (S&OCS)
 * @version 1.1.0.007
 */
public class ContextWriterFilter implements Filter {

	private static Logger logger = Logger.getLogger(ContextWriterFilter.class);

	public void init(FilterConfig config) throws ServletException {
	
	}

	/*
	 *  filters on the presence of the "VistaContext" request attribute
	 *  determines whether to forward to login.jsp or to skip it and
	 *  forward to LoginController servlet
	 * 
	 */
	public void doFilter(ServletRequest servletReq, ServletResponse servletResp,
			FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest req = (HttpServletRequest)servletReq;
		HttpServletResponse res = (HttpServletResponse)servletResp;
		
		// always forward to LoginController; then check its result
		chain.doFilter(servletReq, servletResp);
		// invoked after request has been processed
		// to check outcome of logging in
		doAfter(req, res);
    }

	private void doAfter(HttpServletRequest req, HttpServletResponse res) {
		// this method is called after the user was directed to login through the login.jsp form
		// or through the use of the ccow user context facility
		// if login was successful, set the user context
		
		CcowEnv ccowEnv = CcowEnv.getInstance(req);
		if (ccowEnv == null) return;  // probably a null HttpSession, ignore
		
		LoginResult result = new LoginResult(ccowEnv, req);
		
		if (!result.isSuccessful()) {
			if (logger.isEnabledFor(Level.DEBUG)) {
				logger.debug("user failed to log in . . . ");
			}	
			return;  // failed authentication
		}
		
		// authentication was successful; log the result and write user context		
		
		if (result.UsingToken()) {  // check if ccow/sso login occurred
			// do nothing
			if (logger.isEnabledFor(Level.DEBUG)) {
				logger.debug("user logged in using ccow/sso . . . ");
			}			
			return; 
		} 
		
		if (result.UsingLoginPage()) { // check if successful regular login occurred
			// write user context
			if (logger.isEnabledFor(Level.DEBUG)) {
				logger.debug("user logged in using login page and will write user context . . . ");
			}				
			ContextWriter ctxWriter = new ContextWriter(ccowEnv);
			ctxWriter.writeContext();
			return;
		} 
	}
		
	public void destroy() {
		// TODO Auto-generated method stub

	}
}
