-
Notifications
You must be signed in to change notification settings - Fork 29
/
search.go
82 lines (69 loc) · 2.26 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
package auth
import (
"fmt"
ldap "github.com/go-ldap/ldap/v3"
)
//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) {
search := ldap.NewSearchRequest(
c.Config.BaseDN,
ldap.ScopeWholeSubtree,
ldap.DerefAlways,
sizeLimit,
0,
false,
filter,
attrs,
nil,
)
result, err := c.Conn.Search(search)
if err != nil {
return nil, fmt.Errorf(`Search error "%s": %w`, filter, err)
}
return result.Entries, 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) {
search := ldap.NewSearchRequest(
c.Config.BaseDN,
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 {
return nil, fmt.Errorf(`Search error "%s": more than one entries returned`, filter)
}
}
return nil, fmt.Errorf(`Search error "%s": %w`, filter, err)
}
if len(result.Entries) == 0 {
return nil, fmt.Errorf(`Search error "%s": no entries returned`, filter)
}
return result.Entries[0], nil
}
//GetDN returns the DN for the object with the given attribute value or an error if one occurred.
//attr and value are sanitized.
func (c *Conn) GetDN(attr, value string) (string, error) {
entry, err := c.SearchOne(fmt.Sprintf("(%s=%s)", ldap.EscapeFilter(attr), ldap.EscapeFilter(value)), []string{""})
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.
//attr and value are sanitized.
func (c *Conn) GetAttributes(attr, value string, attrs []string) (*ldap.Entry, error) {
return c.SearchOne(fmt.Sprintf("(%s=%s)", ldap.EscapeFilter(attr), ldap.EscapeFilter(value)), attrs)
}
func (c *Conn) getGroups(dn string) ([]*ldap.Entry, error) {
return c.Search(fmt.Sprintf("(member:%s:=%s)", LDAPMatchingRuleInChain, ldap.EscapeFilter(dn)), []string{""}, 1000)
}