/*
 * Copyright
 *   2008 axYus - www.axyus.com
 *   2008 C.Marchand - christophe.marchand@axyus.com
 *   2008 C.Bosquet - charles.bosquet@axyus.com
 *
 * This file is part of XEMELIOS.
 *
 * XEMELIOS is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * XEMELIOS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with XEMELIOS; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package fr.gouv.finances.cp.xemelios.auth.ldap;

import fr.gouv.finances.dgfip.xemelios.auth.AuthEngine;
import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser.SimpleXemeliosUserImpl;
import fr.gouv.finances.dgfip.xemelios.data.DataConfigurationException;
import fr.gouv.finances.dgfip.xemelios.data.DataLayerManager;
import java.util.Collection;
import java.util.HashSet;
import java.util.Hashtable;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

/**
 * @author CHM
 * @author CBO
 */
public class LdapAuthEngineImpl implements AuthEngine {

    private String baseUrl = null;
    private String userDN = null;
    private String readAccessDN = null;
    private String writeAccessDN = null;

    public LdapAuthEngineImpl() throws DataConfigurationException {
        this.baseUrl = DataLayerManager.getImplementation().getParameterValue("auth.ldap.baseUrl");
        this.userDN = DataLayerManager.getImplementation().getParameterValue("auth.ldap.userDN");
        this.readAccessDN = DataLayerManager.getImplementation().getParameterValue("auth.ldap.readAccessDN");
        this.writeAccessDN = DataLayerManager.getImplementation().getParameterValue("auth.ldap.writeAccessDN");
    }

    public boolean isLoginRequired() {
        return true;
    }

    public boolean isPasswordRequired() {
        return true;
    }

    public XemeliosUser createUser(String login, String password) {
        String bindDN = userDN.replaceAll("%LOGIN%", login.toUpperCase());
        String readDN = readAccessDN == null ? null : readAccessDN.replaceAll("%LOGIN%", login.toUpperCase());
        String writeDN = writeAccessDN == null ? null : writeAccessDN.replaceAll("%LOGIN%", login.toUpperCase());

        Hashtable<String, String> ht = new Hashtable<String, String>();
        ht.put(DirContext.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        ht.put(DirContext.SECURITY_AUTHENTICATION, "simple");
        ht.put(DirContext.SECURITY_PRINCIPAL, bindDN);
        ht.put(DirContext.SECURITY_CREDENTIALS, password);
        ht.put(DirContext.PROVIDER_URL, baseUrl);
        ht.put("com.sun.jndi.ldap.connect.pool", "false");
        ht.put("com.sun.jndi.ldap.connect.timeout", "60000");

        Collection auths = new HashSet();
        try {
            DirContext context = new InitialDirContext(ht);
            //droit de lecture
            try {
                Attributes transaction = context.getAttributes(readDN);
                if (transaction.size() > 0) {
                    auths.add(XemeliosUser.ROLE_CONNECT);
                    auths.add(XemeliosUser.ROLE_BROWSE);
                    auths.add(XemeliosUser.ROLE_SEARCH);
                    auths.add(XemeliosUser.ROLE_EXPORT);
                }
            } catch (NamingException e) {
                e.printStackTrace();
            }
            //droit d'ecriture
            try {
                Attributes transaction = context.getAttributes(writeDN);
                if (transaction.size() > 0) {
                    auths.add(XemeliosUser.ROLE_CLEAN);
                    auths.add(XemeliosUser.ROLE_IMPORT);
                }
            } catch (NamingException e) {
                e.printStackTrace();
            }
            context.close();
        } catch (NamingException e) {
            System.out.println("Bad password ? : " + e.getMessage());
            e.printStackTrace();
        }
        if (!auths.isEmpty()) {
            return new SimpleXemeliosUserImpl(login, login,
                    false, auths, true, null, true, null);
        } else {
            return null;
        }
    }

}
