| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- package auth
-
- import (
- "encoding/base64"
- "net/http"
- "strings"
- "time"
-
- "git.x2erp.com/qdy/go-base/config"
- "git.x2erp.com/qdy/go-base/ctx"
- )
-
- // BasicAuth 简化的Basic认证中间件
- func BasicAuth(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- // 1. 检查认证头
- authHeader := r.Header.Get("Authorization")
- if authHeader == "" {
- unauthorized(w, "缺少认证信息")
- return
- }
-
- // 2. 检查Basic格式
- if !strings.HasPrefix(authHeader, "Basic ") {
- unauthorized(w, "认证格式错误,请使用Basic认证")
- return
- }
-
- // 3. 解码凭证
- base64Creds := strings.TrimPrefix(authHeader, "Basic ")
- credsBytes, err := base64.StdEncoding.DecodeString(base64Creds)
- if err != nil {
- unauthorized(w, "认证信息解码失败")
- return
- }
-
- // 4. 分割用户名密码
- creds := string(credsBytes)
- parts := strings.SplitN(creds, ":", 2)
- if len(parts) != 2 {
- unauthorized(w, "用户名密码格式错误")
- return
- }
-
- username := parts[0]
- password := parts[1]
-
- // 5. 验证用户名密码
- userID, tenantID, ok := verifyCredentials(username, password)
- if !ok {
- unauthorized(w, "用户名或密码错误")
- return
- }
-
- // 6. 创建请求上下文
- traceID := r.Header.Get("X-Trace-ID")
- if traceID == "" {
- // 生成简单的时间戳追踪ID
- traceID = time.Now().Format("20060102150405.000")
- }
-
- cfg := config.GetConfig()
-
- requestCtx := &ctx.RequestContext{
- ServiceName: cfg.GetServiceConfig().ServiceName,
- InstanceName: cfg.GetServiceConfig().InstanceName,
- TraceID: traceID,
- TenantID: tenantID,
- UserID: userID,
- Username: username,
- }
-
- // 7. 保存到请求
- r = ctx.SaveContext(r, requestCtx)
-
- // 8. 继续处理
- next.ServeHTTP(w, r)
- })
- }
-
- // 验证用户名密码(简单示例)
- func verifyCredentials(username, password string) (userID, tenantID string, ok bool) {
-
- // 这里替换为你的实际验证逻辑
- cfg := config.GetConfig()
- sysUsername := cfg.GetServiceConfig().Username
- sysPassword := cfg.GetServiceConfig().Password
-
- if username == sysUsername && password == sysPassword {
- return sysUsername, "tenant-admin", true
- }
- return "", "", false
- }
|