package main import ( "crypto/md5" "encoding/base64" "encoding/json" "fmt" "log" "github.com/474420502/requests" arraystack "github.com/474420502/structure/stack/array" "github.com/go-ldap/ldap/v3" "github.com/tidwall/gjson" ) var appkey = "dingwzebpctav6l3bvkn" var appsecret = "M_WTqBDk06IS6maj_EHipsvYQe76Led72dTKqceHnVJELJ44KOyG1qV5O6MeX2e_" type Department struct { DepartID int64 Name string DN []string Sub []*Department Member gjson.Result } func main() { ldapconn, err := ldap.DialURL("ldap://ldap.yuandian.com:389") if err != nil { log.Fatal(err) } defer ldapconn.Close() err = ldapconn.Bind("cn=admin,dc=yuandian,dc=com", "yuandianldap123") if err != nil { log.Fatal(err) } ses := requests.NewSession() tp := ses.Get(fmt.Sprintf("https://oapi.dingtalk.com/gettoken?appkey=%s&appsecret=%s", appkey, appsecret)) resp, err := tp.Execute() if err != nil { panic(err) } var rjson map[string]any if err := json.Unmarshal(resp.Content(), &rjson); err != nil { panic(err) } token := rjson["access_token"] log.Println(token) Root := &Department{DepartID: 1, DN: []string{"dn=yuandian", "dn=com"}} stack := arraystack.New[*Department]() stack.Push(Root) for !stack.Empty() { department, _ := stack.Pop() // 获取子部门信息 tp = ses.Post(fmt.Sprintf("https://oapi.dingtalk.com/topapi/v2/department/listsub?access_token=%s", token)) if department.DepartID > 1 { tp.SetBodyAuto(fmt.Sprintf(`{"dept_id": %d}`, department.DepartID)) } resp, err = tp.Execute() if err != nil { panic(err) } listsub := gjson.ParseBytes(resp.Content()).Get("result").Array() for _, sub := range listsub { var dept = &Department{ DepartID: sub.Get("dept_id").Int(), Name: sub.Get("name").String(), } stack.Push(dept) department.Sub = append(department.Sub, dept) } tp = ses.Post(fmt.Sprintf("https://oapi.dingtalk.com/topapi/v2/user/list?access_token=%s", token)) tp.SetBodyAuto(fmt.Sprintf(`{"dept_id": %d, "cursor": 0, "size": 100}`, department.DepartID)) resp, err = tp.Execute() if err != nil { panic(err) } department.Member = gjson.ParseBytes(resp.Content()).Get("result.list") if department.DepartID > 1 { req := ldap.NewAddRequest("cn=haha", nil) req.Attribute("objectClass", []string{"inetOrgPerson", "organizationalPerson", "person", "top"}) req.Attribute("cn", []string{"haha"}) req.Attribute("sn", []string{"eson"}) req.Attribute("displayName", []string{"haha"}) req.Attribute("givenName", []string{"haha"}) req.Attribute("mail", []string{"haha"}) req.Attribute("telephoneNumber", []string{"18588505404"}) md5hash := md5.New() md5hash.Write([]byte("18588505404")) pwd := base64.StdEncoding.EncodeToString(md5hash.Sum(nil)) log.Println(pwd) req.Attribute("userPassword", []string{"{MD5}" + pwd}) err = ldapconn.Add(req) if err != nil { panic(err) } } log.Println(string(resp.Content())) } log.Println(Root) }