feat(ldap): Active Directory 双目录支持与 Docker 构建优化
- 新增 ldap_ad.go,支持 AD 密码编码、字段映射与目录类型判断 - 重构 ldap/ldap_users/ldap_ou,兼容 OpenLDAP 与 AD 登录、导入、OU 浏览 - 前端系统设置增加目录类型选择与 AD 配置项 - Dockerfile 按 TARGETARCH 单架构编译 Agent,限制 Node 内存防 OOM - run.sh 新增 docker fast/upgrade,README 补充 LDAP/AD 与常见问题
This commit is contained in:
1 parent
0f0f2770e1
commit
78c27037e3
12 files changed
+613
-226
No files matched your search
+172
-81
@@ -32,6 +32,17 @@ type LDAPAuthInfo struct {
|
||||
Email string
|
||||
}
|
||||
|
||||
var ldapUserAttrs = []string{
|
||||
"uid", "cn", "displayName", "mail", "userPrincipalName", "sAMAccountName",
|
||||
"telephoneNumber", "mobile", "title", "department",
|
||||
}
|
||||
|
||||
var ldapUserAttrSets = [][]string{
|
||||
{"uid", "cn", "displayName", "mail", "telephoneNumber", "mobile", "title", "department"},
|
||||
{"sAMAccountName", "userPrincipalName", "displayName", "cn", "mail", "telephoneNumber", "mobile", "title", "department"},
|
||||
ldapUserAttrs,
|
||||
}
|
||||
|
||||
// dialLDAP 连接LDAP服务器
|
||||
func dialLDAP(cfg *model.LDAPConfig) (*ldap.Conn, error) {
|
||||
if cfg.LDAPHost == "" {
|
||||
@@ -50,6 +61,136 @@ func dialLDAP(cfg *model.LDAPConfig) (*ldap.Conn, error) {
|
||||
return ldap.DialURL(uri, ldap.DialWithDialer(dialer))
|
||||
}
|
||||
|
||||
// ldapUserFilter 构造兼容 OpenLDAP 与 AD 的用户搜索过滤器 // Logan.Li
|
||||
func ldapUserFilter(cfg *model.LDAPConfig, username string) string {
|
||||
escaped := ldap.EscapeFilter(username)
|
||||
if cfg.SearchFilter != nil && strings.TrimSpace(*cfg.SearchFilter) != "" {
|
||||
sf := strings.TrimSpace(*cfg.SearchFilter)
|
||||
if strings.Contains(sf, "%s") {
|
||||
return strings.ReplaceAll(sf, "%s", escaped)
|
||||
}
|
||||
return fmt.Sprintf("(&%s(|(uid=%s)(sAMAccountName=%s)(userPrincipalName=%s)(cn=%s)))", sf, escaped, escaped, escaped, escaped)
|
||||
}
|
||||
return fmt.Sprintf("(|(&(objectClass=inetOrgPerson)(uid=%s))(&(objectClass=user)(|(sAMAccountName=%s)(userPrincipalName=%s)(cn=%s))))", escaped, escaped, escaped, escaped)
|
||||
}
|
||||
|
||||
// ldapADUserFilter 生成 AD 兜底过滤器,参考 opsx-monitor 的 sAMAccountName/userPrincipalName/cn 兼容策略 // Logan.Li
|
||||
func ldapADUserFilter(username string) string {
|
||||
escaped := ldap.EscapeFilter(username)
|
||||
return fmt.Sprintf("(|(sAMAccountName=%s)(userPrincipalName=%s)(cn=%s))", escaped, escaped, escaped)
|
||||
}
|
||||
|
||||
// ldapUserListFilters 返回目录用户列表过滤器,先尊重配置,再补 OpenLDAP/AD 兜底 // Logan.Li
|
||||
func ldapUserListFilters(cfg *model.LDAPConfig) []string {
|
||||
filters := []string{}
|
||||
if cfg.SearchFilter != nil && strings.TrimSpace(*cfg.SearchFilter) != "" {
|
||||
sf := strings.TrimSpace(*cfg.SearchFilter)
|
||||
if strings.Contains(sf, "%s") {
|
||||
filters = append(filters, strings.ReplaceAll(sf, "%s", "*"))
|
||||
} else {
|
||||
filters = append(filters, sf)
|
||||
}
|
||||
}
|
||||
filters = append(filters,
|
||||
"(objectClass=inetOrgPerson)",
|
||||
"(&(objectClass=user)(|(sAMAccountName=*)(userPrincipalName=*)))",
|
||||
)
|
||||
return filters
|
||||
}
|
||||
|
||||
// ldapEntryAttr 按属性名回退读取,兼容 OpenLDAP 与 AD 常见字段 // Logan.Li
|
||||
func ldapEntryAttr(entry *ldap.Entry, names ...string) string {
|
||||
for _, name := range names {
|
||||
if v := entry.GetAttributeValue(name); v != "" {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// ldapUserMapping 读取用户字段映射,同时提供 AD/OpenLDAP 默认回退 // Logan.Li
|
||||
func ldapUserMapping(cfg *model.LDAPConfig) map[string]string {
|
||||
userMapping := ldapDefaultUserMapping(cfg)
|
||||
if cfg.UserMapping != nil && *cfg.UserMapping != "" {
|
||||
_ = json.Unmarshal([]byte(*cfg.UserMapping), &userMapping)
|
||||
}
|
||||
return userMapping
|
||||
}
|
||||
|
||||
// ldapIdentityFromEntry 将目录条目转换为平台统一用户信息 // Logan.Li
|
||||
func ldapIdentityFromEntry(cfg *model.LDAPConfig, entry *ldap.Entry, fallbackUsername string) *LDAPAuthInfo {
|
||||
mapping := ldapUserMapping(cfg)
|
||||
mappedUsername := ldapEntryAttr(entry, mapping["username"])
|
||||
mappedDisplay := ldapEntryAttr(entry, mapping["display_name"])
|
||||
mappedEmail := ldapEntryAttr(entry, mapping["email"])
|
||||
info := &LDAPAuthInfo{
|
||||
Username: ldapFirstNonEmpty(mappedUsername, ldapEntryAttr(entry, "uid", "sAMAccountName", "userPrincipalName", "cn"), fallbackUsername),
|
||||
DisplayName: ldapFirstNonEmpty(mappedDisplay, ldapEntryAttr(entry, "displayName", "cn"), fallbackUsername),
|
||||
Email: ldapFirstNonEmpty(mappedEmail, ldapEntryAttr(entry, "mail", "userPrincipalName")),
|
||||
}
|
||||
return info
|
||||
}
|
||||
|
||||
func ldapFirstNonEmpty(values ...string) string {
|
||||
for _, v := range values {
|
||||
if strings.TrimSpace(v) != "" {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// ldapIsInvalidAttributeErr 判断目录不支持某些属性时的错误,用于 OpenLDAP/AD 属性集降级 // Logan.Li
|
||||
func ldapIsInvalidAttributeErr(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
msg := strings.ToLower(err.Error())
|
||||
return strings.Contains(msg, "undefined attribute") ||
|
||||
strings.Contains(msg, "invalid attribute") ||
|
||||
strings.Contains(msg, "attribute type undefined") ||
|
||||
strings.Contains(msg, "no such attribute")
|
||||
}
|
||||
|
||||
// ldapSearchUsers 使用多组属性搜索,避免 OpenLDAP 与 AD 互不支持属性时整体失败 // Logan.Li
|
||||
func ldapSearchUsers(conn *ldap.Conn, baseDN, filter string, sizeLimit int) (*ldap.SearchResult, error) {
|
||||
var lastErr error
|
||||
for _, attrs := range ldapUserAttrSets {
|
||||
searchReq := ldap.NewSearchRequest(
|
||||
baseDN,
|
||||
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases,
|
||||
sizeLimit, 10, false,
|
||||
filter,
|
||||
attrs,
|
||||
nil,
|
||||
)
|
||||
sr, err := conn.Search(searchReq)
|
||||
if err == nil {
|
||||
return sr, nil
|
||||
}
|
||||
lastErr = err
|
||||
if ldapIsInvalidAttributeErr(err) {
|
||||
continue
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return nil, lastErr
|
||||
}
|
||||
|
||||
// ldapSearchFirstUser 查找单个用户,过滤器兼容 OpenLDAP 与 Active Directory // Logan.Li
|
||||
func ldapSearchFirstUser(conn *ldap.Conn, cfg *model.LDAPConfig, username string) (*ldap.Entry, error) {
|
||||
for _, filter := range []string{ldapUserFilter(cfg, username), ldapADUserFilter(username)} {
|
||||
sr, err := ldapSearchUsers(conn, cfg.BaseDN, filter, 1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(sr.Entries) > 0 {
|
||||
return sr.Entries[0], nil
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("LDAP用户不存在")
|
||||
}
|
||||
|
||||
// tryLDAPAuth 尝试LDAP认证,返回用户信息
|
||||
func tryLDAPAuth(db *gorm.DB, username, password string) (*LDAPAuthInfo, error) {
|
||||
var cfg model.LDAPConfig
|
||||
@@ -71,69 +212,18 @@ func tryLDAPAuth(db *gorm.DB, username, password string) (*LDAPAuthInfo, error)
|
||||
return nil, fmt.Errorf("LDAP管理员绑定失败: %w", err)
|
||||
}
|
||||
|
||||
// Build search filter
|
||||
userFilter := ""
|
||||
baseFilter := "(objectClass=inetOrgPerson)"
|
||||
if cfg.SearchFilter != nil && *cfg.SearchFilter != "" {
|
||||
sf := *cfg.SearchFilter
|
||||
if strings.Contains(sf, "%s") {
|
||||
userFilter = strings.ReplaceAll(sf, "%s", ldap.EscapeFilter(username))
|
||||
} else {
|
||||
baseFilter = sf
|
||||
userFilter = fmt.Sprintf("(&%s(uid=%s))", baseFilter, ldap.EscapeFilter(username))
|
||||
}
|
||||
} else {
|
||||
userFilter = fmt.Sprintf("(&%s(uid=%s))", baseFilter, ldap.EscapeFilter(username))
|
||||
}
|
||||
|
||||
// Search user
|
||||
searchReq := ldap.NewSearchRequest(
|
||||
cfg.BaseDN,
|
||||
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases,
|
||||
1, 10, false,
|
||||
userFilter,
|
||||
[]string{"uid", "cn", "mail", "telephoneNumber"},
|
||||
nil,
|
||||
)
|
||||
sr, err := conn.Search(searchReq)
|
||||
if err != nil || len(sr.Entries) == 0 {
|
||||
entry, err := ldapSearchFirstUser(conn, &cfg, username)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("LDAP用户不存在")
|
||||
}
|
||||
entry := sr.Entries[0]
|
||||
userDN := entry.DN
|
||||
|
||||
// Verify password by binding as user
|
||||
// 使用用户 DN 重新绑定以校验密码,兼容 OpenLDAP 与 AD // Logan.Li
|
||||
if err := conn.Bind(userDN, password); err != nil {
|
||||
return nil, fmt.Errorf("LDAP密码验证失败: %w", err)
|
||||
}
|
||||
|
||||
// Extract user info using mapping
|
||||
userMapping := map[string]string{
|
||||
"username": "uid",
|
||||
"email": "mail",
|
||||
"display_name": "cn",
|
||||
}
|
||||
if cfg.UserMapping != nil && *cfg.UserMapping != "" {
|
||||
json.Unmarshal([]byte(*cfg.UserMapping), &userMapping)
|
||||
}
|
||||
|
||||
getAttr := func(key string) string {
|
||||
if v := entry.GetAttributeValue(key); v != "" {
|
||||
return v
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
info := &LDAPAuthInfo{
|
||||
Username: getAttr(userMapping["username"]),
|
||||
DisplayName: getAttr(userMapping["display_name"]),
|
||||
Email: getAttr(userMapping["email"]),
|
||||
}
|
||||
if info.Username == "" {
|
||||
info.Username = username
|
||||
}
|
||||
|
||||
return info, nil
|
||||
return ldapIdentityFromEntry(&cfg, entry, username), nil
|
||||
}
|
||||
|
||||
// GetLDAPConfig 获取LDAP配置
|
||||
@@ -181,17 +271,29 @@ func (h *LDAPHandler) UpdateLDAPConfig(c *gin.Context) {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
hasKey := func(key string) bool {
|
||||
_, ok := input[key]
|
||||
return ok
|
||||
}
|
||||
|
||||
userMappingStr := ""
|
||||
if um, ok := input["user_mapping"]; ok {
|
||||
if bytes, err := json.Marshal(um); err == nil {
|
||||
if um == nil || um == "" {
|
||||
userMappingStr = "{}"
|
||||
} else if bytes, err := json.Marshal(um); err == nil {
|
||||
userMappingStr = string(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
serverType := getStr("server_type")
|
||||
if serverType == "" {
|
||||
serverType = ldapServerOpenLDAP
|
||||
}
|
||||
|
||||
if len(configs) == 0 {
|
||||
// Create
|
||||
cfg := model.LDAPConfig{
|
||||
ServerType: serverType,
|
||||
LDAPHost: getStr("ldap_host"),
|
||||
AdminDN: getStr("admin_dn"),
|
||||
BaseDN: getStr("base_dn"),
|
||||
@@ -216,6 +318,13 @@ func (h *LDAPHandler) UpdateLDAPConfig(c *gin.Context) {
|
||||
// Update
|
||||
cfg := configs[0]
|
||||
updates := map[string]interface{}{}
|
||||
if hasKey("server_type") {
|
||||
st := getStr("server_type")
|
||||
if st == "" {
|
||||
st = ldapServerOpenLDAP
|
||||
}
|
||||
updates["server_type"] = st
|
||||
}
|
||||
if v := getStr("ldap_host"); v != "" {
|
||||
updates["ldap_host"] = v
|
||||
}
|
||||
@@ -225,8 +334,9 @@ func (h *LDAPHandler) UpdateLDAPConfig(c *gin.Context) {
|
||||
if v := getStr("admin_dn"); v != "" {
|
||||
updates["admin_dn"] = v
|
||||
}
|
||||
if v := getStr("search_filter"); v != "" {
|
||||
updates["search_filter"] = v
|
||||
if hasKey("search_filter") {
|
||||
v := strings.TrimSpace(getStr("search_filter"))
|
||||
updates["search_filter"] = &v
|
||||
}
|
||||
if userMappingStr != "" {
|
||||
updates["user_mapping"] = userMappingStr
|
||||
@@ -282,36 +392,17 @@ func (h *LDAPHandler) TestLDAPConnection(c *gin.Context) {
|
||||
|
||||
// If test_user provided, search and verify
|
||||
if req.TestUser != "" && req.TestPassword != "" {
|
||||
userFilter := ""
|
||||
baseFilter := "(objectClass=inetOrgPerson)"
|
||||
if cfg.SearchFilter != nil && *cfg.SearchFilter != "" {
|
||||
sf := *cfg.SearchFilter
|
||||
if strings.Contains(sf, "%s") {
|
||||
userFilter = strings.ReplaceAll(sf, "%s", ldap.EscapeFilter(req.TestUser))
|
||||
} else {
|
||||
baseFilter = sf
|
||||
userFilter = fmt.Sprintf("(&%s(uid=%s))", baseFilter, ldap.EscapeFilter(req.TestUser))
|
||||
}
|
||||
} else {
|
||||
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"},
|
||||
nil,
|
||||
))
|
||||
if err != nil || len(sr.Entries) == 0 {
|
||||
entry, err := ldapSearchFirstUser(conn, &cfg, req.TestUser)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{"success": false, "message": fmt.Sprintf("用户 %s 不存在", req.TestUser)})
|
||||
return
|
||||
}
|
||||
userDN := sr.Entries[0].DN
|
||||
userDN := entry.DN
|
||||
if err := conn.Bind(userDN, req.TestPassword); err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{"success": false, "message": fmt.Sprintf("密码验证失败: %s", err)})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, model.Response{Code: 200, Data: gin.H{"success": true, "message": fmt.Sprintf("认证成功!用户DN: %s", userDN)}})
|
||||
c.JSON(http.StatusOK, model.Response{Code: 200, Data: gin.H{"success": true, "message": fmt.Sprintf("认证成功!用户DN: %s", userDN), "user_info": ldapIdentityFromEntry(&cfg, entry, req.TestUser)}})
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"unicode/utf16"
|
||||
|
||||
"ezops/model"
|
||||
|
||||
"github.com/go-ldap/ldap/v3"
|
||||
)
|
||||
|
||||
const (
|
||||
ldapServerOpenLDAP = "openldap"
|
||||
ldapServerAD = "ad"
|
||||
)
|
||||
|
||||
// ldapIsAD 判断当前配置是否为 Active Directory // Logan.Li
|
||||
func ldapIsAD(cfg *model.LDAPConfig) bool {
|
||||
if cfg == nil {
|
||||
return false
|
||||
}
|
||||
return strings.EqualFold(strings.TrimSpace(cfg.ServerType), ldapServerAD)
|
||||
}
|
||||
|
||||
// ldapDefaultUserMapping 按目录类型返回默认字段映射 // Logan.Li
|
||||
func ldapDefaultUserMapping(cfg *model.LDAPConfig) map[string]string {
|
||||
if ldapIsAD(cfg) {
|
||||
return map[string]string{
|
||||
"username": "sAMAccountName",
|
||||
"email": "mail",
|
||||
"display_name": "displayName",
|
||||
}
|
||||
}
|
||||
return map[string]string{
|
||||
"username": "uid",
|
||||
"email": "mail",
|
||||
"display_name": "cn",
|
||||
}
|
||||
}
|
||||
|
||||
// ldapEncodeADPassword 将明文密码编码为 AD unicodePwd(UTF-16LE 带引号) // Logan.Li
|
||||
func ldapEncodeADPassword(password string) []byte {
|
||||
quoted := `"` + password + `"`
|
||||
runes := utf16.Encode([]rune(quoted))
|
||||
buf := make([]byte, len(runes)*2)
|
||||
for i, r := range runes {
|
||||
buf[i*2] = byte(r)
|
||||
buf[i*2+1] = byte(r >> 8)
|
||||
}
|
||||
return buf
|
||||
}
|
||||
|
||||
// ldapBuildUserDN 按目录类型构造用户 DN // Logan.Li
|
||||
func ldapBuildUserDN(cfg *model.LDAPConfig, username, displayName, parentDN string) (string, error) {
|
||||
parentDN = strings.TrimSpace(parentDN)
|
||||
if parentDN == "" {
|
||||
return "", fmt.Errorf("父级 DN 不能为空")
|
||||
}
|
||||
if ldapIsAD(cfg) {
|
||||
cn := strings.TrimSpace(displayName)
|
||||
if cn == "" {
|
||||
cn = username
|
||||
}
|
||||
return fmt.Sprintf("CN=%s,%s", ldap.EscapeDN(cn), parentDN), nil
|
||||
}
|
||||
if strings.TrimSpace(username) == "" {
|
||||
return "", fmt.Errorf("用户名不能为空")
|
||||
}
|
||||
return fmt.Sprintf("uid=%s,%s", ldap.EscapeFilter(username), parentDN), nil
|
||||
}
|
||||
|
||||
// ldapOUListFilters 返回 OU/容器列表过滤器,兼容 OpenLDAP 与 AD // Logan.Li
|
||||
func ldapOUListFilters(cfg *model.LDAPConfig) []string {
|
||||
if ldapIsAD(cfg) {
|
||||
return []string{
|
||||
"(|(objectClass=organizationalUnit)(objectClass=container))",
|
||||
}
|
||||
}
|
||||
return []string{"(objectClass=organizationalUnit)"}
|
||||
}
|
||||
|
||||
// ldapOUEntryName 读取 OU/容器显示名 // Logan.Li
|
||||
func ldapOUEntryName(entry *ldap.Entry) string {
|
||||
if v := entry.GetAttributeValue("ou"); v != "" {
|
||||
return v
|
||||
}
|
||||
return ldapEntryAttr(entry, "cn", "name")
|
||||
}
|
||||
|
||||
// ldapAddOpenLDAPUser 在 OpenLDAP 中创建 inetOrgPerson 用户 // Logan.Li
|
||||
func ldapAddOpenLDAPUser(conn *ldap.Conn, cfg *model.LDAPConfig, userDN, username, displayName, email, password string) error {
|
||||
mapping := ldapUserMapping(cfg)
|
||||
uidAttr := mapping["username"]
|
||||
if uidAttr == "" {
|
||||
uidAttr = "uid"
|
||||
}
|
||||
mailAttr := mapping["email"]
|
||||
if mailAttr == "" {
|
||||
mailAttr = "mail"
|
||||
}
|
||||
cn := displayName
|
||||
if cn == "" {
|
||||
cn = username
|
||||
}
|
||||
|
||||
addReq := ldap.NewAddRequest(userDN, nil)
|
||||
addReq.Attribute("objectClass", []string{"inetOrgPerson", "organizationalPerson", "person", "top"})
|
||||
addReq.Attribute(uidAttr, []string{username})
|
||||
addReq.Attribute("cn", []string{cn})
|
||||
addReq.Attribute("sn", []string{cn})
|
||||
if email != "" {
|
||||
addReq.Attribute(mailAttr, []string{email})
|
||||
}
|
||||
addReq.Attribute("userPassword", []string{password})
|
||||
return conn.Add(addReq)
|
||||
}
|
||||
|
||||
// ldapAddADUser 在 Active Directory 中创建并启用用户账号 // Logan.Li
|
||||
func ldapAddADUser(conn *ldap.Conn, userDN, username, displayName, email, password string) error {
|
||||
cn := strings.TrimSpace(displayName)
|
||||
if cn == "" {
|
||||
cn = username
|
||||
}
|
||||
sn := cn
|
||||
if idx := strings.LastIndex(cn, " "); idx > 0 {
|
||||
sn = cn[idx+1:]
|
||||
}
|
||||
|
||||
addReq := ldap.NewAddRequest(userDN, nil)
|
||||
addReq.Attribute("objectClass", []string{"top", "person", "organizationalPerson", "user"})
|
||||
addReq.Attribute("cn", []string{cn})
|
||||
addReq.Attribute("sAMAccountName", []string{username})
|
||||
addReq.Attribute("sn", []string{sn})
|
||||
if email != "" {
|
||||
addReq.Attribute("mail", []string{email})
|
||||
}
|
||||
// 先以禁用状态创建,设置密码后再启用 // Logan.Li
|
||||
addReq.Attribute("userAccountControl", []string{"514"})
|
||||
if err := conn.Add(addReq); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
modPwd := ldap.NewModifyRequest(userDN, nil)
|
||||
modPwd.Replace("unicodePwd", []string{string(ldapEncodeADPassword(password))})
|
||||
if err := conn.Modify(modPwd); err != nil {
|
||||
_ = conn.Del(ldap.NewDelRequest(userDN, nil))
|
||||
return fmt.Errorf("设置 AD 密码失败(需 LDAPS 连接): %w", err)
|
||||
}
|
||||
|
||||
modEnable := ldap.NewModifyRequest(userDN, nil)
|
||||
modEnable.Replace("userAccountControl", []string{"512"})
|
||||
return conn.Modify(modEnable)
|
||||
}
|
||||
@@ -3,7 +3,6 @@ package controller
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"ezops/model"
|
||||
|
||||
@@ -20,48 +19,48 @@ func (h *LDAPHandler) ListLDAPOUs(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
cfg := configs[0]
|
||||
port := 389
|
||||
if cfg.LDAPPort != nil {
|
||||
port = *cfg.LDAPPort
|
||||
}
|
||||
|
||||
conn, err := ldap.DialURL(fmt.Sprintf("ldap://%s:%d", cfg.LDAPHost, port))
|
||||
conn, err := dialLDAP(&cfg)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, model.Response{Code: 200, Data: []interface{}{}})
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
conn.SetTimeout(5 * time.Second)
|
||||
if err := conn.Bind(cfg.AdminDN, cfg.AdminPassword); err != nil {
|
||||
c.JSON(http.StatusOK, model.Response{Code: 200, Data: []interface{}{}})
|
||||
return
|
||||
}
|
||||
|
||||
searchReq := ldap.NewSearchRequest(
|
||||
cfg.BaseDN,
|
||||
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
|
||||
"(objectClass=organizationalUnit)",
|
||||
[]string{"ou", "description"},
|
||||
nil,
|
||||
)
|
||||
sr, err := conn.Search(searchReq)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, model.Response{Code: 200, Data: []interface{}{}})
|
||||
return
|
||||
}
|
||||
|
||||
type OU struct {
|
||||
DN string `json:"dn"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
var ous []OU
|
||||
for _, e := range sr.Entries {
|
||||
ous = append(ous, OU{
|
||||
DN: e.DN,
|
||||
Name: e.GetAttributeValue("ou"),
|
||||
Description: e.GetAttributeValue("description"),
|
||||
})
|
||||
seenDN := map[string]bool{}
|
||||
for _, filter := range ldapOUListFilters(&cfg) {
|
||||
searchReq := ldap.NewSearchRequest(
|
||||
cfg.BaseDN,
|
||||
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
|
||||
filter,
|
||||
[]string{"ou", "cn", "name", "description"},
|
||||
nil,
|
||||
)
|
||||
sr, err := conn.Search(searchReq)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, e := range sr.Entries {
|
||||
if seenDN[e.DN] {
|
||||
continue
|
||||
}
|
||||
seenDN[e.DN] = true
|
||||
ous = append(ous, OU{
|
||||
DN: e.DN,
|
||||
Name: ldapOUEntryName(e),
|
||||
Description: e.GetAttributeValue("description"),
|
||||
})
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, model.Response{Code: 200, Data: ous})
|
||||
}
|
||||
@@ -85,23 +84,18 @@ func (h *LDAPHandler) CreateLDAPOU(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
cfg := configs[0]
|
||||
port := 389
|
||||
if cfg.LDAPPort != nil {
|
||||
port = *cfg.LDAPPort
|
||||
}
|
||||
|
||||
if req.ParentDN == "" {
|
||||
req.ParentDN = cfg.BaseDN
|
||||
}
|
||||
ouDN := fmt.Sprintf("ou=%s,%s", ldap.EscapeFilter(req.OUName), req.ParentDN)
|
||||
|
||||
conn, err := ldap.DialURL(fmt.Sprintf("ldap://%s:%d", cfg.LDAPHost, port))
|
||||
conn, err := dialLDAP(&cfg)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "LDAP连接失败: " + err.Error()})
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
conn.SetTimeout(5 * time.Second)
|
||||
if err := conn.Bind(cfg.AdminDN, cfg.AdminPassword); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "管理员认证失败: " + err.Error()})
|
||||
return
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"ezops/model"
|
||||
|
||||
@@ -24,18 +21,18 @@ func (h *LDAPHandler) ListLDAPUsers(c *gin.Context) {
|
||||
|
||||
var cfg model.LDAPConfig
|
||||
if err := h.db.Order("id").First(&cfg).Error; err != nil {
|
||||
c.JSON(http.StatusOK, []interface{}{})
|
||||
c.JSON(http.StatusOK, model.Response{Code: 200, Data: []interface{}{}})
|
||||
return
|
||||
}
|
||||
|
||||
conn, err := dialLDAP(&cfg)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, []interface{}{})
|
||||
c.JSON(http.StatusOK, model.Response{Code: 200, Data: []interface{}{}})
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
if err := conn.Bind(cfg.AdminDN, cfg.AdminPassword); err != nil {
|
||||
c.JSON(http.StatusOK, []interface{}{})
|
||||
c.JSON(http.StatusOK, model.Response{Code: 200, Data: []interface{}{}})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -44,30 +41,10 @@ func (h *LDAPHandler) ListLDAPUsers(c *gin.Context) {
|
||||
searchBase = req.OuDn
|
||||
}
|
||||
|
||||
baseFilter := "(objectClass=inetOrgPerson)"
|
||||
if cfg.SearchFilter != nil && *cfg.SearchFilter != "" {
|
||||
sf := *cfg.SearchFilter
|
||||
if strings.Contains(sf, "%s") {
|
||||
baseFilter = strings.ReplaceAll(sf, "%s", "*")
|
||||
} else {
|
||||
baseFilter = sf
|
||||
}
|
||||
}
|
||||
|
||||
sr, err := conn.Search(ldap.NewSearchRequest(
|
||||
searchBase, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases,
|
||||
200, 0, false, baseFilter,
|
||||
[]string{"uid", "cn", "mail", "dn", "telephoneNumber", "title", "department"},
|
||||
nil,
|
||||
))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, []interface{}{})
|
||||
return
|
||||
}
|
||||
|
||||
type LdapUser struct {
|
||||
DN string `json:"dn"`
|
||||
UID string `json:"uid"`
|
||||
Username string `json:"username"`
|
||||
CN string `json:"cn"`
|
||||
Mail string `json:"mail"`
|
||||
Phone string `json:"phone"`
|
||||
@@ -75,16 +52,32 @@ func (h *LDAPHandler) ListLDAPUsers(c *gin.Context) {
|
||||
Department string `json:"department"`
|
||||
}
|
||||
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"),
|
||||
Phone: e.GetAttributeValue("telephoneNumber"),
|
||||
Title: e.GetAttributeValue("title"),
|
||||
Department: e.GetAttributeValue("department"),
|
||||
})
|
||||
seenDNs := map[string]bool{}
|
||||
for _, filter := range ldapUserListFilters(&cfg) {
|
||||
sr, err := ldapSearchUsers(conn, searchBase, filter, 500)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, e := range sr.Entries {
|
||||
if seenDNs[e.DN] {
|
||||
continue
|
||||
}
|
||||
info := ldapIdentityFromEntry(&cfg, e, "")
|
||||
if info.Username == "" {
|
||||
continue
|
||||
}
|
||||
seenDNs[e.DN] = true
|
||||
users = append(users, LdapUser{
|
||||
DN: e.DN,
|
||||
UID: info.Username,
|
||||
Username: info.Username,
|
||||
CN: info.DisplayName,
|
||||
Mail: info.Email,
|
||||
Phone: ldapEntryAttr(e, "telephoneNumber", "mobile"),
|
||||
Title: ldapEntryAttr(e, "title"),
|
||||
Department: ldapEntryAttr(e, "department"),
|
||||
})
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, model.Response{Code: 200, Data: users})
|
||||
}
|
||||
@@ -195,54 +188,40 @@ func (h *LDAPHandler) CreateLDAPUser(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
cfg := configs[0]
|
||||
port := 389
|
||||
if cfg.LDAPPort != nil {
|
||||
port = *cfg.LDAPPort
|
||||
}
|
||||
if req.OUDN == "" {
|
||||
req.OUDN = cfg.BaseDN
|
||||
}
|
||||
userDN := fmt.Sprintf("uid=%s,%s", ldap.EscapeFilter(req.Username), req.OUDN)
|
||||
|
||||
// Parse user mapping
|
||||
mapping := map[string]string{"username": "uid", "email": "mail", "display_name": "cn"}
|
||||
if cfg.UserMapping != nil {
|
||||
_ = json.Unmarshal([]byte(*cfg.UserMapping), &mapping)
|
||||
userDN, err := ldapBuildUserDN(&cfg, req.Username, req.DisplayName, req.OUDN)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()})
|
||||
return
|
||||
}
|
||||
if ldapIsAD(&cfg) && (cfg.UseLDAPS == nil || !*cfg.UseLDAPS) {
|
||||
c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "Active Directory 创建用户需启用 LDAPS"})
|
||||
return
|
||||
}
|
||||
|
||||
uidAttr := mapping["username"]
|
||||
if uidAttr == "" {
|
||||
uidAttr = "uid"
|
||||
}
|
||||
mailAttr := mapping["email"]
|
||||
if mailAttr == "" {
|
||||
mailAttr = "mail"
|
||||
}
|
||||
|
||||
conn, err := ldap.DialURL(fmt.Sprintf("ldap://%s:%d", cfg.LDAPHost, port))
|
||||
conn, err := dialLDAP(&cfg)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "LDAP连接失败: " + err.Error()})
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
conn.SetTimeout(5 * time.Second)
|
||||
if err := conn.Bind(cfg.AdminDN, cfg.AdminPassword); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "管理员认证失败: " + err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
addReq := ldap.NewAddRequest(userDN, nil)
|
||||
addReq.Attribute("objectClass", []string{"inetOrgPerson", "organizationalPerson", "person", "top"})
|
||||
addReq.Attribute(uidAttr, []string{req.Username})
|
||||
addReq.Attribute("cn", []string{req.DisplayName})
|
||||
addReq.Attribute("sn", []string{req.DisplayName})
|
||||
if req.Email != "" {
|
||||
addReq.Attribute(mailAttr, []string{req.Email})
|
||||
}
|
||||
addReq.Attribute("userPassword", []string{req.Password})
|
||||
if err := conn.Add(addReq); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "创建用户失败: " + err.Error()})
|
||||
return
|
||||
if ldapIsAD(&cfg) {
|
||||
if err := ldapAddADUser(conn, userDN, req.Username, req.DisplayName, req.Email, req.Password); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "创建 AD 用户失败: " + err.Error()})
|
||||
return
|
||||
}
|
||||
} else {
|
||||
if err := ldapAddOpenLDAPUser(conn, &cfg, userDN, req.Username, req.DisplayName, req.Email, req.Password); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "创建用户失败: " + err.Error()})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.Response{Code: 200, Message: "用户创建成功", Data: gin.H{"dn": userDN}})
|
||||
@@ -265,18 +244,13 @@ func (h *LDAPHandler) DeleteLDAPUser(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
cfg := configs[0]
|
||||
port := 389
|
||||
if cfg.LDAPPort != nil {
|
||||
port = *cfg.LDAPPort
|
||||
}
|
||||
|
||||
conn, err := ldap.DialURL(fmt.Sprintf("ldap://%s:%d", cfg.LDAPHost, port))
|
||||
conn, err := dialLDAP(&cfg)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "LDAP连接失败: " + err.Error()})
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
conn.SetTimeout(5 * time.Second)
|
||||
if err := conn.Bind(cfg.AdminDN, cfg.AdminPassword); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "管理员认证失败: " + err.Error()})
|
||||
return
|
||||
@@ -312,28 +286,23 @@ func (h *LDAPHandler) UpdateLDAPUser(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
cfg := configs[0]
|
||||
port := 389
|
||||
if cfg.LDAPPort != nil {
|
||||
port = *cfg.LDAPPort
|
||||
}
|
||||
|
||||
conn, err := ldap.DialURL(fmt.Sprintf("ldap://%s:%d", cfg.LDAPHost, port))
|
||||
conn, err := dialLDAP(&cfg)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "LDAP连接失败: " + err.Error()})
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
conn.SetTimeout(5 * time.Second)
|
||||
if err := conn.Bind(cfg.AdminDN, cfg.AdminPassword); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "管理员认证失败: " + err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// 先查当前值,做 diff
|
||||
// 先查当前值,做 diff(AD 同时读取 displayName) // Logan.Li
|
||||
sr, err := conn.Search(ldap.NewSearchRequest(
|
||||
req.DN, ldap.ScopeBaseObject, ldap.NeverDerefAliases,
|
||||
1, 0, false, "(objectClass=*)",
|
||||
[]string{"cn", "mail", "telephoneNumber", "title"},
|
||||
[]string{"cn", "displayName", "mail", "telephoneNumber", "title"},
|
||||
nil,
|
||||
))
|
||||
if err != nil || len(sr.Entries) == 0 {
|
||||
@@ -343,10 +312,13 @@ func (h *LDAPHandler) UpdateLDAPUser(c *gin.Context) {
|
||||
entry := sr.Entries[0]
|
||||
|
||||
modReq := ldap.NewModifyRequest(req.DN, nil)
|
||||
// cn
|
||||
oldCN := entry.GetAttributeValue("cn")
|
||||
// cn / displayName(AD 优先 displayName) // Logan.Li
|
||||
oldCN := ldapEntryAttr(entry, "displayName", "cn")
|
||||
if req.CN != "" && req.CN != oldCN {
|
||||
modReq.Replace("cn", []string{req.CN})
|
||||
if ldapIsAD(&cfg) {
|
||||
modReq.Replace("displayName", []string{req.CN})
|
||||
}
|
||||
modReq.Replace("sn", []string{req.CN}) // sn 同步更新
|
||||
}
|
||||
// mail
|
||||
|
||||
@@ -196,6 +196,7 @@ type ChangePasswordRequest struct {
|
||||
// LDAPConfig LDAP配置
|
||||
type LDAPConfig struct {
|
||||
ID int `gorm:"primarykey" json:"id"`
|
||||
ServerType string `gorm:"size:20;default:openldap" json:"server_type"` // openldap | ad // Logan.Li
|
||||
LDAPHost string `gorm:"size:200;not null" json:"ldap_host"`
|
||||
LDAPPort *int `json:"ldap_port"`
|
||||
UseLDAPS *bool `json:"use_ldaps"`
|
||||
|
||||
@@ -231,4 +231,11 @@ func applySchemaPatches(db *gorm.DB) {
|
||||
}
|
||||
ensureTable(&model.LogScopeRole{}, "monitor_log_scope_roles")
|
||||
ensureTable(&model.UserLogScopeRole{}, "monitor_user_log_scope_roles")
|
||||
|
||||
// LDAP 目录类型列(openldap | ad) // Logan.Li
|
||||
if m.HasTable(&model.LDAPConfig{}) && !m.HasColumn(&model.LDAPConfig{}, "server_type") {
|
||||
if err := m.AddColumn(&model.LDAPConfig{}, "ServerType"); err != nil {
|
||||
log.Printf("[DB] 补列 iam_ldap_configs.server_type 失败: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user