Use NewLDAP to instanciate LDAP backend

This commit is contained in:
Alexandre Iooss 2020-09-22 14:16:52 +02:00
parent 07c8dc6ca1
commit c1de814a2a
3 changed files with 30 additions and 11 deletions

View File

@ -15,14 +15,19 @@ type Options struct {
// Backend to log user in
type Backend interface {
Login(string, string) (bool, error)
Close()
}
// New initialize authentification backend
func New(cfg *Options) (Backend, error) {
var backend Backend
var err error
if cfg.Backend == "LDAP" {
backend = ldap.LDAP{Cfg: cfg.LDAP}
backend, err = ldap.NewLDAP(&cfg.LDAP)
if err != nil {
return nil, err
}
} else {
// Package is misconfigured
return nil, errors.New("Authentification backend not found")

View File

@ -12,21 +12,16 @@ type Options struct {
// LDAP authentification backend
type LDAP struct {
Cfg Options
Cfg *Options
Conn *ldap.Conn
}
// Login tries to bind to LDAP
// Returns (true, nil) if success
func (a LDAP) Login(username string, password string) (bool, error) {
// Connect to LDAP server
l, err := ldap.DialURL(a.Cfg.URI)
if err != nil {
return false, err
}
defer l.Close()
// Try to bind as user
err = l.Bind("cn=username,dc=example,dc=com", password)
bindDn := "cn=" + username + "," + a.Cfg.UserDn
err := a.Conn.Bind(bindDn, password)
if err != nil {
return false, err
}
@ -34,3 +29,18 @@ func (a LDAP) Login(username string, password string) (bool, error) {
// Login succeeded
return true, nil
}
// Close LDAP connection
func (a LDAP) Close() {
a.Conn.Close()
}
// NewLDAP instanciate a new LDAP connection
func NewLDAP(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
}

View File

@ -62,7 +62,11 @@ func main() {
}
// Init authentification
//authBackend := auth.New(&cfg.Auth)
authBackend, err := auth.New(&cfg.Auth)
if err != nil {
log.Fatalln("Failed to load authentification backend:", err)
}
defer authBackend.Close()
// Start web server routine
go func() {