This repository has been archived by the owner on Sep 2, 2021. It is now read-only.
forked from korylprince/go-ad-auth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
search.go
103 lines (89 loc) · 2.46 KB
/
search.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package auth
import (
"fmt"
ldap "gopkg.in/ldap.v2"
)
//Search returns the entries for the given search criteria or an error if one occurred.
func (c *Conn) Search(filter string, attrs []string, sizeLimit int) ([]*ldap.Entry, error) {
answer := []*ldap.Entry{}
searches := []string{c.Config.BaseDN}
if c.Config.SearchDN != nil {
searches = c.Config.SearchDN
}
terr := &AggregatingError{}
for _, s := range searches {
search := ldap.NewSearchRequest(
s,
ldap.ScopeWholeSubtree,
ldap.DerefAlways,
sizeLimit,
0,
false,
filter,
attrs,
nil,
)
result, err := c.Conn.Search(search)
if err != nil {
terr.Errorf(`Search error "%s": %v`, filter, err)
continue
}
answer = append(answer, result.Entries...)
}
// If found no answers and have an error, return it
if len(answer) == 0 && terr != nil {
return nil, terr
}
return answer, nil
}
//SearchOne returns the single entry for the given search criteria or an error if one occurred.
//An error is returned if exactly one entry is not returned.
func (c *Conn) SearchOne(filter string, attrs []string) (*ldap.Entry, error) {
searches := []string{c.Config.BaseDN}
if c.Config.SearchDN != nil {
searches = c.Config.SearchDN
}
terr := &AggregatingError{}
for _, s := range searches {
search := ldap.NewSearchRequest(
s,
ldap.ScopeWholeSubtree,
ldap.DerefAlways,
1,
0,
false,
filter,
attrs,
nil,
)
result, err := c.Conn.Search(search)
if err != nil {
if e, ok := err.(*ldap.Error); ok {
if e.ResultCode == ldap.LDAPResultSizeLimitExceeded {
terr.Errorf(`Search error "%s": more than one entries returned`, filter)
continue
}
}
terr.Errorf(`Search error "%s": %v`, filter, err)
continue
}
if len(result.Entries) == 0 {
terr.Errorf(`Search error "%s": no entries returned`, filter)
continue
}
return result.Entries[0], nil
}
return nil, terr
}
//GetDN returns the DN for the object with the given attribute value or an error if one occurred.
func (c *Conn) GetDN(attr, value string) (string, error) {
entry, err := c.SearchOne(fmt.Sprintf("(%s=%s)", attr, value), nil)
if err != nil {
return "", err
}
return entry.DN, nil
}
//GetAttributes returns the *ldap.Entry with the given attributes for the object with the given attribute value or an error if one occurred.
func (c *Conn) GetAttributes(attr, value string, attrs []string) (*ldap.Entry, error) {
return c.SearchOne(fmt.Sprintf("(%s=%s)", attr, value), attrs)
}