123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- package ldap
- import (
- "fmt"
- "github.com/gogits/gogs/modules/ldap"
- "github.com/gogits/gogs/modules/log"
- )
- type Ldapsource struct {
- Name string
- Host string
- Port int
- UseSSL bool
- BaseDN string
- Attributes string
- Filter string
- MsAdSAFormat string
- Enabled bool
- }
- var (
- Authensource []Ldapsource
- )
- func AddSource(name string, host string, port int, usessl bool, basedn string, attributes string, filter string, msadsaformat string) {
- ldaphost := Ldapsource{name, host, port, usessl, basedn, attributes, filter, msadsaformat, true}
- Authensource = append(Authensource, ldaphost)
- }
- func LoginUser(name, passwd string) (a string, r bool) {
- r = false
- for _, ls := range Authensource {
- a, r = ls.SearchEntry(name, passwd)
- if r {
- return
- }
- }
- return
- }
- func (ls Ldapsource) SearchEntry(name, passwd string) (string, bool) {
- l, err := ldapDial(ls)
- if err != nil {
- log.Error(4, "LDAP Connect error, %s:%v", ls.Host, err)
- ls.Enabled = false
- return "", false
- }
- defer l.Close()
- nx := fmt.Sprintf(ls.MsAdSAFormat, name)
- err = l.Bind(nx, passwd)
- if err != nil {
- log.Debug("LDAP Authan failed for %s, reason: %s", nx, err.Error())
- return "", false
- }
- search := ldap.NewSearchRequest(
- ls.BaseDN,
- ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
- fmt.Sprintf(ls.Filter, name),
- []string{ls.Attributes},
- nil)
- sr, err := l.Search(search)
- if err != nil {
- log.Debug("LDAP Authen OK but not in filter %s", name)
- return "", false
- }
- log.Debug("LDAP Authen OK: %s", name)
- if len(sr.Entries) > 0 {
- r := sr.Entries[0].GetAttributeValue(ls.Attributes)
- return r, true
- }
- return "", true
- }
- func ldapDial(ls Ldapsource) (*ldap.Conn, error) {
- if ls.UseSSL {
- return ldap.DialTLS("tcp", fmt.Sprintf("%s:%d", ls.Host, ls.Port), nil)
- } else {
- return ldap.Dial("tcp", fmt.Sprintf("%s:%d", ls.Host, ls.Port))
- }
- }
|