client.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. package ldap
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "github.com/astaxie/beego/logs"
  7. "github.com/go-ldap/ldap/v3"
  8. "nginx-ui/server/models"
  9. )
  10. type Client struct {
  11. *ldap.Conn
  12. Url string
  13. Connected bool
  14. BaseDN string
  15. Admin string
  16. Password string
  17. ServerKey string
  18. pool *ConnectionPool
  19. }
  20. var ActiveClients = make(map[string]*Client)
  21. func createClient(url string, baseDN string, createPool bool) *Client {
  22. var client = &Client{
  23. Url: url,
  24. BaseDN: baseDN,
  25. }
  26. if createPool {
  27. client.pool = NewConnectionPool(5, func() (interface{}, error) {
  28. c := createClient(url, baseDN, false)
  29. if c.Connected {
  30. return c, nil
  31. }
  32. return nil, errors.New("连接服务失败!")
  33. })
  34. }
  35. conn, err := ldap.DialURL(client.Url)
  36. if err != nil {
  37. logs.Error("dialUrl fail: %v", err)
  38. client.Connected = false
  39. } else {
  40. client.Conn = conn
  41. client.Connected = true
  42. }
  43. return client
  44. }
  45. func GetActiveClient(server *models.LdapServer) (*Client, error) {
  46. client := ActiveClients[server.Key]
  47. if client == nil {
  48. client = createClient(server.Url, server.BaseDN, true)
  49. err := client.Bind(server.UserName, server.Password, true)
  50. if err != nil {
  51. logs.Error("Bind fail: %v", err)
  52. return nil, err
  53. }
  54. client.ServerKey = server.Key
  55. ActiveClients[server.Key] = client
  56. }
  57. return client, nil
  58. }
  59. func (c *Client) Close() {
  60. if c.Connected && c.Conn != nil {
  61. c.Conn.Close()
  62. }
  63. }
  64. func (c *Client) Acquire() (*Client, error) {
  65. inter, err := c.pool.Acquire()
  66. if err != nil {
  67. return nil, err
  68. }
  69. return inter.(*Client), err
  70. }
  71. // Bind 验证账号密码?
  72. func (c *Client) Bind(username string, password string, isAdmin bool) error {
  73. err := c.Conn.Bind(username, password)
  74. if err != nil {
  75. logs.Error("GSSAPIBind failed, err:%v", err)
  76. return err
  77. }
  78. if isAdmin {
  79. c.Admin = username
  80. c.Password = password
  81. }
  82. return nil
  83. }
  84. func createUser(entry *ldap.Entry) models.LdapUser {
  85. user := models.LdapUser{
  86. Account: entry.GetAttributeValue("uid"),
  87. DN: entry.DN,
  88. Password: entry.GetAttributeValue("userPassword"),
  89. UserName: entry.GetAttributeValue("cn"),
  90. Mail: entry.GetAttributeValue("mail"),
  91. }
  92. jsonBytes, err := json.Marshal(entry.Attributes)
  93. if err != nil {
  94. logs.Error("marshal fail : %v", err)
  95. user.Remark = "attributes marshal fail: " + err.Error()
  96. } else {
  97. user.Attributes = string(jsonBytes)
  98. }
  99. return user
  100. }
  101. // Search 搜索用户 eg. (&(objectClass=organizationalPerson))
  102. func (c *Client) Search(filter string) ([]models.LdapUser, error) {
  103. if filter == "" {
  104. filter = "(objectClass=*)"
  105. }
  106. searchRequest := ldap.NewSearchRequest(
  107. c.BaseDN, // The base dn to search
  108. ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
  109. filter, // The filter to apply
  110. []string{"*"}, // A list attributes to retrieve,"dn", "cn", "objectClass",
  111. nil,
  112. )
  113. sr, err := c.Conn.Search(searchRequest)
  114. if err != nil {
  115. logs.Error("search fail : %v", err)
  116. return nil, err
  117. }
  118. var users []models.LdapUser
  119. for _, entry := range sr.Entries {
  120. user := createUser(entry)
  121. user.ServerKey = c.ServerKey
  122. users = append(users, user)
  123. }
  124. return users, nil
  125. }
  126. // 通过管理员修改密码,而非自行修改密码
  127. func (c *Client) ModifyPasswordByAdmin(dn string, newPassword string) error {
  128. passwordModifyRequest := ldap.NewPasswordModifyRequest(dn, "", newPassword)
  129. _, err := c.PasswordModify(passwordModifyRequest)
  130. if err != nil {
  131. logs.Error("Password could not be changed: %s", err.Error())
  132. return err
  133. }
  134. return nil
  135. }
  136. // ModifyPassword 自行修改密码
  137. func (c *Client) ModifyPassword(userDN string, password string, newPassword string) error {
  138. l, err := c.Acquire()
  139. if err != nil {
  140. logs.Error(err)
  141. return err
  142. }
  143. err = l.Bind(userDN, password, false)
  144. if err != nil {
  145. logs.Error(err)
  146. return errors.New("密码验证失败:" + err.Error())
  147. }
  148. passwordModifyRequest := ldap.NewPasswordModifyRequest("", password, newPassword)
  149. _, err = l.PasswordModify(passwordModifyRequest)
  150. if err != nil {
  151. logs.Error("Password could not be changed: %s", err.Error())
  152. }
  153. return nil
  154. }
  155. func (c *Client) Modify() error {
  156. return nil
  157. }
  158. func (c *Client) Authentication(account string, password string) (*models.LdapUser, error) {
  159. // The username and password we want to check
  160. users, err := c.Search(fmt.Sprintf("(&(objectClass=*)(uid=%s))", ldap.EscapeFilter(account)))
  161. if err != nil {
  162. logs.Error("search fail: %v", err)
  163. return nil, err
  164. }
  165. if len(users) != 1 {
  166. logs.Error("User does not exist or too many entries returned")
  167. return nil, errors.New("未找到用户或者账号重复!")
  168. }
  169. userDN := users[0].DN
  170. client, err := c.Acquire()
  171. if err != nil {
  172. return nil, err
  173. }
  174. err = client.Bind(userDN, password, false)
  175. if err != nil {
  176. logs.Error("GSSAPIBind failed, err:%v", err)
  177. return nil, errors.New("登录失败,账号或者密码不正确!")
  178. }
  179. c.pool.Release(client)
  180. return &users[0], nil
  181. }