client.go 5.7 KB

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