ldap

package module
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Sep 9, 2025 License: MIT Imports: 7 Imported by: 0

README

Simple LDAP Go

Go Reference Go Report Card

A simple Go library providing an easy-to-use wrapper around go-ldap/ldap/v3 for common LDAP and Active Directory operations.

This package was extracted from netresearch/raybeam to provide a standalone, reusable LDAP client library.

Features

  • 🔐 User Authentication - Password verification for LDAP users
  • 👥 User Management - Create, find, update, and delete users
  • 🏢 Group Operations - Query groups and manage memberships
  • 💻 Computer Management - Find and manage computer objects (Active Directory)
  • 🔑 Password Management - Change user passwords (LDAPS required for AD)
  • 🛡️ Active Directory Support - Special handling for AD-specific features
  • Simple API - Easy-to-use interface with comprehensive error handling

Installation

go get github.com/netresearch/simple-ldap-go

Quick Start

package main

import (
    "fmt"
    "log"
    
    ldap "github.com/netresearch/simple-ldap-go"
)

func main() {
    // Configure LDAP connection
    config := ldap.Config{
        Server:            "ldaps://ldap.example.com:636",
        BaseDN:            "dc=example,dc=com",
        IsActiveDirectory: true, // Set to false for generic LDAP
    }

    // Create client with service account credentials
    client, err := ldap.New(config, "cn=admin,dc=example,dc=com", "password")
    if err != nil {
        log.Fatal(err)
    }

    // Authenticate a user
    user, err := client.CheckPasswordForSAMAccountName("username", "password")
    if err != nil {
        log.Printf("Authentication failed: %v", err)
        return
    }
    
    fmt.Printf("Welcome, %s!\n", user.CN())
}

Examples

Comprehensive examples are available in the examples directory:

API Reference

Core Types
  • Config - LDAP server configuration
  • LDAP - Main client for LDAP operations
  • User - Represents an LDAP user with common attributes
  • Group - Represents an LDAP group with member information
  • Computer - Represents a computer object (Active Directory)
Key Operations
// Client creation
client, err := ldap.New(config, username, password)

// User authentication
user, err := client.CheckPasswordForSAMAccountName("jdoe", "password")

// Find users
user, err := client.FindUserBySAMAccountName("jdoe")
users, err := client.FindUsers()

// User management
err := client.CreateUser(fullUser, "ou=Users,dc=example,dc=com")
err := client.DeleteUser("cn=John Doe,ou=Users,dc=example,dc=com")

// Group operations
group, err := client.FindGroupByDN("cn=Admins,dc=example,dc=com")
err := client.AddUserToGroup(userDN, groupDN)

See the Go Reference for complete API documentation.

Configuration

Generic LDAP Server
config := ldap.Config{
    Server:            "ldap://ldap.example.com:389",
    BaseDN:            "dc=example,dc=com",
    IsActiveDirectory: false,
}
Microsoft Active Directory
config := ldap.Config{
    Server:            "ldaps://ad.example.com:636", // LDAPS recommended
    BaseDN:            "dc=example,dc=com", 
    IsActiveDirectory: true, // Enables AD-specific features
}

Security Best Practices

  • Use LDAPS (TLS encryption) in production environments
  • Use service accounts with minimal required permissions
  • Store credentials securely using environment variables or key management
  • Validate certificates in production deployments
  • ⚠️ Password changes require LDAPS when using Active Directory

Error Handling

The library provides specific error types for common scenarios:

// Check for specific errors
_, err := client.FindUserBySAMAccountName("username")
if err == ldap.ErrUserNotFound {
    // Handle user not found
} else if err != nil {
    // Handle other errors
}

Available error types:

  • ErrUserNotFound - User lookup failed
  • ErrGroupNotFound - Group lookup failed
  • ErrComputerNotFound - Computer lookup failed
  • ErrSAMAccountNameDuplicated - Account name already exists
  • ErrMailDuplicated - Email address already exists
  • ErrActiveDirectoryMustBeLDAPS - LDAPS required for AD operations

Requirements

  • Go 1.23.0 or later
  • Access to an LDAP server (OpenLDAP, Active Directory, etc.)
  • Appropriate credentials and permissions for desired operations

