package gov.nih.nci.nbia.security;


import gov.nih.nci.nbia.beans.security.SecurityBean;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.faces.context.FacesContext;
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.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;


/**
 * Taken from sun software forums
 *
 */
public class SecurityCheckFilter implements Filter {
    private final static String FILTER_APPLIED = "_security_filter_applied";

    final static Logger logger = Logger.getLogger(SecurityCheckFilter.class);

    public SecurityCheckFilter() { // called once. no method arguments allowed
        // here!
    }

    public void init(FilterConfig conf) throws ServletException {
    }

    public void destroy() {
    }

    public void doFilter(ServletRequest request,
    		             ServletResponse response,
    		             FilterChain chain) throws IOException, ServletException {

        HttpServletRequest hreq = (HttpServletRequest) request;
        HttpSession session = hreq.getSession();
        String referer = hreq.getHeader("referer");

        String checkforloginpage = hreq.getServletPath();

        logger.info("session:"+session.getId());
    	logger.info("request:"+hreq.getRequestURL());
    	logger.info("checkforloginpage:"+checkforloginpage);

        // dont filter login.jsp because otherwise an endless loop.

        // & only filter .jsp otherwise it will filter all images etc as well.
        if ((request.getAttribute(FILTER_APPLIED) == null) &&
            shouldApplyFilter(checkforloginpage)) {

            request.setAttribute(FILTER_APPLIED, Boolean.TRUE);

            // If the session bean is not null get the session bean property
            // username.
            boolean loggedIn = false;

            if (((SecurityBean) session.getAttribute("securityBean")) != null) {
                loggedIn = ((SecurityBean) session.getAttribute("securityBean")).getLoggedIn();
            }
            logger.info("loggedIn:"+loggedIn);
            if (!loggedIn) {
            	session.setAttribute("originalRequest", saveRequestInfo(hreq));
            	//RequestDispatcher rd = request.getRequestDispatcher("/login.jsf");
            	//rd.forward(request, response);
            	HttpServletResponse httpServletResponse = (HttpServletResponse)response;
            	httpServletResponse.sendRedirect("/ncia/login.jsf");
                return;
            }
            else if (referer.endsWith("login.jsf"))
            {
				// Change the session ID for fixing sessionID fixation problem
				HashMap<String, Object> attributes = new HashMap<String, Object>();
				// copy/save all attributes
				Enumeration<String> enames = session.getAttributeNames();
				while (enames.hasMoreElements()) {
					String name = enames.nextElement();
					if (!name.equals("JSESSIONID")) {
						attributes.put(name, session.getAttribute(name));
					}
				}
				// invalidate the session
				session.invalidate();

				// create a new session
				session = hreq.getSession(true);
				// "restore" the session values
				for (Map.Entry<String, Object> et : attributes.entrySet()) {
					session.setAttribute(et.getKey(), et.getValue());
				}
			}
		}

        // deliver request to next filter
        chain.doFilter(request, response);
    }

    private static Map<String, Object> saveRequestInfo(HttpServletRequest httpServletRequest) {
    	Map<String, Object>  originalRequestMap = new HashMap<String, Object> ();
    	originalRequestMap.put("servletPath", httpServletRequest.getServletPath());
    	originalRequestMap.put("requestURI", httpServletRequest.getRequestURI());
    	originalRequestMap.put("parameterMap", new HashMap(httpServletRequest.getParameterMap()));

    	return originalRequestMap;
    }
    /**
     * Based upon the path of the request, does security apply to the
     * path.  Mostly yes, but some pre-login screens shouldn't be secured.
     *
     * <p>
     * This isn't ideal as it ties compiled code to layout of web site.
     * Better approach would move these paths into a config file that
     * could be changed as layout changes if necessary.
     */
    private boolean shouldApplyFilter(String checkforloginpage) {
        return !checkforloginpage.endsWith("login.jsf")&&
               // These next pages are available prior to logging in,
               !checkforloginpage.endsWith("imageViewers.jsf") &&
               !checkforloginpage.endsWith("legalRules.jsf") &&
               !checkforloginpage.endsWith("welcome.jsf") &&
               !checkforloginpage.endsWith("registerMain.jsf") &&
               !checkforloginpage.endsWith("accountSupport.jsf") &&
              checkforloginpage.endsWith(".jsf");
    }
}

@@ -191,16 +191,145 @@
 l.Map;%0A%0A
+import javax.faces.application.Application;%0Aimport javax.faces.application.ViewHandler;%0Aimport javax.faces.component.UIViewRoot;%0A
 import j
@@ -361,16 +361,16 @@
 ontext;%0A
-
 import j
@@ -1502,52 +1502,11 @@
     
-String referer = hreq.getHeader(%22referer%22);%0A
+   
 %0A   
@@ -1560,17 +1560,358 @@
 Path();%0A
+        String referer = (String)session.getAttribute(%22previous%22);%0A        System.out.println(%22!!!!previous= %22+ referer);%0A        %0A        System.out.println(%22!!!!Now = %22+ checkforloginpage);%0A//        if (referer == null) %7B%0A//        %09%0A//        %09referer = %22%22;%0A//        %7D%0A        session.setAttribute(%22previous%22, checkforloginpage);%0A      
 %0A
-
         
@@ -3208,40 +3208,102 @@
     
-else if (referer.endsWith(%22login
+%0A            if (loggedIn && referer.endsWith(%22login.jsf%22) && checkforloginpage.endsWith(%22home
 .jsf
@@ -3737,24 +3737,29 @@
 %09%09%09%09%7D%0A%09%09%09%09%7D%0A
+%09%09%09%09%0A
 %09%09%09%09// inval
@@ -4126,24 +4126,447 @@
 onse);%0A    %7D
+%0A    %0A    public void refresh() %7B%0A        FacesContext context = FacesContext.getCurrentInstance();%0A        Application application = context.getApplication();%0A        ViewHandler viewHandler = application.getViewHandler();%0A        UIViewRoot viewRoot = viewHandler.createView(context, context%0A         .getViewRoot().getViewId());%0A        context.setViewRoot(viewRoot);%0A        context.renderResponse(); //Optional%0A      %7D
 %0A%0A    privat

Add previous page url to session.