package com.eactive.eai.rms.common.filter;

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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
 
 
public class CrossScriptingFilter implements Filter {
	
	private static final Log logger = LogFactory.getLog(CrossScriptingFilter.class);
	
    public void init(FilterConfig filterConfig) throws ServletException {
        
    }
 
    public void destroy() {
        
    }
    
    private String getBaseUrl(HttpServletRequest request) {
    	String uri = request.getRequestURL().toString();
    	String servletPath = request.getServletPath();
    	String baseUrl = uri.replace(servletPath, "");
    	return baseUrl;
    }
    
    private boolean checkReturnUrl(HttpServletRequest request, String returnUrl) {
    	String uri = request.getRequestURL().toString();
    	String servletPath = request.getServletPath();
    	String baseUrl = uri.replace(servletPath, "");
		// 25.11.10 - weblogic https://host:443/ 문제 대응
		baseUrl = baseUrl.replace(":443", "");
        return returnUrl.startsWith(baseUrl);
    }
    
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    	HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		
    	String returnUrl = (String)request.getParameter("returnUrl");
    	if(returnUrl != null) {
    		if(!checkReturnUrl(request, returnUrl)) {
	        	response.sendError(HttpServletResponse.SC_BAD_REQUEST, "bad request. - "+returnUrl);
	            return; 
    		}
    	}
    	
    	// Web Cache Deception
    	response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    	response.setHeader("Pragma", "no-cache");
    	response.setDateHeader("Expires", 0);
        
    	chain.doFilter(new RequestWrapper(request), response);
//    	
//    	if(servletPath.startsWith("/onl/admin/common")) {
//    		System.out.println("RequestWrapper called");
//    		chain.doFilter(new RequestWrapper(request), response);
//    	}
//    	else {
//    		chain.doFilter(request, response);
//    	}
    }
 
}
