-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathldap.go
72 lines (58 loc) · 1.72 KB
/
ldap.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package main
import (
"crypto/tls"
"encoding/json"
"errors"
"strings"
"github.com/go-ldap/ldap/v3"
)
func ldapLogin(
url string,
readOnlyUsername string,
readOnlyPassword string,
baseDN string,
filter string,
attributesJSON string,
username string,
password string,
) (bool, error, error) {
l, connectionError := ldap.DialURL(url, ldap.DialWithTLSConfig(&tls.Config{InsecureSkipVerify: true}))
if connectionError != nil {
return false, nil, errors.New("ldap connection failed: " + connectionError.Error())
}
defer l.Close()
readonlyBindError := l.Bind(readOnlyUsername, readOnlyPassword)
if readonlyBindError != nil {
return false, nil, errors.New("ldap readonly user bind failed: " + readonlyBindError.Error())
}
filter = strings.ReplaceAll(filter, ldapUsernamePlaceHolder, username)
var attributes []string
jsonError := json.Unmarshal([]byte(attributesJSON), &attributes)
if jsonError != nil {
return false, nil, errors.New("ldap configure json attributes failed: " + jsonError.Error())
}
// Search for the given username
searchRequest := ldap.NewSearchRequest(
baseDN,
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
filter,
attributes,
nil,
)
searchResult, err := l.Search(searchRequest)
if err != nil {
return false, nil, errors.New("ldap search failed: " + jsonError.Error())
}
count := len(searchResult.Entries)
if count > 1 {
return false, nil, errors.New("to many user returns, check your filter and ldap properties")
}
if count <= 0 {
return false, errors.New("user does not exist"), nil
}
err = l.Bind(searchResult.Entries[0].DN, password)
if err != nil {
return false, errors.New("user dn not found or password is incorrect"), nil
}
return true, nil, nil
}