package main
import (
"fmt"
"github.com/go-ldap/ldap/v3"
"log"
)
var (
ldapServer = "ldap://localhost:389"
baseDN = "dc=vamdemic,dc=black"
username = "yuta"
password = "password"
bindusername = "cn=admin,dc=vamdemic,dc=black"
bindpassword = "password"
)
// This example shows how a typical application can verify a login attempt
func Example_userAuthentication() {
l, err := ldap.DialURL(ldapServer)
if err != nil {
log.Fatal(err)
}
defer l.Close()
// First bind with a read only user
err = l.Bind(bindusername, bindpassword)
if err != nil {
log.Fatal(err)
}
// Search for the given username
searchRequest := ldap.NewSearchRequest(
baseDN,
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
fmt.Sprintf("(&(objectClass=organizationalPerson)(cn=%s))", username),
[]string{"dn"},
nil,
)
sr, err := l.Search(searchRequest)
if err != nil {
log.Fatal(err)
}
if len(sr.Entries) != 1 {
log.Fatal("User does not exist or too many entries returned")
}
userdn := sr.Entries[0].DN
// Bind as the user to verify their password
err = l.Bind(userdn, password)
if err != nil {
log.Fatal(err)
}
// Rebind as the read only user for any further queries
err = l.Bind(bindusername, bindpassword)
if err != nil {
log.Fatal(err)
}
}
func main() {
Example_userAuthentication()
}