package gov.va.med.esr.mvc;

import java.io.IOException;
import java.security.cert.X509Certificate;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.codec.Base64;
import org.springframework.web.filter.GenericFilterBean;

public class AuditFilter extends GenericFilterBean {
	public static final String CERTS_ATTR = "javax.servlet.request.X509Certificate";
	
	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;

		String host = request.getHeader("host");
		String Authorization = request.getHeader("Authorization");

		String username = "<Can not decode if not using Basic auth>";
		if ((Authorization != null) && Authorization.startsWith("Basic ")) {
			byte[] base64Token = Authorization.substring(6).getBytes("UTF-8");
			String token = new String(Base64.decode(base64Token), "UTF-8");

			int delim = token.indexOf(":");
			if (delim != -1) {
				username = token.substring(0, delim);
			}
		}
		X509Certificate[] certs = (X509Certificate[]) arg0.getAttribute(CERTS_ATTR);
		int certsCount = certs != null ? certs.length : 0;
		String firstCertSubjectDN = certsCount > 0 ? certs[0].getSubjectDN().getName() : "null";
		logger.info("WebService [" + request.getRequestURI() + "] accessed by HTTP host[" + host
				+ "] with HTTP Authorization[" + Authorization
				+ "] and decoded HTTP Authorization username[" + username + "] with Client Certs count[" +
				certsCount + "] and Client Certs(0) subjectDName[" + firstCertSubjectDN + "]");

		chain.doFilter(arg0, arg1);
	}

}
