adc

package module
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Apr 30, 2024 License: MIT Imports: 9 Imported by: 0

README

adc

build-img doc-img coverage-img

Active Directory client library.

The library is a wrapper around go-ldap/ldap module that provides a more convient client for Active Directory.

Usage

Import module in your go app:

import "github.com/dlampsi/adc"
Getting started
// Init client
cl := adc.New(&adc.Config{
    URL:         "ldaps://my.ad.site:636",
    SearchBase:  "OU=some,DC=company,DC=com",
    Bind: &adc.BindAccount{
        DN:       "CN=admin,DC=company,DC=com",
        Password: "***",
    },
})

// Connect
if err := cl.Connect(); err != nil {
    // Handle error
}

// Search for a user
user, err := cl.GetUser(adc.GetUserArgs{Id:"userId"})
if err != nil {
    // Handle error
}
if user == nil {
    // Handle not found
}
fmt.Println(user)

// Search for a group
group, err := cl.GetGroup(adc.GetGroupArgs{Id:"groupId"})
if err != nil {
    // Handle error
}
if group == nil {
    // Handle not found
}
fmt.Println(group)

// Add new users to group members
added, err := cl.AddGroupMembers("groupId", "newUserId1", "newUserId2", "newUserId3")
if err != nil {
    // Handle error
}
fmt.Printf("Added %d members", added)


// Delete users from group members
deleted, err := cl.DeleteGroupMembers("groupId", "userId1", "userId2")
if err != nil {
    // Handle error
}
fmt.Printf("Deleted %d users from group members", deleted)

Custom logger

You can specifiy custom logger for client. Logger must implement Logger interface. Provide logger during client init:

cl := New(cfg, adc.WithLogger(myCustomLogger))
Custom search base

You can set custom search base for user/group in config:

cfg := &adc.Config{
    URL:         "ldaps://my.ad.site:636",
    SearchBase:  "OU=some,DC=company,DC=com",
    Bind: &adc.BindAccount{DN: "CN=admin,DC=company,DC=com", Password: "***"},
    Users: &adc.UsersConfigs{
        SearchBase: "OU=users_base,DC=company,DC=com",,
    },
}

cl := New(cfg)

if err := cl.Connect(); err != nil {
    // Handle error
}
Custom entries attributes

You can parse custom attributes to client config to fetch those attributes during users or groups fetch:

// Append new attributes to existsing user attributes
cl.Config.AppendUsesAttributes("manager")

// Search for a user
user, err := cl.GetUser(adc.GetUserArgs{Id:"userId"})
if err != nil {
    // Handle error
}
if user == nil {
    // Handle not found
}

// Get custom attribute
userManager := exists.GetStringAttribute("manager")
fmt.Println(userManager)

Also you can parse custom attributes during each get requests:

user, err := cl.GetUser(adc.GetUserArgs{Id: "userId", Attributes: []string{"manager"}})
if err != nil {
    // Handle error
}
// Get custom attribute
userManager := exists.GetStringAttribute("manager")
fmt.Println(userManager)
Custom search filters

You can parse custom search filters to client config:

cfg := &adc.Config{
    URL:         "ldaps://my.ad.site:636",
    SearchBase:  "OU=some,DC=company,DC=com",
    Bind: &adc.BindAccount{DN: "CN=admin,DC=company,DC=com", Password: "***"},
    Users: &adc.UsersConfigs{
        FilterById: "(&(objectClass=person)(cn=%v))",
    },
    Groups: &adc.GroupsConfigs{
        FilterById: "(&(objectClass=group)(cn=%v))",
    },
}
cl := New(cfg)
if err := cl.Connect(); err != nil {
    // Handle error
}

Also, you can provide a custom search filter for direct searches:

// Init client
cl := adc.New(&adc.Config{
    URL:         "ldaps://my.ad.site:636",
    SearchBase:  "OU=some,DC=company,DC=com",
    Bind: &adc.BindAccount{
        DN:       "CN=admin,DC=company,DC=com",
        Password: "***",
    },
})