Testing

Tests require a live LDAP server. Set the following environment variables:

export LDAP_SERVER="ldaps://your-server:636"
export LDAP_BASE_DN="dc=example,dc=com" 
export LDAP_READ_USER="cn=service,dc=example,dc=com"
export LDAP_READ_PASSWORD="password"

Then run tests:

go test -v ./...

License

This package is licensed under the MIT License. See the included LICENSE file for details.

Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Follow Conventional Commits for commit messages
  4. Use gofmt for code formatting
  5. Add tests for new functionality
  6. Submit a pull request

Documentation

Overview

Package ldap provides a simplified interface for LDAP operations with Active Directory support.

Package ldap provides a simple wrapper around go-ldap/ldap for common LDAP and Active Directory operations.

This package simplifies common LDAP operations including:

  • User authentication and password management
  • User, group, and computer object queries
  • User creation and deletion
  • Group membership management

The package is designed to work with both generic LDAP servers and Microsoft Active Directory, with special handling for AD-specific features like password changes and user account control flags.

Basic Usage

config := ldap.Config{
	Server:            "ldaps://ldap.example.com:636",
	BaseDN:            "dc=example,dc=com",
	IsActiveDirectory: true,
}

client, err := ldap.New(config, "cn=admin,dc=example,dc=com", "password")
if err != nil {
	log.Fatal(err)
}

// Authenticate a user
user, err := client.CheckPasswordForSAMAccountName("username", "password")
if err != nil {
	log.Printf("Authentication failed: %v", err)
	return
}
fmt.Printf("Authenticated user: %s\n", user.CN())

// Find users
users, err := client.FindUsers()
if err != nil {
	log.Printf("Failed to find users: %v", err)
	return
}
for _, u := range users {
	fmt.Printf("User: %s (%s)\n", u.CN(), u.SAMAccountName)
}

Active Directory Considerations

When working with Active Directory, set IsActiveDirectory to true in the Config. This enables AD-specific features:

  • Password changes require LDAPS connection
  • Proper handling of User Account Control flags
  • Support for AD-specific attributes

Error Handling

The package defines specific error variables for common scenarios:

  • ErrUserNotFound: User lookup failed
  • ErrGroupNotFound: Group lookup failed
  • ErrComputerNotFound: Computer lookup failed
  • ErrDNDuplicated: Distinguished name is not unique
  • ErrSAMAccountNameDuplicated: SAM account name already exists
  • ErrMailDuplicated: Email address already exists
  • ErrActiveDirectoryMustBeLDAPS: LDAPS required for AD password operations

Always check for these specific errors when appropriate to provide better error handling in your applications.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrUserNotFound is returned when a user search operation finds no matching entries.
	ErrUserNotFound = errors.New("user not found")
	// ErrSAMAccountNameDuplicated is returned when multiple users have the same sAMAccountName,
	// indicating a data integrity issue in the directory.
	ErrSAMAccountNameDuplicated = errors.New("sAMAccountName is not unique")
	// ErrMailDuplicated is returned when multiple users have the same email address,
	// indicating a data integrity issue in the directory.
	ErrMailDuplicated = errors.New("mail is not unique")
)
View Source
var (

	// ErrActiveDirectoryMustBeLDAPS is returned when attempting to change passwords on Active Directory
	// over an unencrypted connection. Password changes in AD require LDAPS (LDAP over SSL/TLS).
	ErrActiveDirectoryMustBeLDAPS = errors.New("ActiveDirectory servers must be connected to via LDAPS to change passwords")
)
View Source
var ErrComputerNotFound = errors.New("computer not found")

ErrComputerNotFound is returned when a computer search operation finds no matching entries.

View Source
var ErrDNDuplicated = errors.New("DN is not unique")

ErrDNDuplicated is returned when a search operation finds multiple entries with the same DN, indicating a data integrity issue.

View Source
var ErrGroupNotFound = errors.New("group not found")

ErrGroupNotFound is returned when a group search operation finds no matching entries.

Functions

This section is empty.

Types

type Computer

