ldap操作AD-OU,Group,User CRUD

通过ldap操作ADldap.go// Author : Darin Han// Copyright 2020 OneSmart.Org. All rights reserved.// Use of this source code is governed by a BSD-style// license that can be found in the LICENSE file.package ad// package for ad operation by ldapimport (
摘要由CSDN通过智能技术生成

通过ldap操作AD

ldap.go

// Author : Darin Han
// Copyright 2020 OneSmart.Org. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ad

// package for ad operation by ldap

import (
	"errors"
	"fmt"
	"gopkg.in/ldap.v2"
	"log"
)

type UserClaims struct {
	UserName string
	PassWord string
}
type LDAPClient struct {
	Host   string
	Port   int
	BaseDN string
	UserClaims
	Connection *ldap.Conn
}

//Const Name for LDAP Elements
const ObjectCategory_OU string = "organizationalUnit"
const ObjectCategory_Group string = "group"
const ObjectCategory_Person string = "user"

// open connection for ldap, Close() should be called intermediatly with defer
func (client *LDAPClient) Open() (*ldap.Conn, error) {
	if client.UserName == "" || client.PassWord == "" {
		return nil, errors.New("no user account and password !")
	}

	con, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", client.Host, client.Port))
	if err != nil {
		return nil, err
	}

	err = con.Bind(client.UserName, client.PassWord)
	if err != nil {
		return nil, err
	}
	client.Connection = con
	return con, nil
}

// close connection for ldap
func (client *LDAPClient) Close() {
	client.Connection.Close()
	client.Connection = nil
}

// try to connect ldap server, return error for fail.
func (client *LDAPClient) Connect() (bool, error) {
	l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", client.Host, client.Port))
	if err != nil {
		return false, err
	}
	defer l.Close()
	err = l.Bind(client.UserName, client.PassWord)
	if err != nil {
		log.Fatal(err)
	}
	return true, nil
}

/*
	OU attributes:
		description:描述
		c:国家简称
		co:国家
		l:市县
		st:省
		street:街道
		postalCode:邮编
*/
//search ou in the whole tree by dn,return ldap.SearchResult which contains entries , controls
func (client *LDAPClient) SearchOU(search string) (*ldap.SearchResult, error) {
	conn, err := client.Open()
	if err != nil {
		return nil, err
	}
	defer client.Close()

	return conn.Search(ldap.NewSearchRequest(client.BaseDN,
		ldap.ScopeWholeSubtree,
		ldap.NeverDerefAliase
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值