package +zoccolo+.web.filter;

import +zoccolo+.web.servlet.HttpRequestWrapper;

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.log4j.Logger;

public class CrossSiteScriptingFilter implements Filter {

	static Logger log = Logger.getLogger(CrossSiteScriptingFilter.class);
	
	@SuppressWarnings("unused")
	private FilterConfig filterConfig;
	
	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		this.filterConfig = null;
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		String sessionid = ((HttpServletRequest) request).getSession().getId();
		// be careful overwriting: JSESSIONID may have been set with other flags
		((HttpServletResponse) response).setHeader("SET-COOKIE", "JSESSIONID=" + sessionid + ";Path=/; HttpOnly");
		
		chain.doFilter(new HttpRequestWrapper((HttpServletRequest)request), response);	
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;	
		log.info("CrossSiteScriptingFilter correctly initialized.");
	}

	/* screwdriver_knife */

}

