package com.cmeeting.ad.service.impl;

import com.cmeeting.ad.service.ILdapService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.support.LdapUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.naming.directory.DirContext;


@Component
@Slf4j
public class LdapServiceImpl implements ILdapService {
    @Resource
    private LdapTemplate ldapTemplate;

    @Value("${ldap.domain}")
    private String ldapDomain;


    /**
     * LDAP用户认证
     */
    @Override
    public boolean authenticate(String loginName, String password) {
        String userDomainName = loginName + ldapDomain;
        DirContext ctx = null;
        try {
            ctx = ldapTemplate.getContextSource().getContext(userDomainName, password);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            LdapUtils.closeContext(ctx);
        }
        return false;
    }





}