type Computer struct {
	Object
	// SAMAccountName is the Security Account Manager account name for the computer (typically ends with $).
	SAMAccountName string
	// Enabled indicates whether the computer account is enabled (not disabled by userAccountControl).
	Enabled bool
	// OS contains the operating system name from the operatingSystem attribute.
	OS string
	// OSVersion contains the operating system version from the operatingSystemVersion attribute.
	OSVersion string
	// Groups contains a list of distinguished names (DNs) of groups the computer belongs to.
	Groups []string
}

Computer represents an LDAP computer object with common attributes.

type Config

type Config struct {
	// Server is the LDAP server URL (e.g., "ldap://localhost:389" or "ldaps://domain.com:636")
	Server string
	// BaseDN is the base distinguished name for LDAP searches (e.g., "DC=example,DC=com")
	BaseDN string

	// IsActiveDirectory indicates whether the server is Microsoft Active Directory.
	// This affects password change operations which require LDAPS for AD.
	IsActiveDirectory bool

	// DialOptions contains additional options for the LDAP connection
	DialOptions []ldap.DialOpt
}

Config holds the configuration for connecting to an LDAP server.

type FullUser

type FullUser struct {
	// CN is the common name of the user (required, used as the RDN component).
	CN string
	// SAMAccountName is the Security Account Manager account name (optional for creation).
	SAMAccountName *string
	// FirstName is the user's given name (required).
	FirstName string
	// LastName is the user's surname (required).
	LastName string
	// DisplayName is the name displayed in address lists (optional, defaults to CN if nil).
	DisplayName *string
	// Description contains additional information about the user (optional).
	Description *string
	// Email is the user's email address (optional).
	Email *string
	// ObjectClasses defines the LDAP object classes (optional, defaults to standard user classes).
	ObjectClasses []string
	// AccountExpires represents the expiration date of the user's account.
	// When set to nil, the account never expires.
	AccountExpires *time.Time
	// UserAccountControl contains the account control flags (enabled/disabled, password policies, etc.).
	UserAccountControl UAC
	// Path specifies the organizational unit path relative to BaseDN (optional, defaults to BaseDN).
	Path *string
}

FullUser represents a complete user object for creation operations with all configurable attributes.

type Group

type Group struct {
	Object
	// Members contains a list of distinguished names (DNs) of group members.
	Members []string
}

Group represents an LDAP group object with its members.

type LDAP

type LDAP struct {
	// contains filtered or unexported fields
}

LDAP represents a client connection to an LDAP server with authentication credentials.

func New

func New(config Config, user, password string) (*LDAP, error)

New creates a new LDAP client with the specified configuration and credentials. It validates the connection by attempting to connect and authenticate with the provided credentials.

Parameters:

  • config: The LDAP server configuration including server URL and base DN
  • user: The distinguished name (DN) or username for authentication
  • password: The password for authentication

Returns:

  • *LDAP: A configured LDAP client ready for operations
  • error: Any error encountered during connection validation

Example:

config := Config{
    Server: "ldaps://ad.example.com:636",
    BaseDN: "DC=example,DC=com",
    IsActiveDirectory: true,
}
client, err := New(config, "CN=admin,CN=Users,DC=example,DC=com", "password")

func (*LDAP) AddUserToGroup

func (l *LDAP) AddUserToGroup(dn, groupDN string) error

AddUserToGroup adds a user to a group by modifying the group's member attribute.

Parameters:

  • dn: The distinguished name of the user to add to the group
  • groupDN: The distinguished name of the group to modify

Returns:

  • error: Any LDAP operation error, including insufficient permissions or if the user is already a member

This operation requires write permissions on the target group object.

func (*LDAP) ChangePasswordForSAMAccountName

func (l *LDAP) ChangePasswordForSAMAccountName(sAMAccountName, oldPassword, newPassword string) (err error)

ChangePasswordForSAMAccountName changes a user's password in Active Directory. This method requires the current password for authentication and changes it to the new password.

Parameters:

  • sAMAccountName: The Security Account Manager account name of the user
  • oldPassword: The current password (required for authentication)
  • newPassword: The new password to set

