package com.francelabs.datafari.realm;

import java.util.Hashtable;

import javax.naming.Context;

import org.apache.catalina.realm.JNDIRealm;
import org.apache.log4j.Logger;
import org.apache.manifoldcf.core.interfaces.ManifoldCFException;
import org.apache.manifoldcf.core.system.ManifoldCF;

public class DatafariJNDIRealm extends JNDIRealm {

	private static final Logger log = Logger.getLogger(DatafariJNDIRealm.class);

	@Override
	protected Hashtable<String, String> getDirectoryContextEnvironment() {
		final Hashtable<String, String> env = new Hashtable<>();
		// Configure our directory context environment.
		// Here we decrypt password and set it
		try {
			this.connectionPassword = ManifoldCF.deobfuscate(this.connectionPassword);
		} catch (final ManifoldCFException e) {
			log.error("Deobfuscate error on password ! Did you use clear text password ?", e);
		}

		env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory);
		if (connectionName != null) {
			env.put(Context.SECURITY_PRINCIPAL, connectionName);
		}
		if (connectionPassword != null) {
			env.put(Context.SECURITY_CREDENTIALS, connectionPassword);
		}
		if (connectionURL != null && connectionAttempt == 0) {
			env.put(Context.PROVIDER_URL, connectionURL);
		} else if (alternateURL != null && connectionAttempt > 0) {
			env.put(Context.PROVIDER_URL, alternateURL);
		}
		if (authentication != null) {
			env.put(Context.SECURITY_AUTHENTICATION, authentication);
		}
		if (protocol != null) {
			env.put(Context.SECURITY_PROTOCOL, protocol);
		}
		if (referrals != null) {
			env.put(Context.REFERRAL, referrals);
		}
		if (derefAliases != null) {
			env.put(JNDIRealm.DEREF_ALIASES, derefAliases);
		}
		if (connectionTimeout != null) {
			env.put("com.sun.jndi.ldap.connect.timeout", connectionTimeout);
		}
		return env;
	}

}

@@ -417,16 +417,62 @@
 .class);
+%0A%09boolean alreadyDeobfuscatedPassword = false;
 %0A%0A%09@Over
@@ -702,16 +702,55 @@
  it%0A
+%09%09if (!alreadyDeobfuscatedPassword) %7B%0A%09
 %09%09try %7B%0A
 %09%09%09t
@@ -745,16 +745,17 @@
 %09%09try %7B%0A
+%09
 %09%09%09this.
@@ -824,16 +824,57 @@
 sword);%0A
+%09%09%09%09alreadyDeobfuscatedPassword = true;%0A%09
 %09%09%7D catc
@@ -907,16 +907,17 @@
 on e) %7B%0A
+%09
 %09%09%09log.e
@@ -991,14 +991,77 @@
 rd ?
-%22, e);
+ Password to deobfuscate: %22%0A%09%09%09%09%09%09+ this.connectionPassword, e);%0A%09%09%09%7D
 %0A%09%09%7D
@@ -1313,32 +1313,33 @@
 word);%0A%09%09%7D%0A%09%09if 
+(
 (connectionURL !
@@ -1336,36 +1336,38 @@
 ctionURL != null
+)
  && 
+(
 connectionAttemp
@@ -1373,16 +1373,17 @@
 pt == 0)
+)
  %7B%0A%09%09%09en
@@ -1438,16 +1438,17 @@
 else if 
+(
 (alterna
@@ -1460,20 +1460,22 @@
  != null
+)
  && 
+(
 connecti
@@ -1488,16 +1488,17 @@
 mpt %3E 0)
+)
  %7B%0A%09%09%09en

Fix password deobfuscation DatafariRealm