client.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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 && client.Conn.IsClosing() {
  48. CloseActiveClient(server)
  49. client = nil
  50. }
  51. if client == nil {
  52. client = createClient(server.Url, server.BaseDN, true)
  53. err := client.Bind(server.UserName, server.Password, true)
  54. if err != nil {
  55. logs.Error("Bind fail: %v", err)
  56. return nil, err
  57. }
  58. client.ServerKey = server.Key
  59. ActiveClients[server.Key] = client
  60. }
  61. return client, nil
  62. }
  63. func CloseActiveClient(server *models.LdapServer) {
  64. delete(ActiveClients, server.Key)
  65. client := ActiveClients[server.Key]
  66. if client == nil {
  67. return
  68. }
  69. client.Close()
  70. }
  71. func (c *Client) Close() {
  72. if c.Connected && c.Conn != nil {
  73. c.Conn.Close()
  74. }
  75. }
  76. func (c *Client) Acquire() (*Client, error) {
  77. inter, err := c.pool.Acquire()
  78. if err != nil {
  79. return nil, err
  80. }
  81. return inter.(*Client), err
  82. }
  83. // Bind 验证账号密码?
  84. func (c *Client) Bind(username string, password string, isAdmin bool) error {
  85. err := c.Conn.Bind(username, password)
  86. if err != nil {
  87. logs.Error("GSSAPIBind failed, err:%v", err)
  88. return err
  89. }
  90. if isAdmin {
  91. c.Admin = username
  92. c.Password = password
  93. }
  94. return nil
  95. }
  96. // Search 搜索用户 eg. (&(objectClass=organizationalPerson))
  97. func (c *Client) Search(filter string) ([]*ldap.Entry, error) {
  98. if filter == "" {
  99. filter = "(objectClass=*)"
  100. }
  101. searchRequest := ldap.NewSearchRequest(
  102. c.BaseDN, // The base dn to search
  103. ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
  104. filter, // The filter to apply
  105. []string{"*"}, // A list attributes to retrieve,"dn", "cn", "objectClass",
  106. nil,
  107. )
  108. sr, err := c.Conn.Search(searchRequest)
  109. if err != nil {
  110. logs.Error("search fail : %v", err)
  111. return nil, err
  112. }
  113. return sr.Entries, nil
  114. }
  115. // SearchByAccount 指定账号搜索用户
  116. func (c *Client) SearchByAccount(account string) (*ldap.Entry, error) {
  117. filter := fmt.Sprintf("(&(objectClass=*)(uid=%s))", account)
  118. searchRequest := ldap.NewSearchRequest(
  119. c.BaseDN, // The base dn to search
  120. ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
  121. filter, // The filter to apply
  122. []string{"*"}, // A list attributes to retrieve,"dn", "cn", "objectClass",
  123. nil,
  124. )
  125. sr, err := c.Conn.Search(searchRequest)
  126. if err != nil {
  127. logs.Error("search fail : %v", err)
  128. return nil, err
  129. }
  130. if len(sr.Entries) < 1 {
  131. logs.Error("no account found for: %v", account)
  132. }
  133. return sr.Entries[0], nil
  134. }
  135. // 通过管理员修改密码,而非自行修改密码
  136. func (c *Client) ModifyPasswordByAdmin(dn string, newPassword string) error {
  137. passwordModifyRequest := ldap.NewPasswordModifyRequest(dn, "", newPassword)
  138. _, err := c.PasswordModify(passwordModifyRequest)
  139. if err != nil {
  140. logs.Error("Password could not be changed: %s", err.Error())
  141. return err
  142. }
  143. return nil
  144. }
  145. // ModifyPassword 自行修改密码
  146. func (c *Client) ModifyPassword(userDN string, password string, newPassword string) error {
  147. l, err := c.Acquire()
  148. if err != nil {
  149. logs.Error(err)
  150. return err
  151. }
  152. err = l.Bind(userDN, password, false)
  153. if err != nil {
  154. logs.Error(err)
  155. return errors.New("密码验证失败:" + err.Error())
  156. }
  157. passwordModifyRequest := ldap.NewPasswordModifyRequest("", password, newPassword)
  158. _, err = l.PasswordModify(passwordModifyRequest)
  159. if err != nil {
  160. logs.Error("Password could not be changed: %s", err.Error())
  161. }
  162. return nil
  163. }
  164. func (c *Client) Modify() error {
  165. return nil
  166. }
  167. // Add 新增用户
  168. // 搜索指定账号:(&(objectClass=*)(uid=%s))
  169. func (c *Client) Add(user *models.LdapUser) error {
  170. entries, err := c.Search(fmt.Sprintf("(&(objectClass=*)(uid=%s))", user.Account))
  171. if err != nil {
  172. return err
  173. }
  174. if len(entries) > 0 {
  175. entry := entries[0]
  176. if entry.DN != user.DN {
  177. logs.Warn("DN not match: {}, {}", entry.DN, user.DN)
  178. return errors.New("已存在该账号,但DN不相同!")
  179. }
  180. }
  181. var attrs []ldap.EntryAttribute
  182. err = json.Unmarshal([]byte(user.Attributes), &attrs)
  183. if err != nil {
  184. return err
  185. }
  186. isUpdate := len(entries) == 1
  187. if isUpdate {
  188. request := ldap.NewModifyRequest(user.DN, nil)
  189. var attrMap = make(map[string][]string)
  190. for _, attr := range entries[0].Attributes {
  191. attrMap[attr.Name] = attr.Values
  192. }
  193. for _, attr := range attrs {
  194. if attrMap[attr.Name] == nil {
  195. request.Add(attr.Name, attr.Values)
  196. } else {
  197. request.Replace(attr.Name, attr.Values)
  198. }
  199. }
  200. err = c.Conn.Modify(request)
  201. } else {
  202. request := ldap.NewAddRequest(user.DN, nil)
  203. for _, attr := range attrs {
  204. request.Attribute(attr.Name, attr.Values)
  205. }
  206. err = c.Conn.Add(request)
  207. }
  208. if err != nil {
  209. logs.Error("Add fail: %v", err)
  210. }
  211. return err
  212. }
  213. func (c *Client) Authentication(userDN string, password string) error {
  214. client, err := c.Acquire()
  215. if err != nil {
  216. return err
  217. }
  218. err = client.Bind(userDN, password, false)
  219. if err != nil {
  220. logs.Error("GSSAPIBind failed, err:%v", err)
  221. return errors.New("登录失败,账号或者密码不正确!")
  222. }
  223. c.pool.Release(client)
  224. return nil
  225. }