密钥未配置属服务端配置错误,此前与 token 过期一样返回 401,把排查方向引向前端与刷新逻辑,是 P0-1 难以定位的直接原因。 改为识别 ErrSecretNotConfigured 后返回 500 server auth misconfigured 并打 FATAL 日志;JWTAuth、SoftJWTAuth 与 SSE 鉴权三处同步。
158 lines
4.4 KiB
Go
158 lines
4.4 KiB
Go
package jwt
|
||
|
||
import (
|
||
"context"
|
||
"errors"
|
||
"log"
|
||
"net/http"
|
||
"strings"
|
||
"time"
|
||
|
||
"feedsystem_video_go/internal/account"
|
||
"feedsystem_video_go/internal/auth"
|
||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||
|
||
"github.com/gin-gonic/gin"
|
||
)
|
||
|
||
// JWTAuth check jwt token and ensure it matches the currently stored token.
|
||
func JWTAuth(accountRepo *account.AccountRepository, cache *rediscache.Client) gin.HandlerFunc {
|
||
return func(c *gin.Context) {
|
||
authHeader := c.GetHeader("Authorization")
|
||
if authHeader == "" {
|
||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing authorization header"})
|
||
return
|
||
}
|
||
|
||
parts := strings.SplitN(authHeader, " ", 2)
|
||
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
|
||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid authorization header"})
|
||
return
|
||
}
|
||
|
||
tokenString := parts[1]
|
||
|
||
claims, err := auth.ParseToken(tokenString)
|
||
if err != nil {
|
||
// 服务端未正确配置密钥:这是 500 级故障,必须打 FATAL 日志,
|
||
// 绝不能伪装成 401,否则会出现静默误诊。
|
||
if errors.Is(err, auth.ErrSecretNotConfigured) {
|
||
log.Printf("FATAL: JWT secret not configured; %s %s rejected",
|
||
c.Request.Method, c.Request.URL.Path)
|
||
c.AbortWithStatusJSON(http.StatusInternalServerError,
|
||
gin.H{"error": "server auth misconfigured"})
|
||
return
|
||
}
|
||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid or expired token"})
|
||
return
|
||
}
|
||
check(c, claims, tokenString, accountRepo, cache)
|
||
}
|
||
}
|
||
|
||
func SoftJWTAuth(accountRepo *account.AccountRepository, cache *rediscache.Client) gin.HandlerFunc {
|
||
return func(c *gin.Context) {
|
||
authHeader := c.GetHeader("Authorization")
|
||
if authHeader == "" {
|
||
c.Next()
|
||
return
|
||
}
|
||
|
||
parts := strings.SplitN(authHeader, " ", 2)
|
||
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
|
||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid authorization header"})
|
||
return
|
||
}
|
||
|
||
tokenString := parts[1]
|
||
|
||
claims, err := auth.ParseToken(tokenString)
|
||
if err != nil {
|
||
// 服务端未正确配置密钥:这是 500 级故障,必须打 FATAL 日志,
|
||
// 绝不能伪装成 401,否则会出现静默误诊。
|
||
if errors.Is(err, auth.ErrSecretNotConfigured) {
|
||
log.Printf("FATAL: JWT secret not configured; %s %s rejected",
|
||
c.Request.Method, c.Request.URL.Path)
|
||
c.AbortWithStatusJSON(http.StatusInternalServerError,
|
||
gin.H{"error": "server auth misconfigured"})
|
||
return
|
||
}
|
||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid or expired token"})
|
||
return
|
||
}
|
||
|
||
check(c, claims, tokenString, accountRepo, cache)
|
||
}
|
||
}
|
||
|
||
func check(c *gin.Context, claims *auth.Claims, tokenString string, accountRepo *account.AccountRepository, cache *rediscache.Client) {
|
||
key := cache.Key("account:%d", claims.AccountID)
|
||
|
||
// 先查 Redis
|
||
if cache != nil {
|
||
cacheCtx, cancel := context.WithTimeout(c.Request.Context(), 50*time.Millisecond)
|
||
defer cancel()
|
||
|
||
b, err := cache.GetBytes(cacheCtx, key)
|
||
if err == nil {
|
||
if string(b) != tokenString {
|
||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "token has been revoked"})
|
||
return
|
||
}
|
||
c.Set("accountID", claims.AccountID)
|
||
c.Set("username", claims.Username)
|
||
c.Next()
|
||
return
|
||
}
|
||
}
|
||
|
||
// Redis 故障/未启用:查 DB 兜底
|
||
accountInfo, err := accountRepo.FindByID(c.Request.Context(), claims.AccountID)
|
||
if err != nil || accountInfo.Token == "" || accountInfo.Token != tokenString {
|
||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "token has been revoked"})
|
||
return
|
||
}
|
||
|
||
if cache != nil {
|
||
cacheCtx, cancel := context.WithTimeout(c.Request.Context(), 50*time.Millisecond)
|
||
defer cancel()
|
||
|
||
if err := cache.SetBytes(cacheCtx, key, []byte(tokenString), 24*time.Hour); err != nil {
|
||
log.Printf("failed to set cache: %v", err)
|
||
}
|
||
}
|
||
|
||
c.Set("accountID", claims.AccountID)
|
||
c.Set("username", claims.Username)
|
||
c.Next()
|
||
|
||
}
|
||
|
||
func GetAccountID(c *gin.Context) (uint, error) {
|
||
uidValue, exists := c.Get("accountID")
|
||
if !exists {
|
||
return 0, errors.New("accountID not found")
|
||
}
|
||
|
||
accountID, ok := uidValue.(uint)
|
||
if !ok {
|
||
return 0, errors.New("accountID has invalid type")
|
||
}
|
||
|
||
return accountID, nil
|
||
}
|
||
|
||
func GetUsername(c *gin.Context) (string, error) {
|
||
val, exists := c.Get("username")
|
||
if !exists {
|
||
return "", errors.New("username not found")
|
||
}
|
||
|
||
username, ok := val.(string)
|
||
if !ok {
|
||
return "", errors.New("username has invalid type")
|
||
}
|
||
|
||
return username, nil
|
||
}
|