二阶段差不多
This commit is contained in:
@@ -0,0 +1,98 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"mail_go/config"
|
||||
|
||||
"github.com/go-ldap/ldap/v3"
|
||||
)
|
||||
|
||||
// LDAPProvider 实现 LDAP 认证
|
||||
type LDAPProvider struct {
|
||||
cfg config.AuthConfig
|
||||
}
|
||||
|
||||
// NewLDAPProvider 创建 LDAP 认证提供者
|
||||
func NewLDAPProvider(cfg config.AuthConfig) *LDAPProvider {
|
||||
return &LDAPProvider{cfg: cfg}
|
||||
}
|
||||
|
||||
// Name 返回提供者名称
|
||||
func (p *LDAPProvider) Name() string { return "ldap" }
|
||||
|
||||
// Authenticate 使用 LDAP 验证用户凭据,返回邮箱地址
|
||||
func (p *LDAPProvider) Authenticate(credentials map[string]string) (string, error) {
|
||||
username := credentials["username"]
|
||||
password := credentials["password"]
|
||||
if username == "" || password == "" {
|
||||
return "", fmt.Errorf("用户名和密码不能为空")
|
||||
}
|
||||
|
||||
// 使用 go-ldap 库连接
|
||||
l, err := ldap.DialURL(p.cfg.LDAPServer)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("LDAP 连接失败: %w", err)
|
||||
}
|
||||
defer l.Close()
|
||||
|
||||
if p.cfg.LDAPUseTLS {
|
||||
if err := l.StartTLS(&tls.Config{}); err != nil {
|
||||
return "", fmt.Errorf("LDAP TLS 握手失败: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 用绑定DN搜索用户
|
||||
if err := l.Bind(p.cfg.LDAPBindDN, p.cfg.LDAPBindPassword); err != nil {
|
||||
return "", fmt.Errorf("LDAP 绑定失败: %w", err)
|
||||
}
|
||||
|
||||
// 搜索用户
|
||||
filter := fmt.Sprintf(p.cfg.LDAPSearchFilter, ldap.EscapeFilter(username))
|
||||
searchReq := ldap.NewSearchRequest(
|
||||
p.cfg.LDAPSearchBase,
|
||||
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
|
||||
filter,
|
||||
[]string{"mail", "uid", "cn"},
|
||||
nil,
|
||||
)
|
||||
|
||||
sr, err := l.Search(searchReq)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("LDAP 搜索失败: %w", err)
|
||||
}
|
||||
if len(sr.Entries) == 0 {
|
||||
return "", fmt.Errorf("LDAP 用户不存在")
|
||||
}
|
||||
|
||||
entry := sr.Entries[0]
|
||||
userDN := entry.DN
|
||||
email := entry.GetAttributeValue("mail")
|
||||
|
||||
// 验证用户密码
|
||||
if err := l.Bind(userDN, password); err != nil {
|
||||
return "", fmt.Errorf("LDAP 认证失败")
|
||||
}
|
||||
|
||||
// 如果没有邮箱属性,尝试从搜索基准拼凑
|
||||
if email == "" {
|
||||
// 从 LDAPSearchBase 提取域名部分,如 ou=users,dc=example,dc=com -> example.com
|
||||
parts := strings.Split(p.cfg.LDAPSearchBase, ",")
|
||||
var dcParts []string
|
||||
for _, part := range parts {
|
||||
part = strings.TrimSpace(part)
|
||||
if strings.HasPrefix(part, "dc=") {
|
||||
dcParts = append(dcParts, strings.TrimPrefix(part, "dc="))
|
||||
}
|
||||
}
|
||||
if len(dcParts) > 0 {
|
||||
email = username + "@" + strings.Join(dcParts, ".")
|
||||
} else {
|
||||
email = username
|
||||
}
|
||||
}
|
||||
|
||||
return email, nil
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"mail_go/config"
|
||||
|
||||
"golang.org/x/oauth2"
|
||||
"golang.org/x/oauth2/github"
|
||||
"golang.org/x/oauth2/google"
|
||||
)
|
||||
|
||||
// OAuth2Provider 实现 OAuth2 认证
|
||||
type OAuth2Provider struct {
|
||||
cfg config.AuthConfig
|
||||
config *oauth2.Config
|
||||
}
|
||||
|
||||
// NewOAuth2Provider 创建 OAuth2 认证提供者
|
||||
func NewOAuth2Provider(cfg config.AuthConfig) *OAuth2Provider {
|
||||
p := &OAuth2Provider{cfg: cfg}
|
||||
|
||||
var endpoint oauth2.Endpoint
|
||||
switch cfg.OAuth2Provider {
|
||||
case "google":
|
||||
endpoint = google.Endpoint
|
||||
case "github":
|
||||
endpoint = github.Endpoint
|
||||
default:
|
||||
endpoint = oauth2.Endpoint{
|
||||
AuthURL: fmt.Sprintf("https://%s/login/oauth/authorize", cfg.OAuth2Provider),
|
||||
TokenURL: fmt.Sprintf("https://%s/login/oauth/access_token", cfg.OAuth2Provider),
|
||||
}
|
||||
}
|
||||
|
||||
p.config = &oauth2.Config{
|
||||
ClientID: cfg.OAuth2ClientID,
|
||||
ClientSecret: cfg.OAuth2ClientSecret,
|
||||
RedirectURL: cfg.OAuth2RedirectURL,
|
||||
Scopes: []string{"email", "profile"},
|
||||
Endpoint: endpoint,
|
||||
}
|
||||
|
||||
return p
|
||||
}
|
||||
|
||||
// Name 返回提供者名称
|
||||
func (p *OAuth2Provider) Name() string { return "oauth2" }
|
||||
|
||||
// GetAuthURL 返回 OAuth2 授权重定向URL
|
||||
func (p *OAuth2Provider) GetAuthURL(state string) string {
|
||||
return p.config.AuthCodeURL(state)
|
||||
}
|
||||
|
||||
// HandleCallback 处理 OAuth2 回调,返回用户邮箱
|
||||
func (p *OAuth2Provider) HandleCallback(code string) (string, error) {
|
||||
token, err := p.config.Exchange(context.Background(), code)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("OAuth2 token 交换失败: %w", err)
|
||||
}
|
||||
|
||||
email, err := p.fetchUserEmail(token)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return email, nil
|
||||
}
|
||||
|
||||
// fetchUserEmail 从 OAuth2 提供者获取用户邮箱
|
||||
func (p *OAuth2Provider) fetchUserEmail(token *oauth2.Token) (string, error) {
|
||||
client := p.config.Client(context.Background(), token)
|
||||
|
||||
var userinfoURL string
|
||||
switch p.cfg.OAuth2Provider {
|
||||
case "google":
|
||||
userinfoURL = "https://www.googleapis.com/oauth2/v2/userinfo"
|
||||
case "github":
|
||||
userinfoURL = "https://api.github.com/user/emails"
|
||||
default:
|
||||
return "", fmt.Errorf("不支持的 OAuth2 提供者: %s", p.cfg.OAuth2Provider)
|
||||
}
|
||||
|
||||
resp, err := client.Get(userinfoURL)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("获取用户信息失败: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("读取用户信息失败: %w", err)
|
||||
}
|
||||
|
||||
if p.cfg.OAuth2Provider == "google" {
|
||||
var userInfo struct {
|
||||
Email string `json:"email"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &userInfo); err != nil {
|
||||
return "", fmt.Errorf("解析Google用户信息失败: %w", err)
|
||||
}
|
||||
if userInfo.Email == "" {
|
||||
return "", fmt.Errorf("Google账户未关联邮箱")
|
||||
}
|
||||
return userInfo.Email, nil
|
||||
}
|
||||
|
||||
if p.cfg.OAuth2Provider == "github" {
|
||||
var emails []struct {
|
||||
Email string `json:"email"`
|
||||
Primary bool `json:"primary"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &emails); err != nil {
|
||||
return "", fmt.Errorf("解析GitHub用户信息失败: %w", err)
|
||||
}
|
||||
for _, e := range emails {
|
||||
if e.Primary {
|
||||
return e.Email, nil
|
||||
}
|
||||
}
|
||||
if len(emails) > 0 {
|
||||
return emails[0].Email, nil
|
||||
}
|
||||
return "", fmt.Errorf("GitHub账户未关联邮箱")
|
||||
}
|
||||
|
||||
return "", fmt.Errorf("OAuth2 邮箱获取尚未实现")
|
||||
}
|
||||
|
||||
// Authenticate 实现 Provider 接口(OAuth2 不使用此方法,通过回调流程认证)
|
||||
func (p *OAuth2Provider) Authenticate(credentials map[string]string) (string, error) {
|
||||
return "", fmt.Errorf("OAuth2 不支持直接认证,请使用回调流程")
|
||||
}
|
||||
|
||||
// Ensure interfaces are satisfied
|
||||
var (
|
||||
_ Provider = (*LDAPProvider)(nil)
|
||||
_ Provider = (*OAuth2Provider)(nil)
|
||||
)
|
||||
@@ -0,0 +1,9 @@
|
||||
package auth
|
||||
|
||||
// Provider 定义外部认证接口
|
||||
type Provider interface {
|
||||
// Authenticate 验证外部凭据,返回邮箱地址
|
||||
Authenticate(credentials map[string]string) (email string, err error)
|
||||
// Name 返回提供者名称
|
||||
Name() string
|
||||
}
|
||||
Reference in New Issue
Block a user