feat: Go后端LDAP真实对接 — AES-256-GCM密码加解密 + 登录LDAP fallback
- 新增 crypto.go: AES-256-GCM 加解密,与 Python backend 兼容 - auth.go: Login 添加 LDAP fallback(本地优先→LDAP绑定→自动创建本地用户) - ldap.go: 实现真实 LDAP 连接/用户搜索/密码验证/OU列表/用户列表 - 所有 LDAP 操作解密 admin_password 后使用 - 新增/更新密码存储时加密 - router.go: 补充 delete-user 路由 - 添加 go-ldap/v3 依赖
This commit is contained in:
1 parent
622923821b
commit
88e5f4e7ee
71 files changed
+20390
-64
No files matched your search
@@ -1,11 +1,14 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"sql-platform/internal/model"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/go-ldap/ldap/v3"
|
||||
)
|
||||
|
||||
// GET /api/v1/ldap-config
|
||||
@@ -16,9 +19,24 @@ func GetLDAPConfig(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, nil)
|
||||
return
|
||||
}
|
||||
// mask password
|
||||
configs[0].AdminPassword = "******"
|
||||
c.JSON(http.StatusOK, configs[0])
|
||||
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
|
||||
@@ -32,67 +50,309 @@ func UpdateLDAPConfig(c *gin.Context) {
|
||||
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 := model.LDAPConfig{}
|
||||
if v, ok := input["ldap_host"].(string); ok {
|
||||
config.LDAPHost = v
|
||||
// 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 v, ok := input["base_dn"].(string); ok {
|
||||
config.BaseDN = v
|
||||
if port := getInt("ldap_port"); port > 0 {
|
||||
cfg.LDAPPort = &port
|
||||
}
|
||||
if v, ok := input["admin_dn"].(string); ok {
|
||||
config.AdminDN = v
|
||||
if b := getBool("use_ldaps"); b != nil {
|
||||
cfg.UseLDAPS = b
|
||||
}
|
||||
if v, ok := input["admin_password"].(string); ok && v != "******" {
|
||||
config.AdminPassword = v
|
||||
if pw := getStr("admin_password"); pw != "" && pw != "******" {
|
||||
encPw, _ := encryptPassword(pw)
|
||||
cfg.AdminPassword = encPw
|
||||
}
|
||||
if v, ok := input["search_filter"].(string); ok {
|
||||
config.SearchFilter = &v
|
||||
}
|
||||
if v, ok := input["user_mapping"].(string); ok {
|
||||
config.UserMapping = &v
|
||||
}
|
||||
if v, ok := input["ldap_port"].(float64); ok {
|
||||
port := int(v)
|
||||
config.LDAPPort = &port
|
||||
}
|
||||
if v, ok := input["use_ldaps"].(bool); ok {
|
||||
config.UseLDAPS = &v
|
||||
}
|
||||
model.DB.Create(&config)
|
||||
c.JSON(http.StatusOK, config)
|
||||
model.DB.Create(&cfg)
|
||||
cfg.AdminPassword = "******"
|
||||
c.JSON(http.StatusOK, cfg)
|
||||
} else {
|
||||
// update existing
|
||||
if pw, ok := input["admin_password"].(string); ok && pw == "******" {
|
||||
delete(input, "admin_password")
|
||||
// Update existing
|
||||
cfg := configs[0]
|
||||
updates := map[string]interface{}{}
|
||||
|
||||
if v := getStr("ldap_host"); v != "" {
|
||||
updates["ldap_host"] = v
|
||||
}
|
||||
model.DB.Model(&configs[0]).Updates(input)
|
||||
model.DB.First(&configs[0], configs[0].ID)
|
||||
configs[0].AdminPassword = "******"
|
||||
c.JSON(http.StatusOK, configs[0])
|
||||
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) {
|
||||
// TODO: actual LDAP connection test
|
||||
var req struct {
|
||||
TestUser string `json:"test_user"`
|
||||
TestPassword string `json:"test_password"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"detail": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
var cfg model.LDAPConfig
|
||||
if err := model.DB.Order("id").First(&cfg).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"detail": "LDAP 配置不存在,请先保存配置"})
|
||||
return
|
||||
}
|
||||
if cfg.LDAPHost == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": "LDAP 未配置"})
|
||||
return
|
||||
}
|
||||
|
||||
// Connect
|
||||
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)
|
||||
|
||||
conn, err := ldap.DialURL(uri)
|
||||
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__" {
|
||||
baseFilter := "(objectClass=inetOrgPerson)"
|
||||
if cfg.SearchFilter != nil && *cfg.SearchFilter != "" {
|
||||
baseFilter = *cfg.SearchFilter
|
||||
}
|
||||
userFilter := fmt.Sprintf("(&%s(uid=%s))", baseFilter, 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": "LDAP connection test (placeholder)",
|
||||
"message": fmt.Sprintf("LDAP 服务器 %s 连接成功", cfg.LDAPHost),
|
||||
})
|
||||
}
|
||||
|
||||
// POST /api/v1/ldap-config/ou-list
|
||||
func ListLDAPOUs(c *gin.Context) {
|
||||
// TODO: actual LDAP OU list
|
||||
c.JSON(http.StatusOK, []interface{}{})
|
||||
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) {
|
||||
// TODO: actual LDAP user list
|
||||
c.JSON(http.StatusOK, []interface{}{})
|
||||
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
|
||||
}
|
||||
|
||||
baseFilter := "(objectClass=inetOrgPerson)"
|
||||
if cfg.SearchFilter != nil && *cfg.SearchFilter != "" {
|
||||
baseFilter = *cfg.SearchFilter
|
||||
}
|
||||
|
||||
sr, err := conn.Search(ldap.NewSearchRequest(
|
||||
searchBase, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases,
|
||||
200, 0, false, baseFilter,
|
||||
[]string{"uid", "cn", "mail", "dn"},
|
||||
nil,
|
||||
))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, []interface{}{})
|
||||
return
|
||||
}
|
||||
|
||||
type LdapUser struct {
|
||||
DN string `json:"dn"`
|
||||
UID string `json:"uid"`
|
||||
CN string `json:"cn"`
|
||||
Mail string `json:"mail"`
|
||||
}
|
||||
var users []LdapUser
|
||||
for _, e := range sr.Entries {
|
||||
users = append(users, LdapUser{
|
||||
DN: e.DN,
|
||||
UID: e.GetAttributeValue("uid"),
|
||||
CN: e.GetAttributeValue("cn"),
|
||||
Mail: e.GetAttributeValue("mail"),
|
||||
})
|
||||
}
|
||||
c.JSON(http.StatusOK, users)
|
||||
}
|
||||
|
||||
// POST /api/v1/ldap-config/create-ou
|
||||
@@ -109,3 +369,21 @@ func CreateLDAPUser(c *gin.Context) {
|
||||
func BatchImportLDAP(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"message": "Batch import (placeholder)", "count": 0})
|
||||
}
|
||||
|
||||
// POST /api/v1/ldap-config/delete-user
|
||||
func DeleteLDAPUser(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"message": "User deleted (placeholder)"})
|
||||
}
|
||||
|
||||
// helper: dial LDAP with config
|
||||
func dialLDAP(cfg *model.LDAPConfig) (*ldap.Conn, error) {
|
||||
protocol := "ldap"
|
||||
if cfg.UseLDAPS != nil && *cfg.UseLDAPS {
|
||||
protocol = "ldaps"
|
||||
}
|
||||
port := 389
|
||||
if cfg.LDAPPort != nil && *cfg.LDAPPort > 0 {
|
||||
port = *cfg.LDAPPort
|
||||
}
|
||||
return ldap.DialURL(fmt.Sprintf("%s://%s:%d", protocol, cfg.LDAPHost, port))
|
||||
}
|
||||
Reference in new issue
Block a user