// Connect
if err := cl.Connect(); err != nil {
    // Handle error
}

// Search for a user
user, err := cl.GetUser(adc.GetUserArgs{Filter:"(&(objectClass=person)(sAMAccountName=someID))"})
if err != nil {
    // Handle error
}
if user == nil {
    // Handle not found
}
fmt.Println(user)

Note that provided Filter argument int GetUserArgs overwrites Id and Dn arguments usage.

Reconnect

Client has reconnect method, that validates connection to server and reconnects to it with provided ticker interval and retries attempts count.

Exxample for recconect each 5 secconds with 24 retrie attempts:

if err := cl.Reconnect(ctx, time.NewTicker(5*time.Second), 24); err != nil {
    // Handle error
}

Contributing

  1. Create new PR from main branch
  2. Request review from maintainers

License

MIT License.

Documentation

Overview

Package adc provides basic client library for Active Directory.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BindAccount

type BindAccount struct {
	DN       string `json:"dn"`
	Password string `json:"password"`
}

Account attributes to authentificate in AD.

type Client

type Client struct {
	Config *Config
	// contains filtered or unexported fields
}

Active Direcotry client.

func New

func New(cfg *Config, opts ...Option) *Client

Creates new client and populate provided config and options.

func (*Client) AddGroupMembers

func (cl *Client) AddGroupMembers(groupId string, membersIds ...string) (int, error)

Adds provided accounts IDs to provided group members. Returns number of addedd accounts.

func (*Client) CheckAuthByDN

func (cl *Client) CheckAuthByDN(dn, password string) error

Tries to authorise in AcitveDirecotry by provided DN and password and return error if failed. Use this method to check if user can be authenticated in AD.

func (*Client) Connect

func (cl *Client) Connect() error

Connects to AD server and store connection into client.

func (*Client) DeleteGroupMembers

func (cl *Client) DeleteGroupMembers(groupId string, membersIds ...string) (int, error)

Deletes provided accounts IDs from provided group members. Returns number of deleted from group members.

func (*Client) Disconnect

func (cl *Client) Disconnect() error

Closes connection to AD.

func (*Client) GetGroup

func (cl *Client) GetGroup(args GetGroupArgs) (*Group, error)

func (*Client) GetUser

func (cl *Client) GetUser(args GetUserArgs) (*User, error)

func (*Client) Reconnect added in v0.3.0

func (cl *Client) Reconnect(ctx context.Context, tickerDuration time.Duration, maxAttempts int) error

Checks connections to AD and tries to reconnect if the connection is lost.

type Config

type Config struct {
	// LDAP server URL. Examle 'ldaps://cl.local:636'
	URL string `json:"url"`
	// Use insecure SSL connection.
	InsecureTLS bool `json:"insecure_tls"`
	// Time limit for requests.
	Timeout time.Duration
	// Base OU for search requests.
	SearchBase string `json:"search_base"`

	// Bind account info.
	Bind *BindAccount `json:"bind"`

	// Requests filters vars.
	Users *UsersConfigs `json:"users"`
	// Requests filters vars.
	Groups *GroupsConfigs `json:"groups"`
}

func (*Config) AppendGroupsAttributes

func (cfg *Config) AppendGroupsAttributes(attrs ...string)

Appends attributes to params in client config file.

func (*Config) AppendUsesAttributes

func (cfg *Config) AppendUsesAttributes(attrs ...string)

Appends attributes to params in client config file.

type GetGroupArgs added in v0.4.0

type GetGroupArgs struct {
	// Group ID to search.
	Id string `json:"id"`
	// Optional group DN. Overwrites ID if provided in request.
	Dn string `json:"dn"`
	// Optional LDAP filter to search entry. Warning! provided Filter arg overwrites Id and Dn args usage.
	Filter string `json:"filter"`
	// Optional group attributes to overwrite attributes in client config.
	Attributes []string `json:"attributes"`
	// Skip search of group members data. Can improve request time.
	SkipMembersSearch bool `json:"skip_members_search"`
}

func (GetGroupArgs) Validate added in v0.4.0