Returns:

  • error: ErrActiveDirectoryMustBeLDAPS if trying to change AD passwords over unencrypted connection, ErrUserNotFound if user doesn't exist, authentication error if old password is wrong, or any other LDAP operation error

Requirements:

  • For Active Directory servers, LDAPS (SSL/TLS) connection is mandatory
  • User must provide their current password for verification
  • New password must meet the domain's password policy requirements

The password change uses the Microsoft-specific unicodePwd attribute with proper UTF-16LE encoding. Reference: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-adts/6e803168-f140-4d23-b2d3-c3a8ab5917d2

func (*LDAP) CheckPasswordForDN

func (l *LDAP) CheckPasswordForDN(dn, password string) (*User, error)

CheckPasswordForDN validates a user's password by attempting to bind with their credentials. This method finds the user by their distinguished name and then attempts authentication.

Parameters:

  • dn: The distinguished name of the user (e.g., "CN=John Doe,CN=Users,DC=example,DC=com")
  • password: The password to validate

Returns:

  • *User: The user object if authentication succeeds
  • error: ErrUserNotFound if the user doesn't exist, or authentication error if credentials are invalid

This method is useful when you already have the user's DN and want to validate their password.

func (*LDAP) CheckPasswordForSAMAccountName

func (l *LDAP) CheckPasswordForSAMAccountName(sAMAccountName, password string) (*User, error)

CheckPasswordForSAMAccountName validates a user's password by attempting to bind with their credentials. This method finds the user by their sAMAccountName and then attempts authentication.

Parameters:

  • sAMAccountName: The Security Account Manager account name (e.g., "jdoe" for john.doe@domain.com)
  • password: The password to validate

Returns:

  • *User: The user object if authentication succeeds
  • error: ErrUserNotFound if the user doesn't exist, or authentication error if credentials are invalid

This is commonly used for login validation in Active Directory environments.

func (*LDAP) CreateUser

func (l *LDAP) CreateUser(user FullUser, password string) (string, error)

CreateUser creates a new user in the directory with the specified attributes.

Parameters:

  • user: The FullUser object containing all user attributes
  • password: The initial password for the user (currently not implemented in this version)

Returns:

  • string: The distinguished name of the created user
  • error: Any LDAP operation error, including duplicate entries or insufficient permissions

Default behaviors:

  • ObjectClasses defaults to ["top", "person", "organizationalPerson", "user"] if not specified
  • DisplayName defaults to CN if not specified
  • The user is created at the specified Path relative to BaseDN, or directly under BaseDN if Path is nil

Example:

user := FullUser{
    CN: "John Doe",
    FirstName: "John",
    LastName: "Doe",
    SAMAccountName: &"jdoe",
    Email: &"john.doe@example.com",
    UserAccountControl: UAC{NormalAccount: true},
}
dn, err := client.CreateUser(user, "")

func (*LDAP) DeleteUser

func (l *LDAP) DeleteUser(dn string) error

DeleteUser removes a user from the directory.

Parameters:

  • dn: The distinguished name of the user to delete

Returns:

  • error: Any LDAP operation error, including user not found or insufficient permissions

Warning: This operation is irreversible. Ensure you have proper backups and permissions before deletion.

func (*LDAP) FindComputerByDN

func (l *LDAP) FindComputerByDN(dn string) (computer *Computer, err error)

FindComputerByDN retrieves a computer by its distinguished name.

Parameters:

  • dn: The distinguished name of the computer (e.g., "CN=COMPUTER01,CN=Computers,DC=example,DC=com")

Returns:

  • *Computer: The computer object if found
  • error: ErrComputerNotFound if no computer exists with the given DN, ErrDNDuplicated if multiple entries share the same DN (data integrity issue), or any LDAP operation error

func (*LDAP) FindComputerBySAMAccountName

func (l *LDAP) FindComputerBySAMAccountName(sAMAccountName string) (computer *Computer, err error)

FindComputerBySAMAccountName retrieves a computer by its Security Account Manager account name.

Parameters:

  • sAMAccountName: The SAM account name of the computer (e.g., "COMPUTER01$")

