This commit is contained in:
laodaming 2023-11-15 11:23:50 +08:00
parent 1cc0cc8d72
commit 3ef91f9b93

View File

@ -4,6 +4,10 @@ import (
"context"
"fusenapi/utils/auth"
"fusenapi/utils/basic"
"github.com/go-ldap/ldap/v3"
"log"
"sort"
"strings"
"fusenapi/server/ldap-admin/internal/svc"
"fusenapi/server/ldap-admin/internal/types"
@ -28,10 +32,71 @@ func NewGetDepartmentsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Ge
// 处理进入前逻辑w,r
// func (l *GetDepartmentsLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) {
// }
type mapDnItem struct {
EntryAttribute []*ldap.EntryAttribute `json:"entry_attribute"`
DN string `json:"dn"`
Sort int `json:"sort"`
Child []*mapDnItem `json:"child"`
}
func (l *GetDepartmentsLogic) GetDepartments(req *types.Request, userinfo *auth.UserInfo) (resp *basic.Response) {
// todo 从ldap获取组织架构数据
return nil
searchBase := "dc=fusen,dc=com"
// 创建搜索请求
searchRequest := ldap.NewSearchRequest(
searchBase,
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
"(objectClass=*)",
[]string{ /*"cn", "sn", "givenName", "mail", "telephoneNumber", "department", "title"*/ },
nil,
)
// 执行搜索请求
searchResult, err := l.svcCtx.Ldap.Search(searchRequest)
if err != nil {
log.Fatal(err)
}
mapDN := make(map[string]*mapDnItem)
sortNum := 0
for _, v := range searchResult.Entries {
sortNum++
mapDN[v.DN] = &mapDnItem{
DN: v.DN,
EntryAttribute: v.Attributes,
Sort: sortNum,
Child: make([]*mapDnItem, 0, 100),
}
}
//组织层级关系
minLevel := 0
for dn, v := range mapDN {
sl := strings.Split(dn, ",")
lensl := len(sl)
if lensl < minLevel || minLevel == 0 {
minLevel = lensl
}
//没有父级
if lensl <= 1 {
continue
}
//有父级
parentKey := strings.Join(sl[1:], ",")
if parent, ok := mapDN[parentKey]; ok {
parent.Child = append(parent.Child, v)
//排序
sort.Slice(parent.Child, func(i, j int) bool {
return parent.Child[i].Sort < parent.Child[j].Sort
})
}
}
//只获取最顶层
list := make([]interface{}, 0, len(mapDN))
for dn, v := range mapDN {
sl := strings.Split(dn, ",")
if len(sl) == minLevel {
list = append(list, v)
}
}
return resp.SetStatusWithMessage(basic.CodeOK, "", list)
}
/*