- multi-round user filters (config filter first, then objectClass=inetOrgPerson, then AD sAMAccountName/userPrincipalName fallback) applied to login search, user listing and batch import; previously pure-AD directories found no users - attribute fallback chains (uid/sAMAccountName/userPrincipalName, cn/displayName, telephoneNumber/mobile) via ldapEntryAttr - import errors explain likely cause instead of empty result - AES-encrypted admin password kept (aiops stores plaintext) - frontend gating per aiops pattern: LDAP account management panel hidden with hint until a config is actually saved (was gated on unsaved form values); batch-import modal hides to/from-LDAP tabs when unconfigured, local CSV always available
682 lines
17 KiB
Go
682 lines
17 KiB
Go
package handler
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"sql-platform/internal/handler/resp"
|
|
"sql-platform/internal/model"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/go-ldap/ldap/v3"
|
|
)
|
|
|
|
// GET /api/v1/ldap-config
|
|
func GetLDAPConfig(c *gin.Context) {
|
|
var configs []model.LDAPConfig
|
|
model.DB.Order("id").Find(&configs)
|
|
if len(configs) == 0 {
|
|
c.JSON(http.StatusOK, nil)
|
|
return
|
|
}
|
|
cfg := configs[0]
|
|
// mask password in response
|
|
cfg.AdminPassword = "******"
|
|
|
|
// Parse user_mapping from JSON string to object for frontend
|
|
type ldapResponse struct {
|
|
model.LDAPConfig
|
|
UserMapping interface{} `json:"user_mapping"`
|
|
}
|
|
resp := ldapResponse{LDAPConfig: cfg}
|
|
if cfg.UserMapping != nil && *cfg.UserMapping != "" {
|
|
var mapping map[string]string
|
|
json.Unmarshal([]byte(*cfg.UserMapping), &mapping)
|
|
resp.UserMapping = mapping
|
|
} else {
|
|
resp.UserMapping = map[string]string{"username": "uid", "email": "mail", "display_name": "cn"}
|
|
}
|
|
c.JSON(http.StatusOK, resp)
|
|
}
|
|
|
|
// PUT /api/v1/ldap-config
|
|
func UpdateLDAPConfig(c *gin.Context) {
|
|
var input map[string]interface{}
|
|
if err := c.ShouldBindJSON(&input); err != nil {
|
|
resp.BadRequest(c, err.Error())
|
|
return
|
|
}
|
|
|
|
var configs []model.LDAPConfig
|
|
model.DB.Order("id").Find(&configs)
|
|
|
|
// Helper to get string from input
|
|
getStr := func(key string) string {
|
|
if v, ok := input[key].(string); ok {
|
|
return v
|
|
}
|
|
return ""
|
|
}
|
|
getInt := func(key string) int {
|
|
if v, ok := input[key].(float64); ok {
|
|
return int(v)
|
|
}
|
|
return 0
|
|
}
|
|
getBool := func(key string) *bool {
|
|
if v, ok := input[key].(bool); ok {
|
|
return &v
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Serialize user_mapping to JSON string
|
|
userMappingStr := ""
|
|
if um, ok := input["user_mapping"]; ok {
|
|
if bytes, err := json.Marshal(um); err == nil {
|
|
userMappingStr = string(bytes)
|
|
}
|
|
}
|
|
|
|
if len(configs) == 0 {
|
|
// Create new config
|
|
cfg := model.LDAPConfig{
|
|
LDAPHost: getStr("ldap_host"),
|
|
AdminDN: getStr("admin_dn"),
|
|
BaseDN: getStr("base_dn"),
|
|
SearchFilter: func() *string {
|
|
s := getStr("search_filter")
|
|
if s != "" {
|
|
return &s
|
|
}
|
|
return nil
|
|
}(),
|
|
UserMapping: func() *string {
|
|
s := userMappingStr
|
|
if s != "" {
|
|
return &s
|
|
}
|
|
return nil
|
|
}(),
|
|
}
|
|
if port := getInt("ldap_port"); port > 0 {
|
|
cfg.LDAPPort = &port
|
|
}
|
|
if b := getBool("use_ldaps"); b != nil {
|
|
cfg.UseLDAPS = b
|
|
}
|
|
if pw := getStr("admin_password"); pw != "" && pw != "******" {
|
|
encPw, _ := encryptPassword(pw)
|
|
cfg.AdminPassword = encPw
|
|
}
|
|
model.DB.Create(&cfg)
|
|
cfg.AdminPassword = "******"
|
|
c.JSON(http.StatusOK, cfg)
|
|
} else {
|
|
// Update existing
|
|
cfg := configs[0]
|
|
updates := map[string]interface{}{}
|
|
|
|
if v := getStr("ldap_host"); v != "" {
|
|
updates["ldap_host"] = v
|
|
}
|
|
if v := getStr("base_dn"); v != "" {
|
|
updates["base_dn"] = v
|
|
}
|
|
if v := getStr("admin_dn"); v != "" {
|
|
updates["admin_dn"] = v
|
|
}
|
|
if v := getStr("search_filter"); v != "" {
|
|
updates["search_filter"] = v
|
|
}
|
|
if userMappingStr != "" {
|
|
updates["user_mapping"] = userMappingStr
|
|
}
|
|
if v := getStr("admin_password"); v != "" && v != "******" {
|
|
encPw, _ := encryptPassword(v)
|
|
updates["admin_password"] = encPw
|
|
}
|
|
if port := getInt("ldap_port"); port > 0 {
|
|
updates["ldap_port"] = port
|
|
}
|
|
if b := getBool("use_ldaps"); b != nil {
|
|
updates["use_ldaps"] = *b
|
|
}
|
|
if len(updates) > 0 {
|
|
model.DB.Model(&cfg).Updates(updates)
|
|
}
|
|
model.DB.First(&cfg, cfg.ID)
|
|
cfg.AdminPassword = "******"
|
|
c.JSON(http.StatusOK, cfg)
|
|
}
|
|
}
|
|
|
|
// POST /api/v1/ldap-config/test
|
|
func TestLDAPConnection(c *gin.Context) {
|
|
var req struct {
|
|
TestUser string `json:"test_user"`
|
|
TestPassword string `json:"test_password"`
|
|
}
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
resp.BadRequest(c, err.Error())
|
|
return
|
|
}
|
|
|
|
var cfg model.LDAPConfig
|
|
if err := model.DB.Order("id").First(&cfg).Error; err != nil {
|
|
resp.NotFound(c, "LDAP 配置不存在,请先保存配置")
|
|
return
|
|
}
|
|
if cfg.LDAPHost == "" {
|
|
c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": "LDAP 未配置"})
|
|
return
|
|
}
|
|
|
|
// Connect
|
|
conn, err := dialLDAP(&cfg)
|
|
if err != nil {
|
|
c.JSON(http.StatusOK, gin.H{"success": false, "message": fmt.Sprintf("连接失败: %s", err)})
|
|
return
|
|
}
|
|
defer conn.Close()
|
|
|
|
// Admin bind (decrypt password)
|
|
adminPw, _ := decryptPassword(cfg.AdminPassword)
|
|
if err := conn.Bind(cfg.AdminDN, adminPw); err != nil {
|
|
c.JSON(http.StatusOK, gin.H{"success": false, "message": fmt.Sprintf("管理员绑定失败: %s", err)})
|
|
return
|
|
}
|
|
|
|
// If test_user provided, search and verify
|
|
if req.TestUser != "" && req.TestPassword != "" && req.TestPassword != "__use_stored__" {
|
|
userFilter := ""
|
|
if cfg.SearchFilter != nil && *cfg.SearchFilter != "" {
|
|
sf := *cfg.SearchFilter
|
|
if strings.Contains(sf, "%s") {
|
|
userFilter = strings.ReplaceAll(sf, "%s", ldap.EscapeFilter(req.TestUser))
|
|
} else {
|
|
userFilter = fmt.Sprintf("(&%s(uid=%s))", sf, ldap.EscapeFilter(req.TestUser))
|
|
}
|
|
} else {
|
|
userFilter = fmt.Sprintf("(uid=%s)", ldap.EscapeFilter(req.TestUser))
|
|
}
|
|
|
|
sr, err := conn.Search(ldap.NewSearchRequest(
|
|
cfg.BaseDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases,
|
|
1, 10, false, userFilter,
|
|
[]string{"uid", "cn", "mail", "telephoneNumber", "title", "department", "memberOf", "distinguishedName"},
|
|
nil,
|
|
))
|
|
if err != nil || len(sr.Entries) == 0 {
|
|
c.JSON(http.StatusOK, gin.H{"success": false, "message": fmt.Sprintf("未找到用户: %s", req.TestUser)})
|
|
return
|
|
}
|
|
entry := sr.Entries[0]
|
|
userDN := entry.DN
|
|
|
|
// Verify password
|
|
if err := conn.Bind(userDN, req.TestPassword); err != nil {
|
|
c.JSON(http.StatusOK, gin.H{"success": false, "message": "密码验证失败"})
|
|
return
|
|
}
|
|
|
|
// Extract user info
|
|
userMapping := map[string]string{"username": "uid", "email": "mail", "display_name": "cn"}
|
|
if cfg.UserMapping != nil && *cfg.UserMapping != "" {
|
|
json.Unmarshal([]byte(*cfg.UserMapping), &userMapping)
|
|
}
|
|
|
|
userInfo := map[string]string{
|
|
"User lookup": "successful",
|
|
"User ID": entry.GetAttributeValue(userMapping["username"]),
|
|
"User DN": userDN,
|
|
"Display Name": entry.GetAttributeValue(userMapping["display_name"]),
|
|
"Email": entry.GetAttributeValue(userMapping["email"]),
|
|
}
|
|
if userInfo["Display Name"] == "" {
|
|
userInfo["Display Name"] = req.TestUser
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"success": true,
|
|
"message": fmt.Sprintf("用户 %s 验证通过", req.TestUser),
|
|
"user_info": userInfo,
|
|
})
|
|
return
|
|
}
|
|
|
|
// Just test server connection
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"success": true,
|
|
"message": fmt.Sprintf("LDAP 服务器 %s 连接成功", cfg.LDAPHost),
|
|
})
|
|
}
|
|
|
|
// POST /api/v1/ldap-config/ou-list
|
|
func ListLDAPOUs(c *gin.Context) {
|
|
var cfg model.LDAPConfig
|
|
if err := model.DB.Order("id").First(&cfg).Error; err != nil {
|
|
c.JSON(http.StatusOK, []interface{}{})
|
|
return
|
|
}
|
|
|
|
conn, err := dialLDAP(&cfg)
|
|
if err != nil {
|
|
c.JSON(http.StatusOK, []interface{}{})
|
|
return
|
|
}
|
|
defer conn.Close()
|
|
|
|
adminPw, _ := decryptPassword(cfg.AdminPassword)
|
|
if err := conn.Bind(cfg.AdminDN, adminPw); err != nil {
|
|
c.JSON(http.StatusOK, []interface{}{})
|
|
return
|
|
}
|
|
|
|
sr, err := conn.Search(ldap.NewSearchRequest(
|
|
cfg.BaseDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases,
|
|
100, 0, false, "(objectClass=organizationalUnit)",
|
|
[]string{"ou", "dn", "description"},
|
|
nil,
|
|
))
|
|
if err != nil {
|
|
c.JSON(http.StatusOK, []interface{}{})
|
|
return
|
|
}
|
|
|
|
type OuItem struct {
|
|
DN string `json:"dn"`
|
|
Name string `json:"name"`
|
|
}
|
|
var items []OuItem
|
|
for _, e := range sr.Entries {
|
|
items = append(items, OuItem{
|
|
DN: e.DN,
|
|
Name: e.GetAttributeValue("ou"),
|
|
})
|
|
}
|
|
c.JSON(http.StatusOK, items)
|
|
}
|
|
|
|
// POST /api/v1/ldap-config/user-list
|
|
func ListLDAPUsers(c *gin.Context) {
|
|
var req struct {
|
|
OuDn string `json:"ou_dn"`
|
|
}
|
|
c.ShouldBindJSON(&req)
|
|
|
|
var cfg model.LDAPConfig
|
|
if err := model.DB.Order("id").First(&cfg).Error; err != nil {
|
|
c.JSON(http.StatusOK, []interface{}{})
|
|
return
|
|
}
|
|
|
|
conn, err := dialLDAP(&cfg)
|
|
if err != nil {
|
|
c.JSON(http.StatusOK, []interface{}{})
|
|
return
|
|
}
|
|
defer conn.Close()
|
|
|
|
adminPw2, _ := decryptPassword(cfg.AdminPassword)
|
|
if err := conn.Bind(cfg.AdminDN, adminPw2); err != nil {
|
|
c.JSON(http.StatusOK, []interface{}{})
|
|
return
|
|
}
|
|
|
|
searchBase := cfg.BaseDN
|
|
if req.OuDn != "" {
|
|
searchBase = req.OuDn
|
|
}
|
|
|
|
// 多轮过滤器(配置优先 → OpenLDAP → AD 兜底),命中后去重合并
|
|
type LdapUser struct {
|
|
DN string `json:"dn"`
|
|
UID string `json:"uid"`
|
|
CN string `json:"cn"`
|
|
Mail string `json:"mail"`
|
|
}
|
|
seen := map[string]bool{}
|
|
var users []LdapUser
|
|
for _, filter := range ldapUserListFilters(&cfg) {
|
|
sr, err := conn.Search(ldap.NewSearchRequest(
|
|
searchBase, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases,
|
|
200, 0, false, filter,
|
|
[]string{"uid", "sAMAccountName", "userPrincipalName", "cn", "displayName", "mail", "dn"},
|
|
nil,
|
|
))
|
|
if err != nil {
|
|
continue
|
|
}
|
|
for _, e := range sr.Entries {
|
|
if seen[e.DN] {
|
|
continue
|
|
}
|
|
seen[e.DN] = true
|
|
uid, cn, mail := ldapIdentityFromEntry(e, "")
|
|
users = append(users, LdapUser{DN: e.DN, UID: uid, CN: cn, Mail: mail})
|
|
}
|
|
}
|
|
c.JSON(http.StatusOK, users)
|
|
}
|
|
|
|
// POST /api/v1/ldap-config/create-ou
|
|
func CreateLDAPOU(c *gin.Context) {
|
|
var req struct {
|
|
OuName string `json:"ou_name"`
|
|
ParentDN string `json:"parent_dn"`
|
|
Description string `json:"description"`
|
|
}
|
|
if err := c.ShouldBindJSON(&req); err != nil || req.OuName == "" {
|
|
resp.BadRequest(c, "缺少 ou_name 参数")
|
|
return
|
|
}
|
|
|
|
var cfg model.LDAPConfig
|
|
if err := model.DB.Order("id").First(&cfg).Error; err != nil {
|
|
resp.BadRequest(c, "LDAP 配置不存在")
|
|
return
|
|
}
|
|
|
|
conn, err := dialLDAP(&cfg)
|
|
if err != nil {
|
|
resp.BadRequest(c, "LDAP 连接失败: "+err.Error())
|
|
return
|
|
}
|
|
defer conn.Close()
|
|
|
|
adminPw, _ := decryptPassword(cfg.AdminPassword)
|
|
if err := conn.Bind(cfg.AdminDN, adminPw); err != nil {
|
|
resp.BadRequest(c, "LDAP 管理员绑定失败")
|
|
return
|
|
}
|
|
|
|
ouDN := fmt.Sprintf("ou=%s,%s", ldap.EscapeFilter(req.OuName), req.ParentDN)
|
|
addReq := ldap.NewAddRequest(ouDN, nil)
|
|
addReq.Attribute("objectClass", []string{"organizationalUnit", "top"})
|
|
addReq.Attribute("ou", []string{req.OuName})
|
|
if req.Description != "" {
|
|
addReq.Attribute("description", []string{req.Description})
|
|
}
|
|
|
|
if err := conn.Add(addReq); err != nil {
|
|
resp.BadRequest(c, "创建 OU 失败: "+err.Error())
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{"message": fmt.Sprintf("OU %s 创建成功", req.OuName), "dn": ouDN})
|
|
}
|
|
|
|
// POST /api/v1/ldap-config/create-user
|
|
func CreateLDAPUser(c *gin.Context) {
|
|
var req struct {
|
|
Username string `json:"username"`
|
|
DisplayName string `json:"display_name"`
|
|
Email string `json:"email"`
|
|
Password string `json:"password"`
|
|
OuDn string `json:"ou_dn"`
|
|
}
|
|
if err := c.ShouldBindJSON(&req); err != nil || req.Username == "" || req.Password == "" {
|
|
resp.BadRequest(c, "缺少 username 或 password 参数")
|
|
return
|
|
}
|
|
|
|
var cfg model.LDAPConfig
|
|
if err := model.DB.Order("id").First(&cfg).Error; err != nil {
|
|
resp.BadRequest(c, "LDAP 配置不存在")
|
|
return
|
|
}
|
|
|
|
// Parse user_mapping for attribute names
|
|
userMapping := map[string]string{"username": "uid", "email": "mail", "display_name": "cn"}
|
|
if cfg.UserMapping != nil && *cfg.UserMapping != "" {
|
|
json.Unmarshal([]byte(*cfg.UserMapping), &userMapping)
|
|
}
|
|
|
|
conn, err := dialLDAP(&cfg)
|
|
if err != nil {
|
|
resp.BadRequest(c, "LDAP 连接失败: "+err.Error())
|
|
return
|
|
}
|
|
defer conn.Close()
|
|
|
|
adminPw, _ := decryptPassword(cfg.AdminPassword)
|
|
if err := conn.Bind(cfg.AdminDN, adminPw); err != nil {
|
|
resp.BadRequest(c, "LDAP 管理员绑定失败")
|
|
return
|
|
}
|
|
|
|
uidAttr := userMapping["username"]
|
|
if uidAttr == "" {
|
|
uidAttr = "uid"
|
|
}
|
|
cnAttr := userMapping["display_name"]
|
|
if cnAttr == "" {
|
|
cnAttr = "cn"
|
|
}
|
|
mailAttr := userMapping["email"]
|
|
if mailAttr == "" {
|
|
mailAttr = "mail"
|
|
}
|
|
|
|
userDN := fmt.Sprintf("%s=%s,%s", uidAttr, ldap.EscapeFilter(req.Username), req.OuDn)
|
|
displayName := req.DisplayName
|
|
if displayName == "" {
|
|
displayName = req.Username
|
|
}
|
|
|
|
addReq := ldap.NewAddRequest(userDN, nil)
|
|
addReq.Attribute("objectClass", []string{"inetOrgPerson", "organizationalPerson", "person", "top"})
|
|
addReq.Attribute(uidAttr, []string{req.Username})
|
|
addReq.Attribute(cnAttr, []string{displayName})
|
|
addReq.Attribute("sn", []string{displayName})
|
|
addReq.Attribute("userPassword", []string{req.Password})
|
|
if req.Email != "" {
|
|
addReq.Attribute(mailAttr, []string{req.Email})
|
|
}
|
|
|
|
if err := conn.Add(addReq); err != nil {
|
|
resp.BadRequest(c, "创建用户失败: "+err.Error())
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{"message": fmt.Sprintf("用户 %s 创建成功", req.Username), "dn": userDN})
|
|
}
|
|
|
|
// POST /api/v1/ldap-config/batch-import-ldap
|
|
func BatchImportLDAP(c *gin.Context) {
|
|
var req struct {
|
|
OuDn string `json:"ou_dn"`
|
|
Role string `json:"role"`
|
|
UserIDs []string `json:"user_ids"`
|
|
}
|
|
c.ShouldBindJSON(&req)
|
|
if req.Role == "" {
|
|
req.Role = "developer"
|
|
}
|
|
|
|
var cfg model.LDAPConfig
|
|
if err := model.DB.Order("id").First(&cfg).Error; err != nil {
|
|
resp.BadRequest(c, "LDAP 配置不存在")
|
|
return
|
|
}
|
|
|
|
conn, err := dialLDAP(&cfg)
|
|
if err != nil {
|
|
resp.BadRequest(c, "LDAP 连接失败: "+err.Error())
|
|
return
|
|
}
|
|
defer conn.Close()
|
|
|
|
adminPw, _ := decryptPassword(cfg.AdminPassword)
|
|
if err := conn.Bind(cfg.AdminDN, adminPw); err != nil {
|
|
resp.BadRequest(c, "LDAP 管理员绑定失败")
|
|
return
|
|
}
|
|
|
|
searchBase := cfg.BaseDN
|
|
if req.OuDn != "" {
|
|
searchBase = req.OuDn
|
|
}
|
|
|
|
// 多轮过滤器搜索(配置优先 → OpenLDAP → AD 兜底),按 DN 去重合并
|
|
type ldapEntryUser struct {
|
|
uid, cn, mail string
|
|
}
|
|
var candidates []ldapEntryUser
|
|
seen := map[string]bool{}
|
|
for _, filter := range ldapUserListFilters(&cfg) {
|
|
sr, err := conn.Search(ldap.NewSearchRequest(
|
|
searchBase, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases,
|
|
500, 0, false, filter,
|
|
[]string{"uid", "sAMAccountName", "userPrincipalName", "cn", "displayName", "mail"}, nil,
|
|
))
|
|
if err != nil {
|
|
continue
|
|
}
|
|
for _, entry := range sr.Entries {
|
|
if seen[entry.DN] {
|
|
continue
|
|
}
|
|
seen[entry.DN] = true
|
|
uid, cn, mail := ldapIdentityFromEntry(entry, "")
|
|
if uid == "" {
|
|
continue
|
|
}
|
|
candidates = append(candidates, ldapEntryUser{uid: uid, cn: cn, mail: mail})
|
|
}
|
|
}
|
|
if len(candidates) == 0 {
|
|
resp.BadRequest(c, "LDAP 搜索无结果:请检查 Base DN/过滤器是否匹配目录结构")
|
|
return
|
|
}
|
|
|
|
isActive := true
|
|
imported := 0
|
|
skipped := 0
|
|
var results []map[string]string
|
|
|
|
for _, entry := range candidates {
|
|
uid := entry.uid
|
|
if len(req.UserIDs) > 0 {
|
|
found := false
|
|
for _, id := range req.UserIDs {
|
|
if id == uid {
|
|
found = true
|
|
break
|
|
}
|
|
}
|
|
if !found {
|
|
continue
|
|
}
|
|
}
|
|
|
|
cn := entry.cn
|
|
mail := entry.mail
|
|
|
|
var existing model.User
|
|
err := model.DB.Where("username = ?", uid).First(&existing).Error
|
|
if err == nil {
|
|
// Update existing user
|
|
updates := map[string]interface{}{}
|
|
if cn != "" && cn != existing.DisplayName {
|
|
updates["display_name"] = cn
|
|
}
|
|
if mail != "" && (existing.Email == nil || *existing.Email != mail) {
|
|
updates["email"] = mail
|
|
}
|
|
if len(updates) > 0 {
|
|
model.DB.Model(&existing).Updates(updates)
|
|
}
|
|
results = append(results, map[string]string{"uid": uid, "status": "updated"})
|
|
skipped++
|
|
continue
|
|
}
|
|
|
|
newUser := model.User{
|
|
Username: uid,
|
|
DisplayName: cn,
|
|
Role: req.Role,
|
|
AuthSource: "ldap",
|
|
IsActive: &isActive,
|
|
HashedPassword: "-",
|
|
}
|
|
if mail != "" {
|
|
newUser.Email = &mail
|
|
}
|
|
if err := model.DB.Create(&newUser).Error; err != nil {
|
|
results = append(results, map[string]string{"uid": uid, "status": "error: " + err.Error()})
|
|
skipped++
|
|
continue
|
|
}
|
|
results = append(results, map[string]string{"uid": uid, "status": "created"})
|
|
imported++
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"message": fmt.Sprintf("导入完成: %d 新建, %d 更新", imported, skipped),
|
|
"imported": imported,
|
|
"skipped": skipped,
|
|
"results": results,
|
|
})
|
|
}
|
|
|
|
// POST /api/v1/ldap-config/delete-user
|
|
func DeleteLDAPUser(c *gin.Context) {
|
|
var req struct {
|
|
DN string `json:"dn" binding:"required"`
|
|
}
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
resp.BadRequest(c, "缺少 dn 参数")
|
|
return
|
|
}
|
|
|
|
var cfg model.LDAPConfig
|
|
if err := model.DB.Order("id").First(&cfg).Error; err != nil {
|
|
resp.BadRequest(c, "LDAP 配置不存在")
|
|
return
|
|
}
|
|
|
|
conn, err := dialLDAP(&cfg)
|
|
if err != nil {
|
|
resp.BadRequest(c, "LDAP 连接失败: "+err.Error())
|
|
return
|
|
}
|
|
defer conn.Close()
|
|
|
|
adminPw, _ := decryptPassword(cfg.AdminPassword)
|
|
if err := conn.Bind(cfg.AdminDN, adminPw); err != nil {
|
|
resp.BadRequest(c, "LDAP 管理员绑定失败")
|
|
return
|
|
}
|
|
|
|
if err := conn.Del(ldap.NewDelRequest(req.DN, nil)); err != nil {
|
|
resp.BadRequest(c, "删除用户失败: "+err.Error())
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{"message": "用户已从 LDAP 删除"})
|
|
}
|
|
|
|
// helper: dial LDAP with config
|
|
func dialLDAP(cfg *model.LDAPConfig) (*ldap.Conn, error) {
|
|
if cfg.LDAPHost == "" {
|
|
return nil, fmt.Errorf("LDAP not configured")
|
|
}
|
|
protocol := "ldap"
|
|
if cfg.UseLDAPS != nil && *cfg.UseLDAPS {
|
|
protocol = "ldaps"
|
|
}
|
|
port := 389
|
|
if cfg.LDAPPort != nil && *cfg.LDAPPort > 0 {
|
|
port = *cfg.LDAPPort
|
|
}
|
|
uri := fmt.Sprintf("%s://%s:%d", protocol, cfg.LDAPHost, port)
|
|
dialer := &net.Dialer{Timeout: 3 * time.Second}
|
|
return ldap.DialURL(uri, ldap.DialWithDialer(dialer))
|
|
}
|