chat/internal/middleware/anon_middleware.go

79 lines
1.8 KiB
Go
Raw Normal View History

2025-12-31 09:36:02 +00:00
package middleware
import (
"chat/internal/config"
"context"
"net/http"
"strings"
"github.com/golang-jwt/jwt/v4"
"github.com/zeromicro/go-zero/core/logx"
)
type AnonMiddleware struct {
jwtSecret string
}
func NewAnonMiddleware(c config.Config) *AnonMiddleware {
return &AnonMiddleware{
jwtSecret: c.JWT.Secret,
}
}
func (m *AnonMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// 從 Authorization header 提取 token
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
http.Error(w, "Authorization header is required", http.StatusUnauthorized)
return
}
// 移除 "Bearer " 前綴
parts := strings.Split(authHeader, " ")
if len(parts) != 2 || parts[0] != "Bearer" {
http.Error(w, "Invalid authorization header format", http.StatusUnauthorized)
return
}
tokenString := parts[1]
// 解析和驗證 JWT
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
// 驗證簽名方法
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, jwt.ErrSignatureInvalid
}
return []byte(m.jwtSecret), nil
})
if err != nil {
logx.Errorf("Failed to parse JWT: %v", err)
http.Error(w, "Invalid token", http.StatusUnauthorized)
return
}
if !token.Valid {
http.Error(w, "Invalid token", http.StatusUnauthorized)
return
}
// 提取 UID
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
http.Error(w, "Invalid token claims", http.StatusUnauthorized)
return
}
uid, ok := claims["uid"].(string)
if !ok || uid == "" {
http.Error(w, "UID not found in token", http.StatusUnauthorized)
return
}
// 將 UID 存入 context
ctx := context.WithValue(r.Context(), "uid", uid)
next(w, r.WithContext(ctx))
}
}