func (args GetGroupArgs) Validate() error

type GetUserArgs added in v0.4.0

type GetUserArgs struct {
	// User ID to search.
	Id string `json:"id"`
	// Optional User DN. Overwrites ID if provided in request.
	Dn string `json:"dn"`
	// Optional LDAP filter to search entry. Warning! provided Filter arg overwrites Id and Dn args usage.
	Filter string `json:"filter"`
	// Optional user attributes to overwrite attributes in client config.
	Attributes []string `json:"attributes"`
	// Skip search of user groups data. Can improve request time.
	SkipGroupsSearch bool `json:"skip_groups_search"`
}

func (GetUserArgs) Validate added in v0.4.0

func (args GetUserArgs) Validate() error

type Group

type Group struct {
	DN         string                 `json:"dn"`
	Id         string                 `json:"id"`
	Attributes map[string]interface{} `json:"attributes"`
	Members    []GroupMember          `json:"members"`
}

Active Direcotry group.

func (*Group) GetStringAttribute

func (g *Group) GetStringAttribute(name string) string

Returns string attribute by attribute name. Returns empty string if attribute not exists or it can't be covnerted to string.

func (*Group) MembersDn

func (g *Group) MembersDn() []string

Returns list of group members DNs.

func (*Group) MembersId

func (g *Group) MembersId() []string

Returns list of group members IDs.

type GroupMember

type GroupMember struct {
	DN string `json:"dn"`
	Id string `json:"id"`
}

Active Direcotry member info.

type GroupsConfigs

type GroupsConfigs struct {
	// The ID attribute name for group.
	IdAttribute string `json:"id_attribute"`
	// Group attributes for fetch from AD.
	Attributes []string `json:"attributes"`
	// Base OU to search groups requests. Sets to Config.SearchBase if not provided.
	SearchBase string `json:"search_base"`
	// LDAP filter to get group by ID.
	FilterById string `json:"filter_by_id"`
	// LDAP filter to get group by DN.
	FilterByDn string `json:"filter_by_dn"`
	// LDAP filter to get group members.
	FilterMembersByDn string `json:"filter_members_by_dn"`
}

type Logger added in v0.2.0

type Logger interface {
	Debug(args ...interface{})
	Debugf(template string, args ...interface{})
}

Client logger interface.

type Option

type Option func(*Client)

func WithLogger added in v0.2.0

func WithLogger(l Logger) Option

Specifies custom logger for client.

type User

type User struct {
	DN         string                 `json:"dn"`
	Id         string                 `json:"id"`
	Attributes map[string]interface{} `json:"attributes"`
	Groups     []UserGroup            `json:"groups"`
}

Active Direcotry user.

func (*User) GetStringAttribute

func (u *User) GetStringAttribute(name string) string

Returns string attribute by attribute name. Returns empty string if attribute not exists or it can't be covnerted to string.

func (*User) GroupsDn added in v0.1.0

func (u *User) GroupsDn() []string

Returns list of user groups DNs.

func (*User) GroupsId added in v0.1.0

func (u *User) GroupsId() []string

Returns list of user groups IDs.

func (*User) IsGroupMember

func (u *User) IsGroupMember(groupId string) bool

type UserGroup

type UserGroup struct {
	DN string `json:"dn"`
	Id string `json:"id"`
}

Active Direcotry user group info.

type UsersConfigs

type UsersConfigs struct {
	// The ID attribute name for group.
	IdAttribute string `json:"id_attribute"`
	// User attributes for fetch from AD.
	Attributes []string `json:"attributes"`
	// Base OU to search users requests. Sets to Config.SearchBase if not provided.
	SearchBase string `json:"search_base"`
	// LDAP filter to get user by ID.
	FilterById string `json:"filter_by_id"`
	// LDAP filter to get user by DN.
	FilterByDn string `json:"filter_by_dn"`
	// LDAP filter to get user groups membership.
	FilterGroupsByDn string `json:"filter_groups_by_dn"`
}

Jump to

Keyboard shortcuts

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