ldap

package
v1.20.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 10, 2026 License: MIT Imports: 14 Imported by: 0

README

ldap Package Documentation

Note:
This package uses an older design and would benefit from a refactor to modern Go idioms and best practices.


Overview

The ldap package provides helpers for connecting to, authenticating with, and querying LDAP servers in Go. It supports both plain and TLS/StartTLS connections, user and group lookups, and flexible configuration.


Features

  • Connect to LDAP servers with or without TLS/StartTLS
  • Bind and authenticate users
  • Retrieve user and group information
  • Check group membership and list group members
  • Customizable search filters and attributes
  • Integrated error handling with custom codes
  • Logging support for debugging and tracing

Main Types

Config

Represents the LDAP server configuration.

  • Uri: Server hostname (FQDN, required)
  • PortLdap: LDAP port (required, integer)
  • Portldaps: LDAPS port (optional, integer)
  • Basedn: Base DN for searches
  • FilterGroup: Pattern for group search (e.g., (&(objectClass=groupOfNames)(%s=%s)))
  • FilterUser: Pattern for user search (e.g., (%s=%s))

Validation:
Use Validate() to check config correctness.

TLSMode

Enum for connection mode:

  • TLSModeNone: No TLS
  • TLSModeTLS: Strict TLS
  • TLSModeStarttls: StartTLS
  • _TLSModeInit: Not defined
HelperLDAP

Main struct for managing LDAP connections and queries.

  • NewLDAP(ctx, config, attributes): Create a new helper
  • SetLogger(fct): Set a logger function
  • SetCredentials(user, pass): Set bind DN and password
  • ForceTLSMode(mode, tlsConfig): Force a specific TLS mode and config

Main Methods

  • Check(): Test connection (no bind)
  • Connect(): Connect and bind using credentials
  • AuthUser(username, password): Test user bind
  • UserInfo(username): Get user attributes as a map
  • UserInfoByField(username, field): Get user info by a specific field
  • GroupInfo(groupname): Get group attributes as a map
  • GroupInfoByField(groupname, field): Get group info by a specific field
  • UserMemberOf(username): List groups a user belongs to
  • UserIsInGroup(username, groupnames): Check if user is in any of the given groups
  • UsersOfGroup(groupname): List users in a group
  • ParseEntries(entry): Parse DN or attribute string into a map

Error Handling

All errors are wrapped with custom codes for diagnostics, such as:

  • ErrorParamEmpty
  • ErrorLDAPContext
  • ErrorLDAPServerConfig
  • ErrorLDAPServerConnection
  • ErrorLDAPBind
  • ErrorLDAPSearch
  • ErrorLDAPUserNotFound
  • ErrorLDAPGroupNotFound
  • ...and more

Use err.Error() for user-friendly messages and check error codes for diagnostics.


Example Usage

import (
    "context"
    "github.com/nabbar/golib/ldap"
)

cfg := ldap.Config{
    Uri:         "ldap.example.com",
    PortLdap:    389,
    Portldaps:   636,
    Basedn:      "dc=example,dc=com",
    FilterUser:  "(uid=%s)",
    FilterGroup: "(&(objectClass=groupOfNames)(cn=%s))",
}

if err := cfg.Validate(); err != nil {
    // handle config error
}

helper, err := ldap.NewLDAP(context.Background(), &cfg, ldap.GetDefaultAttributes())
if err != nil {
    // handle error
}

helper.SetCredentials("cn=admin,dc=example,dc=com", "password")

if err := helper.Connect(); err != nil {
    // handle connection/bind error
}

userInfo, err := helper.UserInfo("jdoe")
if err != nil {
    // handle user lookup error
}

// ... use userInfo map
helper.Close()

Notes

  • The package is thread-safe for most operations.
  • Designed for Go 1.18+.
  • Logging is optional but recommended for debugging.
  • The API and code structure are legacy and may not follow modern Go conventions.

Documentation

Index

Constants

View Source
const (
	ErrorParamEmpty liberr.CodeError = iota + liberr.MinPkgLDAP
	ErrorLDAPContext
	ErrorLDAPServerConfig
	ErrorLDAPServerConnection
	ErrorLDAPServerDial
	ErrorLDAPServerDialClosing
	ErrorLDAPServerTLS
	ErrorLDAPServerStartTLS
	ErrorLDAPBind
	ErrorLDAPSearch
	ErrorLDAPUserNotUniq
	ErrorLDAPUserNotFound
	ErrorLDAPInvalidDN
	ErrorLDAPInvalidUID
	ErrorLDAPAttributeNotFound
	ErrorLDAPAttributeEmpty
	ErrorLDAPValidatorError
	ErrorLDAPGroupNotFound
)

Variables

This section is empty.

Functions

func GetDefaultAttributes

func GetDefaultAttributes() []string

Types

type Config

