feat: add mutex to ldap service

This commit is contained in:
Stavros
2025-09-02 00:08:19 +03:00
parent b9e35716ac
commit 5184c96e85

View File

@@ -4,6 +4,7 @@ import (
"context" "context"
"crypto/tls" "crypto/tls"
"fmt" "fmt"
"sync"
"time" "time"
"github.com/cenkalti/backoff/v5" "github.com/cenkalti/backoff/v5"
@@ -23,6 +24,7 @@ type LdapServiceConfig struct {
type LdapService struct { type LdapService struct {
Config LdapServiceConfig Config LdapServiceConfig
Conn *ldapgo.Conn Conn *ldapgo.Conn
Mutex sync.RWMutex
} }
func NewLdapService(config LdapServiceConfig) *LdapService { func NewLdapService(config LdapServiceConfig) *LdapService {
@@ -55,6 +57,8 @@ func (ldap *LdapService) Init() error {
} }
func (ldap *LdapService) connect() (*ldapgo.Conn, error) { func (ldap *LdapService) connect() (*ldapgo.Conn, error) {
ldap.Mutex.Lock()
conn, err := ldapgo.DialURL(ldap.Config.Address, ldapgo.DialWithTLSConfig(&tls.Config{ conn, err := ldapgo.DialURL(ldap.Config.Address, ldapgo.DialWithTLSConfig(&tls.Config{
InsecureSkipVerify: ldap.Config.Insecure, InsecureSkipVerify: ldap.Config.Insecure,
MinVersion: tls.VersionTLS12, MinVersion: tls.VersionTLS12,
@@ -68,6 +72,8 @@ func (ldap *LdapService) connect() (*ldapgo.Conn, error) {
return nil, err return nil, err
} }
ldap.Mutex.Unlock()
// Set and return the connection // Set and return the connection
ldap.Conn = conn ldap.Conn = conn
return conn, nil return conn, nil
@@ -86,10 +92,12 @@ func (ldap *LdapService) Search(username string) (string, error) {
nil, nil,
) )
ldap.Mutex.Lock()
searchResult, err := ldap.Conn.Search(searchRequest) searchResult, err := ldap.Conn.Search(searchRequest)
if err != nil { if err != nil {
return "", err return "", err
} }
ldap.Mutex.Unlock()
if len(searchResult.Entries) != 1 { if len(searchResult.Entries) != 1 {
return "", fmt.Errorf("multiple or no entries found for user %s", username) return "", fmt.Errorf("multiple or no entries found for user %s", username)
@@ -100,10 +108,12 @@ func (ldap *LdapService) Search(username string) (string, error) {
} }
func (ldap *LdapService) Bind(userDN string, password string) error { func (ldap *LdapService) Bind(userDN string, password string) error {
ldap.Mutex.Lock()
err := ldap.Conn.Bind(userDN, password) err := ldap.Conn.Bind(userDN, password)
if err != nil { if err != nil {
return err return err
} }
ldap.Mutex.Unlock()
return nil return nil
} }
@@ -118,10 +128,12 @@ func (ldap *LdapService) heartbeat() error {
nil, nil,
) )
ldap.Mutex.Lock()
_, err := ldap.Conn.Search(searchRequest) _, err := ldap.Conn.Search(searchRequest)
if err != nil { if err != nil {
return err return err
} }
ldap.Mutex.Unlock()
// No error means the connection is alive // No error means the connection is alive
return nil return nil