/*
 * 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.ldapAphm;

import fr.gouv.finances.dgfip.xemelios.common.Scramble;
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 fr.gouv.finances.dgfip.xemelios.data.impl.pool.PoolManager;
import fr.gouv.finances.dgfip.xemelios.data.impl.pool.SQLRuntimeException;
import fr.gouv.finances.dgfip.xemelios.data.utils.jdbc.JdbcUtils;
import fr.gouv.finances.dgfip.xemelios.data.utils.jdbc.PStmtBinder.SimplePStmtBinderBuilder;
import fr.gouv.finances.dgfip.xemelios.data.utils.jdbc.RowMapper.ColToIntegerRowMapper;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Hashtable;
import javax.naming.AuthenticationException;
import javax.naming.NamingEnumeration;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;

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

    private String baseUrl;
    private String adminLogin;
    private String adminPassword;
    private String searchPath;
    private String searchField;

    public LdapAuthEngineImpl() throws DataConfigurationException, SQLException {
        baseUrl = DataLayerManager.getImplementation().getParameterValue("auth.ldap.baseUrl");
        adminLogin = DataLayerManager.getImplementation().getParameterValue("auth.ldap.adminLogin");
        adminPassword = DataLayerManager.getImplementation().getParameterValue("auth.ldap.adminPassword");
        searchPath = DataLayerManager.getImplementation().getParameterValue("auth.ldap.searchPath");
        searchField = DataLayerManager.getImplementation().getParameterValue("auth.ldap.searchField");
        if (adminPassword != null) {
            // le mot de passe est crypté, il faut le décrypter
            adminPassword = Scramble.unScramblePassword(adminPassword);
        }
        Connection connection = null;
        try {
            connection = PoolManager.getInstance().getConnection();
            String sql = "CREATE TABLE IF NOT EXISTS APHM_USERS (LOGIN VARCHAR(24) NOT NULL, ACCESS INT)";
            JdbcUtils.executeUpdate(connection, sql);
        } finally {
            PoolManager.getInstance().releaseConnection(connection);
        }
    }

    public boolean isLoginRequired() {
        return true;
    }

    public boolean isPasswordRequired() {
        return true;
    }

    public XemeliosUser createUser(String login, String password) {
        Integer authAsInteger = getAuth(login);
        if (authAsInteger != null) {
            Hashtable env = new Hashtable();
            env.put(DirContext.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            env.put(DirContext.PROVIDER_URL, baseUrl);
            env.put(DirContext.SECURITY_AUTHENTICATION, "simple");
            env.put(DirContext.SECURITY_PRINCIPAL, adminLogin);
            env.put(DirContext.SECURITY_CREDENTIALS, adminPassword);
            DirContext ctx = null;
            String userDN = null;
            try {
                // Bind admin :
                ctx = new InitialDirContext(env);
                //recherche login demandé dans l'arbre
                SearchControls ctls = new SearchControls();
                ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
                NamingEnumeration e = ctx.search(searchPath, "(" + searchField + "=" + login.toUpperCase() + ")", ctls);
                if (e.hasMore()) {
                    SearchResult o = (SearchResult) e.next();
                    userDN = "" + o.getAttributes().get("distinguishedName").getAll().next();
                }
            } catch (Exception e) {
            } finally {
                try {
                    if (ctx != null) {
                        ctx.close();
                    }
                } catch (Exception e) {
                }
            }
            if (userDN == null) {
                return null; // user pas trouvé
            } else {
                // Bind user :
                env = new Hashtable();
                env.put(DirContext.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
                env.put(DirContext.PROVIDER_URL, baseUrl);
                env.put(DirContext.SECURITY_AUTHENTICATION, "simple");
                env.put(DirContext.SECURITY_PRINCIPAL, userDN);
                env.put(DirContext.SECURITY_CREDENTIALS, password);
                try {
                    ctx = new InitialDirContext(env);
                    return new SimpleXemeliosUserImpl(login, login,
                            false, AuthEngine.Helper.rolesFromInt(authAsInteger), true, null, true, null);
                } catch (AuthenticationException e) {
                    return null;
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                } finally {
                    try {
                        if (ctx != null) {
                            ctx.close();
                        }
                    } catch (Exception e) { }
                }
            }
        } else {
            return null;
        }
    }

    static private Integer getAuth(String login) {
        Connection connection = null;
        try {
            connection = PoolManager.getInstance().getConnection();
            String sql = "SELECT ACCESS FROM APHM_USERS WHERE LOGIN = ?";//'"+login.toLowerCase()+"'";
            return (Integer) JdbcUtils.queryObject(connection,
                    sql,
                    new ColToIntegerRowMapper(),
                    new SimplePStmtBinderBuilder().add(login.toLowerCase()).toPStmtBinder());
        } catch (SQLException sqle) {
            throw new SQLRuntimeException(sqle);
        } finally {
            PoolManager.getInstance().releaseConnection(connection);
        }
    }

}
