package de.starwit.auth.userdata;

import java.io.IOException;
import java.util.Hashtable;
import java.util.Map;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
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 org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

/**
 * TODO
 * * extract user ID from session
 * 
 * @author ztarbug
 *
 */
public class UserDataFilter implements Filter {
	
	final String ATTRIBUTE_NAME = "de.starwit.auth.userdata";
	private DirContext ctx;
	
	private Logger log = Logger.getLogger(UserDataFilter.class);
	
	public void init(FilterConfig filterConfig) throws ServletException {
	
	}

	private void getDirContext() {
		BasicConfigurator.configure();
		log.debug("UserDataFilter init");
		
		ConfigData configData = ConfigData.getInstance();
		String username = (String) configData.get("directory.username");
		String password = (String) configData.get("directory.password");
		String directoryUrl = (String) configData.get("directory.url");
		
		Hashtable<Object, Object> env = new Hashtable<Object, Object>();
		env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
		env.put(Context.PROVIDER_URL, directoryUrl);
		env.put(Context.SECURITY_CREDENTIALS, password);
		env.put(Context.SECURITY_PRINCIPAL, username);
		
		try {
			ctx = new InitialDirContext(env);
		} catch (NamingException e) {
			// panic no connection to directory!
			log.error("Could not reach user directory " + 
					directoryUrl + 
					" with error " + 
					e.getMessage() + " " + 
					e.getExplanation());
		}
	}

	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		log.debug("UserDataFilter called, check if user data is already present on session");
		HttpServletRequest request = (HttpServletRequest) req;
		HttpSession session = request.getSession();
		Object data = session.getAttribute(ATTRIBUTE_NAME);
		
		if (data == null) {
			if (request.getUserPrincipal() != null) {
				getDirContext();
				String loggedInUser = request.getUserPrincipal().getName();
	
				UserDirectoryDataRequester dataRequester = new UserDirectoryDataRequester(ctx);
				Map<String, String> userData = dataRequester.getUserData(loggedInUser);
				userData.put("alias", loggedInUser);
				session.setAttribute(ATTRIBUTE_NAME, userData);
			
				if (userData.size() > 1 ) {
					log.debug("loaded user data to session");
				} else {
					log.warn("no data for user " + loggedInUser + " could be loaded from directory - empty data set on session");
				}
			} else {
				log.warn("No logged in user found, please use UserDataFilter only on context paths with forced login.");
			}

			
		} // nothing to to do if data is present - therefore no else
		
		chain.doFilter(req, resp);
	}

	public void destroy() {
		log.debug("UserDataFilter destroyed");
	}
}

@@ -48,32 +48,58 @@
 io.IOException;%0A
+import java.util.HashMap;%0A
 import java.util
@@ -110,16 +110,16 @@
 htable;%0A
-
 import j
@@ -853,33 +853,8 @@
 a%22;%0A
-%09private DirContext ctx;%0A
 %09%0A%09p
@@ -1001,20 +1001,26 @@
 private 
-void
+DirContext
  getDirC
@@ -1030,16 +1030,34 @@
 ext() %7B%0A
+%09%09DirContext ctx;%0A
 %09%09BasicC
@@ -1687,13 +1687,14 @@
 %0A%09%09%09
-ctx =
+return
  new
@@ -1939,16 +1939,32 @@
 ion());%0A
+%09%09%09return null;%0A
 %09%09%7D%0A%09%7D%0A%0A
@@ -2333,16 +2333,80 @@
 _NAME);%0A
+%09%09Map%3CString, String%3E userData = new HashMap%3CString, String%3E();%0A
 %09%09%0A%09%09if 
@@ -2471,16 +2471,33 @@
 ) %7B%0A%09%09%09%09
+DirContext ctx = 
 getDirCo
@@ -2570,17 +2570,39 @@
 ame();%0A%09
-%0A
+%09%09%09if (ctx != null) %7B%0A%09
 %09%09%09%09User
@@ -2681,36 +2681,17 @@
 x);%0A%09%09%09%09
-Map%3CString, String%3E 
+%09
 userData
@@ -2730,24 +2730,30 @@
 gedInUser);%0A
+%09%09%09%09%7D%0A
 %09%09%09%09userData

add alias to userData from session even when connection to ldap is broken.