ghostream/auth/ldap/ldap.go

53 lines
1.1 KiB
Go
Raw Normal View History

2020-10-09 20:36:02 +00:00
// Package ldap provides a LDAP authentification backend
2020-09-22 09:42:57 +00:00
package ldap
2020-09-22 10:54:12 +00:00
import (
"github.com/go-ldap/ldap/v3"
"log"
2020-09-22 10:54:12 +00:00
)
// Options holds package configuration
2020-09-22 09:42:57 +00:00
type Options struct {
Aliases map[string]string
URI string
UserDn string
2020-09-22 09:42:57 +00:00
}
2020-09-22 10:54:12 +00:00
// LDAP authentification backend
type LDAP struct {
Cfg *Options
Conn *ldap.Conn
2020-09-22 10:54:12 +00:00
}
// Login tries to bind to LDAP
// Returns (true, nil) if success
func (a LDAP) Login(username string, password string) (bool, error) {
// Resolve stream alias if necessary
2020-12-06 12:41:17 +00:00
for aliasFor, ok := a.Cfg.Aliases[username]; ok; aliasFor, ok = a.Cfg.Aliases[username] {
log.Printf("[LDAP] Use stream alias %s for username %s", username, aliasFor)
username = aliasFor
}
2020-09-22 10:54:12 +00:00
// Try to bind as user
bindDn := "cn=" + username + "," + a.Cfg.UserDn
err := a.Conn.Bind(bindDn, password)
2020-09-22 10:54:12 +00:00
2020-09-22 14:39:06 +00:00
// Login succeeded if no error
return err == nil, err
2020-09-22 10:54:12 +00:00
}
// Close LDAP connection
func (a LDAP) Close() {
a.Conn.Close()
}
2020-09-22 14:39:06 +00:00
// New instanciates a new LDAP connection
func New(cfg *Options) (LDAP, error) {
backend := LDAP{Cfg: cfg}
// Connect to LDAP server
c, err := ldap.DialURL(backend.Cfg.URI)
backend.Conn = c
return backend, err
}