Nuestro burocrata preferido: Sam Lowry https://lowry.sindominio.net
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
lowry/ldap/user.go

122 lines
2.6 KiB

package ldap
import (
"errors"
"fmt"
"log"
5 years ago
"strconv"
"github.com/go-ldap/ldap"
)
5 years ago
//User has the ldap data of the user
type User struct {
DN string
Name string
Shell string
UID int
GID int
Home string
}
// ValidateUser in the ldap
func (l *Ldap) ValidateUser(user string, pass string) error {
conn, err := l.login(user, pass)
if err == nil {
conn.Close()
}
return err
}
// ChangePass changes logged in user's password
func (l *Ldap) ChangePass(user string, oldpass string, newpass string) error {
conn, err := l.login(user, oldpass)
if err != nil {
return err
}
defer conn.Close()
if l.RO {
log.Println("Changing password in read only mode")
return nil
}
5 years ago
passwordModifyRequest := ldap.NewPasswordModifyRequest("", oldpass, newpass)
_, err = conn.PasswordModify(passwordModifyRequest)
5 years ago
return err
}
5 years ago
//ListUsers returns a list of usernames
func (l *Ldap) ListUsers() ([]User, error) {
conn, err := l.connect()
if err != nil {
return nil, err
}
defer conn.Close()
searchRequest := ldap.NewSearchRequest(
"ou=people,"+l.DC,
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
"(&(objectClass=posixAccount))",
[]string{"dn", "uid", "uidNumber", "gidNumber", "loginShell", "homeDirectory"},
nil,
)
sr, err := conn.Search(searchRequest)
if err != nil {
return nil, err
}
users := []User{}
for _, entry := range sr.Entries {
uid, _ := strconv.Atoi(entry.GetAttributeValue("uidNumber"))
gid, _ := strconv.Atoi(entry.GetAttributeValue("gidNumber"))
users = append(users, User{
DN: entry.DN,
Name: entry.GetAttributeValue("uid"),
Shell: entry.GetAttributeValue("loginShell"),
UID: uid,
GID: gid,
Home: entry.GetAttributeValue("homeDirectory"),
})
}
return users, nil
}
func (l *Ldap) login(user string, password string) (*ldap.Conn, error) {
conn, err := l.connect()
if err != nil {
return nil, err
}
entry, err := l.searchUser(user, conn)
if err != nil {
conn.Close()
return nil, err
}
userdn := entry.DN
return conn, conn.Bind(userdn, password)
}
func (l *Ldap) searchUser(user string, conn *ldap.Conn) (entry *ldap.Entry, err error) {
searchRequest := ldap.NewSearchRequest(
"ou=people,"+l.DC,
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
fmt.Sprintf("(&(objectClass=posixAccount)(uid=%s))", ldap.EscapeFilter(user)),
[]string{"dn"},
nil,
)
sr, err := conn.Search(searchRequest)
if err != nil {
return entry, err
}
switch len(sr.Entries) {
case 1:
entry = sr.Entries[0]
return entry, nil
case 0:
return entry, errors.New("No user found")
default:
return entry, errors.New("More than one user found!!!")
}
}