/*
 * @Author: Kane
 * @Date: 2022-12-15 09:51:12
 * @LastEditors: Kane
 * @LastEditTime: 2022-12-16 15:29:34
 * @FilePath: \AdminSys\src\main\java\com\cpic\xim\myutils\account\LdapAccountCheck.java
 * @Description: P13验证相关方法。
 * 
 * Copyright (c) ${2022} by Kane, All Rights Reserved. 
 */
package com.cpic.xim.myutils.account;

import javax.naming.CommunicationException;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import java.util.Hashtable;

public class LdapAccountCheck
{
    private static String ldapServerUrl = "ldap://10.39.0.205:389";

    /*****************************************************
     * 对p13账号密码提交AD域服务器进行验证
     * @param userName p13uid
     * @param password p13密码
     * @return 返回验证结果，true为成功，false失败。
     *****************************************************/
    public static boolean ldapLogin( String userName, String password )
    {
        boolean result = false;

        if ( userName.endsWith( "@pr.intra.cpic.com.cn" ) == false)
        {
            userName += "@pr.intra.cpic.com.cn";
        }

        DirContext ctx = null;
        Hashtable<String, String> ldap = new Hashtable<String, String>();

        ldap.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory" );
        ldap.put( Context.SECURITY_AUTHENTICATION, "simple" );
        ldap.put( Context.PROVIDER_URL, ldapServerUrl );
        ldap.put( Context.SECURITY_PRINCIPAL, userName );
        ldap.put( Context.SECURITY_CREDENTIALS, password );

        try
        {
            ctx = new InitialDirContext( ldap );
            ctx.close();

            result = true;
        }
        catch ( CommunicationException error )
        {
            error.printStackTrace();
            error.getMessage();

            result = false;
        }
        catch ( NamingException error )
        {
            error.printStackTrace();
            result = false;
        }

        return result;
    }
}