Returns:

  • *Computer: The computer object if found
  • error: ErrComputerNotFound if no computer exists with the given sAMAccountName, ErrSAMAccountNameDuplicated if multiple computers have the same sAMAccountName, or any LDAP operation error

This method performs a subtree search starting from the configured BaseDN. Computer sAMAccountNames typically end with a dollar sign ($).

func (*LDAP) FindComputers

func (l *LDAP) FindComputers() (computers []Computer, err error)

FindComputers retrieves all computer objects from the directory.

Returns:

  • []Computer: A slice of all computer objects found in the directory
  • error: Any LDAP operation error

This method performs a subtree search starting from the configured BaseDN. Computers that cannot be parsed (due to missing required attributes) are skipped.

func (*LDAP) FindGroupByDN

func (l *LDAP) FindGroupByDN(dn string) (group *Group, err error)

FindGroupByDN retrieves a group by its distinguished name.

Parameters:

  • dn: The distinguished name of the group (e.g., "CN=Administrators,CN=Builtin,DC=example,DC=com")

Returns:

  • *Group: The group object if found
  • error: ErrGroupNotFound if no group exists with the given DN, ErrDNDuplicated if multiple entries share the same DN (data integrity issue), or any LDAP operation error

func (*LDAP) FindGroups

func (l *LDAP) FindGroups() (groups []Group, err error)

FindGroups retrieves all group objects from the directory.

Returns:

  • []Group: A slice of all group objects found in the directory
  • error: Any LDAP operation error

This method performs a subtree search starting from the configured BaseDN. Groups that cannot be parsed are skipped and not included in the results.

func (*LDAP) FindUserByDN

func (l *LDAP) FindUserByDN(dn string) (user *User, err error)

FindUserByDN retrieves a user by their distinguished name.

Parameters:

  • dn: The distinguished name of the user (e.g., "CN=John Doe,CN=Users,DC=example,DC=com")

Returns:

  • *User: The user object if found
  • error: ErrUserNotFound if no user exists with the given DN, ErrDNDuplicated if multiple entries share the same DN (data integrity issue), or any LDAP operation error

func (*LDAP) FindUserByMail

func (l *LDAP) FindUserByMail(mail string) (user *User, err error)

FindUserByMail retrieves a user by their email address.

Parameters:

  • mail: The email address to search for (e.g., "john.doe@example.com")

Returns:

  • *User: The user object if found
  • error: ErrUserNotFound if no user exists with the given email, ErrMailDuplicated if multiple users have the same email address, or any LDAP operation error

This method performs a subtree search starting from the configured BaseDN.

func (*LDAP) FindUserBySAMAccountName

func (l *LDAP) FindUserBySAMAccountName(sAMAccountName string) (user *User, err error)

FindUserBySAMAccountName retrieves a user by their Security Account Manager account name.

Parameters:

  • sAMAccountName: The SAM account name (e.g., "jdoe" for john.doe@domain.com)

Returns:

  • *User: The user object if found
  • error: ErrUserNotFound if no user exists with the given sAMAccountName, ErrSAMAccountNameDuplicated if multiple users have the same sAMAccountName, or any LDAP operation error

This method performs a subtree search starting from the configured BaseDN.

func (*LDAP) FindUsers

func (l *LDAP) FindUsers() (users []User, err error)

FindUsers retrieves all user objects from the directory.

Returns:

  • []User: A slice of all user objects found in the directory
  • error: Any LDAP operation error

This method performs a subtree search starting from the configured BaseDN. Users that cannot be parsed (due to missing required attributes) are skipped.

func (LDAP) GetConnection

func (l LDAP) GetConnection() (*ldap.Conn, error)

GetConnection establishes and returns an authenticated LDAP connection. The connection must be closed by the caller when no longer needed.

Returns:

  • *ldap.Conn: An authenticated LDAP connection
  • error: Any error encountered during connection or authentication

The returned connection is ready for LDAP operations. Always defer Close() on the connection:

conn, err := client.GetConnection()
if err != nil {
    return err
}
defer conn.Close()

func (*LDAP) RemoveUserFromGroup

func (l *LDAP) RemoveUserFromGroup(dn, groupDN string) error

