package ldap import ( "errors" "fmt" "github.com/astaxie/beego/logs" "github.com/astaxie/beego/orm" "github.com/go-ldap/ldap/v3" "nginx-ui/server/models" "strings" ) type OrganizeService struct { } // Add Update 保存或者修改 func (c *OrganizeService) Add(body *models.LdapOrganize) (*models.LdapOrganize, error) { server, err := GetServer(body.ServerKey) if err != nil { return nil, err } o := orm.NewOrm() _, err = models.InsertOrUpdate[models.LdapOrganize](o, body) if err != nil { return nil, err } if body.Name == "" { return body, nil } client, err := GetActiveClient(server) if err != nil { return nil, err } entries, err := client.Search(fmt.Sprintf("(&(objectClass=*)(ou=%s))", body.Name)) if err != nil { logs.Error("search fail: %v", err) return body, errors.New("LDAP服务搜索失败!") } if len(entries) > 0 { entry := entries[0] if entry.DN != body.DN { logs.Warn("DN not match: {}, {}", entry.DN, body.DN) return body, errors.New("已存在该组织,但DN不相同!") } } var attrs = make([]*ldap.EntryAttribute, 0) attrs = append(attrs, &ldap.EntryAttribute{ Name: "ou", Values: []string{body.Name}, }) ocList := strings.Split(body.ObjectClass, ",") attrs = append(attrs, &ldap.EntryAttribute{ Name: "objectClass", Values: ocList, }) isUpdate := len(entries) == 1 if isUpdate { request := ldap.NewModifyRequest(body.DN, nil) var attrMap = make(map[string][]string) for _, attr := range entries[0].Attributes { attrMap[attr.Name] = attr.Values } for _, attr := range attrs { if attrMap[attr.Name] == nil { request.Add(attr.Name, attr.Values) } else { request.Replace(attr.Name, attr.Values) } } err = client.Conn.Modify(request) } else { request := ldap.NewAddRequest(body.DN, nil) for _, attr := range attrs { request.Attribute(attr.Name, attr.Values) } err = client.Conn.Add(request) } if err != nil { logs.Error("Add fail: %v", err) } return body, err } // GetDetail 获取详情 func (c *OrganizeService) GetDetail(id int) (*models.LdapOrganize, error) { o := orm.NewOrm() user := models.LdapOrganize{Id: id} err := o.Read(&user, "Id") if err != nil { return nil, err } return &user, nil } // GetList 获取全部组织 func (c *OrganizeService) GetList(serverKey string) ([]models.LdapOrganize, error) { o := orm.NewOrm() qs := o.QueryTable(&models.LdapOrganize{}) qs = qs.Filter("ServerKey", serverKey) qs = qs.OrderBy("-Id") var list []models.LdapOrganize _, err := qs.All(&list) if err != nil { return nil, err } return list, nil }