type Config struct {
	Uri       string `cloud:"uri" mapstructure:"uri" json:"uri" yaml:"uri" toml:"uri" validate:"fqdn,required"`
	PortLdap  int    `` /* 144-byte string literal not displayed */
	Portldaps int    `` /* 143-byte string literal not displayed */
	Basedn    string `cloud:"basedn" mapstructure:"basedn" json:"basedn" yaml:"basedn" toml:"basedn" validate:"printascii,omitempty"`
	//FilterGroup is fmt pattern like '(&(objectClass=groupOfNames)(%s=%s))' to make search of group object class
	FilterGroup string `` /* 139-byte string literal not displayed */
	//FilterUser is a fmt pattern like '(%s=%s)' to make search of user. By default, uid field is 'uid'
	FilterUser string `` /* 134-byte string literal not displayed */
}

func NewConfig

func NewConfig() *Config

func (Config) BaseDN

func (cnf Config) BaseDN() string

func (Config) Clone

func (cnf Config) Clone() *Config

func (Config) PatternFilterGroup

func (cnf Config) PatternFilterGroup() string

func (Config) PatternFilterUser

func (cnf Config) PatternFilterUser() string

func (Config) ServerAddr

func (cnf Config) ServerAddr(withTls bool) string

func (Config) Validate added in v1.3.0

func (cnf Config) Validate() errors.Error

type FuncLogger added in v1.7.0

type FuncLogger liblog.FuncLog

type HelperLDAP

type HelperLDAP struct {
	Attributes []string
	// contains filtered or unexported fields
}

HelperLDAP struct use to manage connection to server and request it.

func NewLDAP

func NewLDAP(ctx context.Context, cnf *Config, attributes []string) (*HelperLDAP, liberr.Error)

NewLDAP build a new LDAP helper based on config struct given.

func (*HelperLDAP) AttributeFilter added in v1.17.0

func (lc *HelperLDAP) AttributeFilter(search string, filter string, allAttribute bool, attribute ...string) (map[string]map[string]string, liberr.Error)

func (*HelperLDAP) AuthUser

func (lc *HelperLDAP) AuthUser(username, password string) liberr.Error

AuthUser used to test bind given user uid and password.

func (*HelperLDAP) Check

func (lc *HelperLDAP) Check() liberr.Error

Check used to check if connection success (without any bind).

func (*HelperLDAP) Clone added in v1.13.1

func (lc *HelperLDAP) Clone() *HelperLDAP

func (*HelperLDAP) Close

func (lc *HelperLDAP) Close()

Close used to close connection object.

func (*HelperLDAP) Connect

func (lc *HelperLDAP) Connect() liberr.Error

Connect used to connect and bind to server.

func (*HelperLDAP) ForceTLSMode

func (lc *HelperLDAP) ForceTLSMode(tlsMode TLSMode, tlsConfig *tls.Config)

ForceTLSMode used to force tls mode and defined tls condition.

func (*HelperLDAP) GetTLSMode added in v1.13.6

func (lc *HelperLDAP) GetTLSMode() TLSMode

func (*HelperLDAP) GroupInfo added in v1.3.0

func (lc *HelperLDAP) GroupInfo(groupname string) (map[string]interface{}, liberr.Error)

GroupInfo used to retrieve the information of a given group cn.

func (*HelperLDAP) GroupInfoByField added in v1.5.0

func (lc *HelperLDAP) GroupInfoByField(groupname string, fieldForUnicValue string) (map[string]interface{}, liberr.Error)

GroupInfoByField used to retrieve the information of a given group cn, but use a given field to make the search.

func (*HelperLDAP) ParseEntries

func (lc *HelperLDAP) ParseEntries(entry string) map[string][]string

ParseEntries used to clean attributes of an object class.

func (*HelperLDAP) SetCredentials

func (lc *HelperLDAP) SetCredentials(user, pass string)

SetCredentials used to defined the BindDN and password for connection.

func (*HelperLDAP) SetLogger added in v1.7.0

func (lc *HelperLDAP) SetLogger(fct liblog.FuncLog)

SetLogger is used to specify the logger to be used for debug messgae

func (*HelperLDAP) UserInfo

func (lc *HelperLDAP) UserInfo(username string) (map[string]string, liberr.Error)

UserInfo used to retrieve the information of a given username.

func (*HelperLDAP) UserInfoByField added in v1.5.0

func (lc *HelperLDAP) UserInfoByField(username string, fieldOfUnicValue string) (map[string]string, liberr.Error)

UserInfoByField used to retrieve the information of a given username but use a given field to make the search.

func (*HelperLDAP) UserIsInGroup

func (lc *HelperLDAP) UserIsInGroup(username string, groupname []string) (bool, liberr.Error)

UserIsInGroup used to check if a given username is a group member of a list of reference group name.

func (*HelperLDAP) UserMemberOf

func (lc *HelperLDAP) UserMemberOf(username string) ([]string, liberr.Error)

UserMemberOf returns the group list of a given user.

func (*HelperLDAP) UsersOfGroup

func (lc *HelperLDAP) UsersOfGroup(groupname string) ([]string, liberr.Error)

UsersOfGroup used to retrieve the member list of a given group name.

type TLSMode

type TLSMode uint8
const (

	//TLSModeNone no tls connection.
	TLSModeNone TLSMode = iota + 1
	//TLSModeTLS strict tls connection.
	TLSModeTLS
	//TLSModeStarttls starttls connection (tls into a no tls connection).
	TLSModeStarttls
)

func (TLSMode) String

func (m TLSMode) String() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL