From c1de814a2a7e7b8639c746afca65e12a26b99d78 Mon Sep 17 00:00:00 2001 From: Alexandre Iooss Date: Tue, 22 Sep 2020 14:16:52 +0200 Subject: [PATCH] Use NewLDAP to instanciate LDAP backend --- auth/auth.go | 7 ++++++- auth/ldap/ldap.go | 28 +++++++++++++++++++--------- main.go | 6 +++++- 3 files changed, 30 insertions(+), 11 deletions(-) diff --git a/auth/auth.go b/auth/auth.go index 127c0f0..9503ce3 100644 --- a/auth/auth.go +++ b/auth/auth.go @@ -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") diff --git a/auth/ldap/ldap.go b/auth/ldap/ldap.go index e6d9336..0dba25f 100644 --- a/auth/ldap/ldap.go +++ b/auth/ldap/ldap.go @@ -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 +} diff --git a/main.go b/main.go index 082a919..1c5e666 100644 --- a/main.go +++ b/main.go @@ -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() {