RemoveUserFromGroup removes a user from a group by modifying the group's member attribute.

Parameters:

  • dn: The distinguished name of the user to remove from the group
  • groupDN: The distinguished name of the group to modify

Returns:

  • error: Any LDAP operation error, including insufficient permissions or if the user is not a member

This operation requires write permissions on the target group object.

func (*LDAP) WithCredentials

func (l *LDAP) WithCredentials(dn, password string) (*LDAP, error)

WithCredentials creates a new LDAP client using the same configuration but with different credentials. This is useful for operations that need to be performed with different user privileges.

Parameters:

  • dn: The distinguished name for the new credentials
  • password: The password for the new credentials

Returns:

  • *LDAP: A new LDAP client with updated credentials
  • error: Any error encountered during connection validation

type Object

type Object struct {
	// contains filtered or unexported fields
}

Object represents the base LDAP object with common name and distinguished name.

func (Object) CN

func (o Object) CN() string

CN returns the common name of the object. The common name is the human-readable name component of the distinguished name.

func (Object) DN

func (o Object) DN() string

DN returns the distinguished name of the object. The distinguished name uniquely identifies an object in the LDAP directory tree.

type SamAccountType

type SamAccountType uint32

SamAccountType represents the Security Account Manager account type values used in Active Directory. This enumeration defines the type of account object and is stored in the sAMAccountType attribute.

Reference: https://learn.microsoft.com/en-us/windows/win32/adschema/a-samaccounttype

const (
	// SamDomainObject (0x0) represents a domain object.
	SamDomainObject SamAccountType = 0x0
	// SamGroupObject (0x10000000) represents a security group object.
	SamGroupObject SamAccountType = 0x10000000
	// SamNonSecurityGroupObject (0x10000001) represents a non-security group object.
	SamNonSecurityGroupObject SamAccountType = 0x10000001
	// SamAliasObject (0x20000000) represents an alias object (local group).
	SamAliasObject SamAccountType = 0x20000000
	// SamNonSecurityAliasObject (0x20000001) represents a non-security alias object.
	SamNonSecurityAliasObject SamAccountType = 0x20000001
	// SamUserObject (0x30000000) represents a normal user account (also known as SAM_NORMAL_USER_ACCOUNT).
	SamUserObject SamAccountType = 0x30000000
	// SamMachineAccount (0x30000001) represents a computer/machine account.
	SamMachineAccount SamAccountType = 0x30000001
	// SamTrustAccount (0x30000002) represents an interdomain trust account.
	SamTrustAccount SamAccountType = 0x30000002
	// SamAppBasicGroup (0x40000000) represents an application basic group.
	SamAppBasicGroup SamAccountType = 0x40000000
	// SamAppQueryGroup (0x40000001) represents an application query group.
	SamAppQueryGroup SamAccountType = 0x40000001
	// SamAccountTypeMax (0x7fffffff) represents the maximum account type value.
	SamAccountTypeMax SamAccountType = 0x7fffffff
)

func (SamAccountType) String

func (t SamAccountType) String() string

String returns a human-readable description of the SAM account type.

Returns:

  • string: A descriptive name for the account type, or "Unknown" for unrecognized values

This method is useful for logging and debugging to understand what type of account object is being processed.

type UAC

