modify.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Copyright 2014 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package main
  5. import (
  6. "errors"
  7. "fmt"
  8. "log"
  9. "github.com/gogits/gogs/modules/ldap"
  10. )
  11. var (
  12. LdapServer string = "localhost"
  13. LdapPort uint16 = 389
  14. BaseDN string = "dc=enterprise,dc=org"
  15. BindDN string = "cn=admin,dc=enterprise,dc=org"
  16. BindPW string = "enterprise"
  17. Filter string = "(cn=kirkj)"
  18. )
  19. func search(l *ldap.Conn, filter string, attributes []string) (*ldap.Entry, *ldap.Error) {
  20. search := ldap.NewSearchRequest(
  21. BaseDN,
  22. ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
  23. filter,
  24. attributes,
  25. nil)
  26. sr, err := l.Search(search)
  27. if err != nil {
  28. log.Fatalf("ERROR: %s\n", err)
  29. return nil, err
  30. }
  31. log.Printf("Search: %s -> num of entries = %d\n", search.Filter, len(sr.Entries))
  32. if len(sr.Entries) == 0 {
  33. return nil, ldap.NewError(ldap.ErrorDebugging, errors.New(fmt.Sprintf("no entries found for: %s", filter)))
  34. }
  35. return sr.Entries[0], nil
  36. }
  37. func main() {
  38. l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", LdapServer, LdapPort))
  39. if err != nil {
  40. log.Fatalf("ERROR: %s\n", err.Error())
  41. }
  42. defer l.Close()
  43. // l.Debug = true
  44. l.Bind(BindDN, BindPW)
  45. log.Printf("The Search for Kirk ... %s\n", Filter)
  46. entry, err := search(l, Filter, []string{})
  47. if err != nil {
  48. log.Fatal("could not get entry")
  49. }
  50. entry.PrettyPrint(0)
  51. log.Printf("modify the mail address and add a description ... \n")
  52. modify := ldap.NewModifyRequest(entry.DN)
  53. modify.Add("description", []string{"Captain of the USS Enterprise"})
  54. modify.Replace("mail", []string{"captain@enterprise.org"})
  55. if err := l.Modify(modify); err != nil {
  56. log.Fatalf("ERROR: %s\n", err.Error())
  57. }
  58. entry, err = search(l, Filter, []string{})
  59. if err != nil {
  60. log.Fatal("could not get entry")
  61. }
  62. entry.PrettyPrint(0)
  63. log.Printf("reset the entry ... \n")
  64. modify = ldap.NewModifyRequest(entry.DN)
  65. modify.Delete("description", []string{})
  66. modify.Replace("mail", []string{"james.kirk@enterprise.org"})
  67. if err := l.Modify(modify); err != nil {
  68. log.Fatalf("ERROR: %s\n", err.Error())
  69. }
  70. entry, err = search(l, Filter, []string{})
  71. if err != nil {
  72. log.Fatal("could not get entry")
  73. }
  74. entry.PrettyPrint(0)
  75. }