mirror of
https://gitee.com/dromara/mayfly-go
synced 2025-11-02 15:30:25 +08:00
refactor: ldap登录配置迁移至系统配置
This commit is contained in:
@@ -37,18 +37,4 @@ log:
|
||||
level: info
|
||||
# file:
|
||||
# path: ./
|
||||
# name: mayfly-go.log
|
||||
|
||||
# ldap相关配置
|
||||
ldap:
|
||||
enabled: true
|
||||
host: "ldap.example.com"
|
||||
port: 389
|
||||
baseDn: "ou=users,dc=example,dc=com"
|
||||
bindDn: "cn=admin,dc=example,dc=com"
|
||||
userFilter: "(&(objectClass=organizationalPerson)(uid=%s))"
|
||||
bindPassword: "admin123."
|
||||
fieldMapping:
|
||||
identifier: "cn"
|
||||
displayName: "displayName"
|
||||
email: "mail"
|
||||
# name: mayfly-go.log
|
||||
@@ -1,7 +1,7 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"mayfly-go/internal/auth/api/form"
|
||||
msgapp "mayfly-go/internal/msg/application"
|
||||
@@ -10,14 +10,15 @@ import (
|
||||
"mayfly-go/pkg/biz"
|
||||
"mayfly-go/pkg/cache"
|
||||
"mayfly-go/pkg/captcha"
|
||||
"mayfly-go/pkg/config"
|
||||
"mayfly-go/pkg/ginx"
|
||||
"mayfly-go/pkg/ldap"
|
||||
"mayfly-go/pkg/req"
|
||||
"mayfly-go/pkg/utils/cryptox"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-ldap/ldap/v3"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
@@ -29,12 +30,8 @@ type LdapLogin struct {
|
||||
|
||||
// @router /auth/ldap/enabled [get]
|
||||
func (a *LdapLogin) GetLdapEnabled(rc *req.Ctx) {
|
||||
if config.Conf.Ldap != nil {
|
||||
rc.ResData = config.Conf.Ldap.Enabled
|
||||
return
|
||||
}
|
||||
|
||||
rc.ResData = false
|
||||
ldapLoginConfig := a.ConfigApp.GetConfig(sysentity.ConfigKeyLdapLogin).ToLdapLogin()
|
||||
rc.ResData = ldapLoginConfig.Enable
|
||||
}
|
||||
|
||||
// @router /auth/ldap/login [post]
|
||||
@@ -96,7 +93,7 @@ func (a *LdapLogin) createUser(userName, displayName string) {
|
||||
}
|
||||
|
||||
func (a *LdapLogin) getOrCreateUserWithLdap(userName string, password string, cols ...string) (*sysentity.Account, error) {
|
||||
userInfo, err := ldap.Authenticate(userName, password)
|
||||
userInfo, err := Authenticate(userName, password)
|
||||
if err != nil {
|
||||
return nil, errors.New("用户名密码错误")
|
||||
}
|
||||
@@ -110,3 +107,98 @@ func (a *LdapLogin) getOrCreateUserWithLdap(userName string, password string, co
|
||||
}
|
||||
return account, nil
|
||||
}
|
||||
|
||||
type UserInfo struct {
|
||||
UserName string
|
||||
DisplayName string
|
||||
Email string
|
||||
}
|
||||
|
||||
// Authenticate 通过 LDAP 验证用户名密码
|
||||
func Authenticate(username, password string) (*UserInfo, error) {
|
||||
ldapConf := sysapp.GetConfigApp().GetConfig(sysentity.ConfigKeyLdapLogin).ToLdapLogin()
|
||||
conn, err := Connect(ldapConf)
|
||||
if err != nil {
|
||||
return nil, errors.Errorf("connect: %v", err)
|
||||
}
|
||||
defer func() { _ = conn.Close() }()
|
||||
|
||||
sr, err := conn.Search(
|
||||
ldap.NewSearchRequest(
|
||||
ldapConf.BaseDN,
|
||||
ldap.ScopeWholeSubtree,
|
||||
ldap.NeverDerefAliases,
|
||||
0,
|
||||
0,
|
||||
false,
|
||||
strings.ReplaceAll(ldapConf.UserFilter, "%s", username),
|
||||
[]string{"dn", ldapConf.UidMap, ldapConf.UdnMap, ldapConf.EmailMap},
|
||||
nil,
|
||||
),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, errors.Errorf("search user DN: %v", err)
|
||||
} else if len(sr.Entries) != 1 {
|
||||
return nil, errors.Errorf("expect 1 user DN but got %d", len(sr.Entries))
|
||||
}
|
||||
entry := sr.Entries[0]
|
||||
|
||||
// Bind as the user to verify their password
|
||||
err = conn.Bind(entry.DN, password)
|
||||
if err != nil {
|
||||
return nil, errors.Errorf("bind user: %v", err)
|
||||
}
|
||||
|
||||
userName := entry.GetAttributeValue(ldapConf.UidMap)
|
||||
if userName == "" {
|
||||
return nil, errors.Errorf("the attribute %q is not found or has empty value", ldapConf.UidMap)
|
||||
}
|
||||
return &UserInfo{
|
||||
UserName: userName,
|
||||
DisplayName: entry.GetAttributeValue(ldapConf.UdnMap),
|
||||
Email: entry.GetAttributeValue(ldapConf.EmailMap),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Connect 创建 LDAP 连接
|
||||
func Connect(ldapConf *sysentity.ConfigLdapLogin) (*ldap.Conn, error) {
|
||||
conn, err := dial(ldapConf)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Bind with a system account
|
||||
err = conn.Bind(ldapConf.BindDN, ldapConf.BindPwd)
|
||||
if err != nil {
|
||||
_ = conn.Close()
|
||||
return nil, errors.Errorf("bind: %v", err)
|
||||
}
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
func dial(ldapConf *sysentity.ConfigLdapLogin) (*ldap.Conn, error) {
|
||||
addr := fmt.Sprintf("%s:%s", ldapConf.Host, ldapConf.Port)
|
||||
tlsConfig := &tls.Config{
|
||||
ServerName: ldapConf.Host,
|
||||
InsecureSkipVerify: ldapConf.SkipTLSVerify,
|
||||
}
|
||||
if ldapConf.SecurityProtocol == "LDAPS" {
|
||||
conn, err := ldap.DialTLS("tcp", addr, tlsConfig)
|
||||
if err != nil {
|
||||
return nil, errors.Errorf("dial TLS: %v", err)
|
||||
}
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
conn, err := ldap.Dial("tcp", addr)
|
||||
if err != nil {
|
||||
return nil, errors.Errorf("dial: %v", err)
|
||||
}
|
||||
if ldapConf.SecurityProtocol == "StartTLS" {
|
||||
if err = conn.StartTLS(tlsConfig); err != nil {
|
||||
_ = conn.Close()
|
||||
return nil, errors.Errorf("start TLS: %v", err)
|
||||
}
|
||||
}
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
@@ -3,12 +3,14 @@ package entity
|
||||
import (
|
||||
"encoding/json"
|
||||
"mayfly-go/pkg/model"
|
||||
"mayfly-go/pkg/utils/stringx"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
const (
|
||||
ConfigKeyAccountLoginSecurity string = "AccountLoginSecurity" // 账号登录安全配置
|
||||
ConfigKeyOauth2Login string = "Oauth2Login" // oauth2认证登录配置
|
||||
ConfigKeyLdapLogin string = "LdapLogin" // ldap登录配置
|
||||
ConfigKeyDbQueryMaxCount string = "DbQueryMaxCount" // 数据库查询的最大数量
|
||||
ConfigKeyDbSaveQuerySQL string = "DbSaveQuerySQL" // 数据库是否记录查询相关sql
|
||||
ConfigUseWartermark string = "UseWartermark" // 是否使用水印
|
||||
@@ -105,13 +107,46 @@ func (c *Config) ToOauth2Login() *ConfigOauth2Login {
|
||||
ol.AuthorizationURL = jm["authorizationURL"]
|
||||
ol.AccessTokenURL = jm["accessTokenURL"]
|
||||
ol.RedirectURL = jm["redirectURL"]
|
||||
ol.Scopes = jm["scopes"]
|
||||
ol.Scopes = stringx.Trim(jm["scopes"])
|
||||
ol.ResourceURL = jm["resourceURL"]
|
||||
ol.UserIdentifier = jm["userIdentifier"]
|
||||
ol.AutoRegister = c.ConvBool(jm["autoRegister"], true)
|
||||
return ol
|
||||
}
|
||||
|
||||
type ConfigLdapLogin struct {
|
||||
Enable bool // 是否启用
|
||||
Host string
|
||||
Port string `json:"port"`
|
||||
SkipTLSVerify bool `json:"skipTLSVerify"` // 客户端是否跳过 TLS 证书验证
|
||||
SecurityProtocol string `json:"securityProtocol"` // 安全协议(为Null不使用安全协议),如: StartTLS, LDAPS
|
||||
BindDN string `json:"bindDn"` // LDAP 服务的管理员账号,如: "cn=admin,dc=example,dc=com"
|
||||
BindPwd string `json:"bindPwd"` // LDAP 服务的管理员密码
|
||||
BaseDN string `json:"baseDN"` // 用户所在的 base DN, 如: "ou=users,dc=example,dc=com"
|
||||
UserFilter string `json:"userFilter"` // 过滤用户的方式, 如: "(uid=%s)"
|
||||
UidMap string `json:"UidMap"` // 用户id和 LDAP 字段名之间的映射关系
|
||||
UdnMap string `json:"UdnMap"` // 用户姓名(dispalyName)和 LDAP 字段名之间的映射关系
|
||||
EmailMap string `json:"emailMap"` // 用户email和 LDAP 字段名之间的映射关系
|
||||
}
|
||||
|
||||
// 转换为LdapLogin结构体
|
||||
func (c *Config) ToLdapLogin() *ConfigLdapLogin {
|
||||
jm := c.GetJsonMap()
|
||||
ll := new(ConfigLdapLogin)
|
||||
ll.Enable = c.ConvBool(jm["enable"], false)
|
||||
ll.Host = jm["host"]
|
||||
ll.SkipTLSVerify = c.ConvBool(jm["skipTLSVerify"], true)
|
||||
ll.SecurityProtocol = jm["securityProtocol"]
|
||||
ll.BindDN = stringx.Trim(jm["bindDN"])
|
||||
ll.BindPwd = stringx.Trim(jm["bindPwd"])
|
||||
ll.BaseDN = stringx.Trim(jm["baseDN"])
|
||||
ll.UserFilter = stringx.Trim(jm["userFilter"])
|
||||
ll.UidMap = stringx.Trim(jm["uidMap"])
|
||||
ll.UdnMap = stringx.Trim(jm["udnMap"])
|
||||
ll.EmailMap = stringx.Trim(jm["emailMap"])
|
||||
return ll
|
||||
}
|
||||
|
||||
// 转换配置中的值为bool类型(默认"1"或"true"为true,其他为false)
|
||||
func (c *Config) ConvBool(value string, defaultValue bool) bool {
|
||||
if value == "" {
|
||||
|
||||
@@ -439,8 +439,9 @@ CREATE TABLE `t_sys_config` (
|
||||
-- Records of t_sys_config
|
||||
-- ----------------------------
|
||||
BEGIN;
|
||||
INSERT INTO `t_sys_config` (name, `key`, params, value, remark, permission, create_time, creator_id, creator, update_time, modifier_id, modifier) VALUES('账号登录安全设置', 'AccountLoginSecurity', '[{"name":"登录验证码","model":"useCaptcha","placeholder":"是否启用登录验证码","options":"true,false"},{"name":"双因素校验(OTP)","model":"useOtp","placeholder":"是否启用双因素(OTP)校验","options":"true,false"},{"name":"OTP签发人","model":"otpIssuer","placeholder":"otp签发人"},{"name":"允许失败次数","model":"loginFailCount","placeholder":"登录失败n次后禁止登录"},{"name":"禁止登录时间","model":"loginFailMin","placeholder":"登录失败指定次数后禁止m分钟内再次登录"}]', '{"useCaptcha":"true","useOtp":"false","loginFailCount":"5","loginFailMin":"10","otpIssuer":"mayfly-go"}', '系统账号登录相关安全设置', 'admin,', '2023-06-17 11:02:11', 1, 'admin', '2023-06-17 14:18:07', 1, 'admin');
|
||||
INSERT INTO `t_sys_config` (name, `key`, params, value, remark, create_time, creator_id, creator, update_time, modifier_id, modifier, is_deleted, delete_time) VALUES('oauth2登录配置', 'Oauth2Login', '[{"name":"是否启用","model":"enable","placeholder":"是否启用oauth2登录","options":"true,false"},{"name":"名称","model":"name","placeholder":"oauth2名称"},{"name":"Client ID","model":"clientId","placeholder":"Client ID"},{"name":"Client Secret","model":"clientSecret","placeholder":"Client Secret"},{"name":"Authorization URL","model":"authorizationURL","placeholder":"Authorization URL"},{"name":"AccessToken URL","model":"accessTokenURL","placeholder":"AccessToken URL"},{"name":"Redirect URL","model":"redirectURL","placeholder":"本系统地址"},{"name":"Scopes","model":"scopes","placeholder":"Scopes"},{"name":"Resource URL","model":"resourceURL","placeholder":"获取用户信息资源地址"},{"name":"UserIdentifier","model":"userIdentifier","placeholder":"用户唯一标识字段;格式为type:fieldPath(string:username)"},{"name":"是否自动注册","model":"autoRegister","placeholder":"","options":"true,false"}]', '', 'oauth2登录相关配置信息', '2023-07-22 13:58:51', 1, 'admin', '2023-07-22 19:34:37', 1, 'admin', 0, NULL);
|
||||
INSERT INTO `t_sys_config` (name, `key`, params, value, remark, create_time, creator_id, creator, update_time, modifier_id, modifier) VALUES('账号登录安全设置', 'AccountLoginSecurity', '[{"name":"登录验证码","model":"useCaptcha","placeholder":"是否启用登录验证码","options":"true,false"},{"name":"双因素校验(OTP)","model":"useOtp","placeholder":"是否启用双因素(OTP)校验","options":"true,false"},{"name":"OTP签发人","model":"otpIssuer","placeholder":"otp签发人"},{"name":"允许失败次数","model":"loginFailCount","placeholder":"登录失败n次后禁止登录"},{"name":"禁止登录时间","model":"loginFailMin","placeholder":"登录失败指定次数后禁止m分钟内再次登录"}]', '{"useCaptcha":"true","useOtp":"false","loginFailCount":"5","loginFailMin":"10","otpIssuer":"mayfly-go"}', '系统账号登录相关安全设置', '2023-06-17 11:02:11', 1, 'admin', '2023-06-17 14:18:07', 1, 'admin');
|
||||
INSERT INTO `t_sys_config` (name, `key`, params, value, remark, permission, create_time, creator_id, creator, update_time, modifier_id, modifier, is_deleted, delete_time) VALUES('oauth2登录配置', 'Oauth2Login', '[{"name":"是否启用","model":"enable","placeholder":"是否启用oauth2登录","options":"true,false"},{"name":"名称","model":"name","placeholder":"oauth2名称"},{"name":"Client ID","model":"clientId","placeholder":"Client ID"},{"name":"Client Secret","model":"clientSecret","placeholder":"Client Secret"},{"name":"Authorization URL","model":"authorizationURL","placeholder":"Authorization URL"},{"name":"AccessToken URL","model":"accessTokenURL","placeholder":"AccessToken URL"},{"name":"Redirect URL","model":"redirectURL","placeholder":"本系统地址"},{"name":"Scopes","model":"scopes","placeholder":"Scopes"},{"name":"Resource URL","model":"resourceURL","placeholder":"获取用户信息资源地址"},{"name":"UserIdentifier","model":"userIdentifier","placeholder":"用户唯一标识字段;格式为type:fieldPath(string:username)"},{"name":"是否自动注册","model":"autoRegister","placeholder":"","options":"true,false"}]', '', 'oauth2登录相关配置信息', 'admin,', '2023-07-22 13:58:51', 1, 'admin', '2023-07-22 19:34:37', 1, 'admin', 0, NULL);
|
||||
INSERT INTO `t_sys_config` (name, `key`, params, value, remark, permission, create_time, creator_id, creator, update_time, modifier_id, modifier, is_deleted, delete_time) VALUES('ldap登录配置', 'LdapLogin', '[{"name":"是否启用","model":"enable","placeholder":"是否启用","options":"true,false"},{"name":"host","model":"host","placeholder":"host"},{"name":"port","model":"port","placeholder":"port"},{"name":"bindDN","model":"bindDN","placeholder":"LDAP 服务的管理员账号,如: \\"cn=admin,dc=example,dc=com\\""},{"name":"bindPwd","model":"bindPwd","placeholder":"LDAP 服务的管理员密码"},{"name":"baseDN","model":"baseDN","placeholder":"用户所在的 base DN, 如: \\"ou=users,dc=example,dc=com\\""},{"name":"userFilter","model":"userFilter","placeholder":"过滤用户的方式, 如: \\"(uid=%s)、(&(objectClass=organizationalPerson)(uid=%s))\\""},{"name":"uidMap","model":"uidMap","placeholder":"用户id和 LDAP 字段名之间的映射关系,如: cn"},{"name":"udnMap","model":"udnMap","placeholder":"用户姓名(dispalyName)和 LDAP 字段名之间的映射关系,如: displayName"},{"name":"emailMap","model":"emailMap","placeholder":"用户email和 LDAP 字段名之间的映射关系"},{"name":"skipTLSVerify","model":"skipTLSVerify","placeholder":"客户端是否跳过 TLS 证书验证","options":"true,false"},{"name":"安全协议","model":"securityProtocol","placeholder":"安全协议(为Null不使用安全协议),如: StartTLS, LDAPS","options":"Null,StartTLS,LDAPS"}]', '', 'ldap登录相关配置', 'admin,', '2023-08-25 21:47:20', 1, 'admin', '2023-08-25 22:56:07', 1, 'admin', 0, NULL);
|
||||
INSERT INTO `t_sys_config` (name, `key`, params, value, remark, create_time, creator_id, creator, update_time, modifier_id, modifier)VALUES ('是否启用水印', 'UseWartermark', NULL, '1', '1: 启用、0: 不启用', '2022-08-25 23:36:35', 1, 'admin', '2022-08-26 10:02:52', 1, 'admin');
|
||||
INSERT INTO `t_sys_config` (name, `key`, params, value, remark, create_time, creator_id, creator, update_time, modifier_id, modifier)VALUES ('数据库查询最大结果集', 'DbQueryMaxCount', '[]', '200', '允许sql查询的最大结果集数。注: 0=不限制', '2023-02-11 14:29:03', 1, 'admin', '2023-02-11 14:40:56', 1, 'admin');
|
||||
INSERT INTO `t_sys_config` (name, `key`, params, value, remark, create_time, creator_id, creator, update_time, modifier_id, modifier)VALUES ('数据库是否记录查询SQL', 'DbSaveQuerySQL', '[]', '0', '1: 记录、0:不记录', '2023-02-11 16:07:14', 1, 'admin', '2023-02-11 16:44:17', 1, 'admin');
|
||||
@@ -454,7 +455,7 @@ CREATE TABLE `t_sys_log` (
|
||||
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
|
||||
`type` tinyint(4) NOT NULL COMMENT '类型',
|
||||
`description` varchar(255) DEFAULT NULL COMMENT '描述',
|
||||
`req_param` varchar(1000) DEFAULT NULL COMMENT '请求信息',
|
||||
`req_param` varchar(2000) DEFAULT NULL COMMENT '请求信息',
|
||||
`resp` varchar(1000) DEFAULT NULL COMMENT '响应信息',
|
||||
`creator` varchar(36) NOT NULL COMMENT '调用者',
|
||||
`creator_id` bigint(20) NOT NULL COMMENT '调用者id',
|
||||
|
||||
@@ -43,7 +43,6 @@ type Config struct {
|
||||
Mysql *Mysql `yaml:"mysql"`
|
||||
Redis *Redis `yaml:"redis"`
|
||||
Log *Log `yaml:"log"`
|
||||
Ldap *Ldap `yaml:"ldap"`
|
||||
}
|
||||
|
||||
// 配置文件内容校验
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
package config
|
||||
|
||||
// FieldMapping 表示用户属性和 LDAP 字段名之间的映射关系
|
||||
type FieldMapping struct {
|
||||
// Identifier 表示用户标识
|
||||
Identifier string `yaml:"identifier,omitempty"`
|
||||
// DisplayName 表示用户姓名
|
||||
DisplayName string `yaml:"displayName,omitempty"`
|
||||
// Email 表示 Email 地址
|
||||
Email string `yaml:"email,omitempty"`
|
||||
}
|
||||
|
||||
// SecurityProtocol 表示连接 LDAP 服务器的安全协议
|
||||
type SecurityProtocol string
|
||||
|
||||
const (
|
||||
// SecurityProtocolStartTLS 表示 StartTLS 安全协议
|
||||
SecurityProtocolStartTLS SecurityProtocol = "starttls"
|
||||
// SecurityProtocolLDAPS 表示 LDAPS 安全协议
|
||||
SecurityProtocolLDAPS SecurityProtocol = "ldaps"
|
||||
)
|
||||
|
||||
// Ldap 是 LDAP 服务配置
|
||||
type Ldap struct {
|
||||
// Enabled 表示是否启用 LDAP 登录
|
||||
Enabled bool `yaml:"enabled"`
|
||||
// Host 是 LDAP 服务地址, 如: "ldap.example.com"
|
||||
Host string `yaml:"host"`
|
||||
// Port 是 LDAP 服务端口号, 如: 389
|
||||
Port int `yaml:"port"`
|
||||
// SkipTLSVerify 控制客户端是否跳过 TLS 证书验证
|
||||
SkipTLSVerify bool `yaml:"skipTlsVerify"`
|
||||
// BindDN 是 LDAP 服务的管理员账号,如: "cn=admin,dc=example,dc=com"
|
||||
BindDN string `yaml:"bindDn"`
|
||||
// BindPassword 是 LDAP 服务的管理员密码
|
||||
BindPassword string `yaml:"bindPassword"`
|
||||
// BaseDN 是用户所在的 base DN, 如: "ou=users,dc=example,dc=com".
|
||||
BaseDN string `yaml:"baseDn"`
|
||||
// UserFilter 是过滤用户的方式, 如: "(uid=%s)".
|
||||
UserFilter string `yaml:"userFilter"`
|
||||
// SecurityProtocol 是连接使用的 LDAP 安全协议(为空不使用安全协议),如: StartTLS, LDAPS
|
||||
SecurityProtocol SecurityProtocol `yaml:"securityProtocol"`
|
||||
// FieldMapping 表示用户属性和 LDAP 字段名之间的映射关系
|
||||
FieldMapping FieldMapping `yaml:"fieldMapping"`
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
package ldap
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"mayfly-go/pkg/config"
|
||||
"strings"
|
||||
|
||||
"github.com/go-ldap/ldap/v3"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type UserInfo struct {
|
||||
UserName string
|
||||
DisplayName string
|
||||
Email string
|
||||
}
|
||||
|
||||
func dial() (*ldap.Conn, error) {
|
||||
conf := config.Conf.Ldap
|
||||
addr := fmt.Sprintf("%s:%d", conf.Host, conf.Port)
|
||||
tlsConfig := &tls.Config{
|
||||
ServerName: conf.Host,
|
||||
InsecureSkipVerify: conf.SkipTLSVerify,
|
||||
}
|
||||
if conf.SecurityProtocol == config.SecurityProtocolLDAPS {
|
||||
conn, err := ldap.DialTLS("tcp", addr, tlsConfig)
|
||||
if err != nil {
|
||||
return nil, errors.Errorf("dial TLS: %v", err)
|
||||
}
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
conn, err := ldap.Dial("tcp", addr)
|
||||
if err != nil {
|
||||
return nil, errors.Errorf("dial: %v", err)
|
||||
}
|
||||
if conf.SecurityProtocol == config.SecurityProtocolStartTLS {
|
||||
if err = conn.StartTLS(tlsConfig); err != nil {
|
||||
_ = conn.Close()
|
||||
return nil, errors.Errorf("start TLS: %v", err)
|
||||
}
|
||||
}
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
// Connect 创建 LDAP 连接
|
||||
func Connect() (*ldap.Conn, error) {
|
||||
conn, err := dial()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Bind with a system account
|
||||
conf := config.Conf.Ldap
|
||||
err = conn.Bind(conf.BindDN, conf.BindPassword)
|
||||
if err != nil {
|
||||
_ = conn.Close()
|
||||
return nil, errors.Errorf("bind: %v", err)
|
||||
}
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
// Authenticate 通过 LDAP 验证用户名密码
|
||||
func Authenticate(username, password string) (*UserInfo, error) {
|
||||
conn, err := Connect()
|
||||
if err != nil {
|
||||
return nil, errors.Errorf("connect: %v", err)
|
||||
}
|
||||
defer func() { _ = conn.Close() }()
|
||||
|
||||
conf := config.Conf.Ldap
|
||||
sr, err := conn.Search(
|
||||
ldap.NewSearchRequest(
|
||||
conf.BaseDN,
|
||||
ldap.ScopeWholeSubtree,
|
||||
ldap.NeverDerefAliases,
|
||||
0,
|
||||
0,
|
||||
false,
|
||||
strings.ReplaceAll(conf.UserFilter, "%s", username),
|
||||
[]string{"dn", conf.FieldMapping.Identifier, conf.FieldMapping.DisplayName, conf.FieldMapping.Email},
|
||||
nil,
|
||||
),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, errors.Errorf("search user DN: %v", err)
|
||||
} else if len(sr.Entries) != 1 {
|
||||
return nil, errors.Errorf("expect 1 user DN but got %d", len(sr.Entries))
|
||||
}
|
||||
entry := sr.Entries[0]
|
||||
|
||||
// Bind as the user to verify their password
|
||||
err = conn.Bind(entry.DN, password)
|
||||
if err != nil {
|
||||
return nil, errors.Errorf("bind user: %v", err)
|
||||
}
|
||||
|
||||
userName := entry.GetAttributeValue(conf.FieldMapping.Identifier)
|
||||
if userName == "" {
|
||||
return nil, errors.Errorf("the attribute %q is not found or has empty value", conf.FieldMapping.Identifier)
|
||||
}
|
||||
return &UserInfo{
|
||||
UserName: userName,
|
||||
DisplayName: entry.GetAttributeValue(conf.FieldMapping.DisplayName),
|
||||
Email: entry.GetAttributeValue(conf.FieldMapping.Email),
|
||||
}, nil
|
||||
}
|
||||
Reference in New Issue
Block a user