type UAC struct {
	// LogonScript (0x1) - Execute a logon script for the user
	LogonScript bool
	// AccountDisabled (0x2) - The account is disabled
	AccountDisabled bool
	// HomeDirRequired (0x8) - A home directory is required for the user
	HomeDirRequired bool
	// Lockout (0x10) - The account is locked out (read-only flag, set by the system)
	Lockout bool
	// PasswordNotRequired (0x20) - No password is required for the account
	PasswordNotRequired bool
	// PasswordCantChange (0x40) - The user cannot change their password
	PasswordCantChange bool
	// EncryptedTextPasswordAllowed (0x80) - Allows encrypted text passwords for the account
	EncryptedTextPasswordAllowed bool
	// TempDuplicateAccount (0x100) - This is a temporary duplicate account
	TempDuplicateAccount bool
	// NormalAccount (0x200) - This is a default account type representing a typical user
	NormalAccount bool
	// InterdomainTrustAccount (0x800) - This is a permit to trust account for a system domain that trusts other domains
	InterdomainTrustAccount bool
	// WorkstationTrustAccount (0x1000) - This is a computer account for a computer that is a member of this domain
	WorkstationTrustAccount bool
	// ServerTrustAccount (0x2000) - This is a computer account for a system backup domain controller that is a member of this domain
	ServerTrustAccount bool
	// NoPasswordExpiration (0x10000) - The password for this account does not expire
	NoPasswordExpiration bool
	// MNSLogonAccount (0x20000) - This is an MNS logon account
	MNSLogonAccount bool
	// SmartCardRequired (0x40000) - The user is required to log on using a smart card
	SmartCardRequired bool
	// TrustedForDelegation (0x80000) - The service account (user or computer account) under which a service runs is trusted for Kerberos delegation
	TrustedForDelegation bool
	// NotDelegated (0x100000) - The security context of the user will not be delegated to a service even if the service account is set as trusted for Kerberos delegation
	NotDelegated bool
	// UseDESKeyOnly (0x200000) - Use DES encryption types for keys for this account
	UseDESKeyOnly bool
	// DontRequirePreauth (0x400000) - This account does not require Kerberos pre-authentication for logon
	DontRequirePreauth bool
	// PasswordExpired (0x800000) - The user password has expired
	PasswordExpired bool
	// TrustedToAuthenticateForDelegation (0x1000000) - The account is enabled for delegation; used with the Kerberos constrained delegation feature
	TrustedToAuthenticateForDelegation bool
}

UAC represents the User Account Control flags for Active Directory user and computer accounts. These flags control various security settings and account behaviors.

Reference: https://learn.microsoft.com/en-us/windows/win32/adschema/a-useraccountcontrol

func UACFromUint32

func UACFromUint32(v uint32) UAC

UACFromUint32 creates a UAC struct from a uint32 userAccountControl value. This function decodes the bitmask flags from Active Directory's userAccountControl attribute.

Parameters:

  • v: The uint32 value from the userAccountControl attribute

Returns:

  • UAC: A UAC struct with boolean flags corresponding to the bitmask

Example:

// For a typical enabled user account (0x200 = ADS_UF_NORMAL_ACCOUNT)
uac := UACFromUint32(512)
// uac.NormalAccount will be true, AccountDisabled will be false

func (UAC) String

func (u UAC) String() string

String returns a human-readable representation of the UAC flags. Only flags that are set to true are included in the output string.

Returns:

  • string: A comma-separated list of active UAC flag names

Example output: "NormalAccount, NoPasswordExpiration" If no flags are set, returns an empty string.

func (UAC) Uint32

func (u UAC) Uint32() uint32

Uint32 converts the UAC struct back to a uint32 userAccountControl value. This function encodes the boolean flags into the bitmask format expected by Active Directory.

Returns:

  • uint32: The userAccountControl bitmask value suitable for Active Directory operations

This method is useful when creating or modifying user accounts and need to set the userAccountControl attribute with the appropriate flags.

type User

type User struct {
	Object
	// Enabled indicates whether the user account is enabled (not disabled by userAccountControl).
	Enabled bool
	// SAMAccountName is the Security Account Manager account name (unique identifier for Windows authentication).
	SAMAccountName string
	// Description contains the user's description or notes.
	Description string
	// Mail contains the user's email address (nil if not set).
	Mail *string
	// Groups contains a list of distinguished names (DNs) of groups the user belongs to.
	Groups []string
}

User represents an LDAP user object with common attributes.

Directories

Path Synopsis
examples
authentication command
Package main demonstrates authentication operations using simple-ldap-go
Package main demonstrates authentication operations using simple-ldap-go
basic-usage command
Package main demonstrates basic LDAP operations using simple-ldap-go
Package main demonstrates basic LDAP operations using simple-ldap-go
user-management command
Package main demonstrates user management operations using simple-ldap-go
Package main demonstrates user management operations using simple-ldap-go

Jump to

Keyboard shortcuts

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