package org.jeecg.common.configure;


import java.util.Hashtable;

import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.Control;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

/**
 * 功能描述：
 *
 * @Author: chenchuang
 * @Date: 2020/6/11 9:22
 */
public class LDAPAuthentication {
    private final String URL = "ldap://10.21.2.100:389/";
    private final String BASEDN = "ou=Departments,dc=frontage,dc=com";
    private final String FACTORY = "com.sun.jndi.ldap.LdapCtxFactory";
    private LdapContext ctx = null;
    private final Control[] connCtls = null;

    private void LDAP_connect() {
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, FACTORY);
        env.put(Context.PROVIDER_URL, URL + BASEDN);
        env.put(Context.SECURITY_AUTHENTICATION, "simple");

        String root = "cn=frontagelabadmini";// root
        env.put(Context.SECURITY_PRINCIPAL, root);
        env.put(Context.SECURITY_CREDENTIALS, "h$1Pqitm");
        // 此处若不指定用户名和密码,则自动转换为匿名登录
        try {
            ctx = new InitialLdapContext(env, connCtls);
        } catch (javax.naming.AuthenticationException e) {
            System.out.println("验证失败：" + e.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getUserDN(String uid) {
        String userDN = "";
        LDAP_connect();
        try {
            SearchControls constraints = new SearchControls();
            constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
            NamingEnumeration<SearchResult> en = ctx.search("", "uid=" + uid, constraints);
            if (en == null || !en.hasMoreElements()) {
                System.out.println("未找到该用户");
            }
            // maybe more than one element
            while (en != null && en.hasMoreElements()) {
                Object obj = en.nextElement();
                if (obj instanceof SearchResult) {
                    SearchResult si = (SearchResult) obj;
                    userDN += si.getName();
                    userDN += "," + BASEDN;
                } else {
                    System.out.println(obj);
                }
            }
        } catch (Exception e) {
            System.out.println("查找用户时产生异常。");
            e.printStackTrace();
        }

        return userDN;
    }

    public boolean authenricate(String UID, String password) {
        boolean valide = false;
        String userDN = getUserDN(UID);

        try {
            ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userDN);
            ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
            ctx.reconnect(connCtls);
            System.out.println(userDN + " 验证通过");
            valide = true;
        } catch (AuthenticationException e) {
            System.out.println(userDN + " 验证失败");
            System.out.println(e.toString());
            valide = false;
        } catch (NamingException e) {
            System.out.println(userDN + " 验证失败");
            valide = false;
        }

        return valide;
    }

    public boolean login(String UID, String password){
        String host = "10.21.2.100"; // AD服务器IP

        String port = "50000"; // 端口

        // String domain = "@domain.com.cn"; //邮箱的后缀名

        String user=UID;//这里有两种格式，domain\User或邮箱的后缀名,建议用domain\User这种格式
        String url = new String("ldap://" + host + ":" + port);

        //String user = userName.indexOf(domain) > 0 ? userName : userName + domain;

        Hashtable env = new Hashtable();

        DirContext ctx;

        env.put(Context.SECURITY_AUTHENTICATION, "simple");//一种模式，不用管，就这么写就可以了
        env.put(Context.SECURITY_PRINCIPAL,"CN=idau.com,OU=Frontage Labortories,DC=frontage");//这

        env.put(Context.SECURITY_CREDENTIALS, "Fr0ntage@2o19");

        env.put(Context.INITIAL_CONTEXT_FACTORY,

                "com.sun.jndi.ldap.LdapCtxFactory");

        env.put(Context.PROVIDER_URL, url);

        try {
            System.out.println("authenticating");
            ctx = new InitialDirContext(env);
            System.out.println("authenticated");
            ctx.close();

            return true; //验证成功返回name

        } catch (NamingException err) {
            err.getMessage();
            System.out.println(err.getMessage());
            return false;//验证失败返回空

        }
    }
}
