[feature/backend] implement /auth/logout handling + overall enhancement
This commit is contained in:
parent
d8d8e4b0d7
commit
e5fc8691bf
12 changed files with 420 additions and 64 deletions
|
@ -10,10 +10,11 @@ import (
|
|||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/rs/zerolog/log"
|
||||
"tss-rocks-be/internal/service"
|
||||
)
|
||||
|
||||
// AuthMiddleware creates a middleware for JWT authentication
|
||||
func AuthMiddleware(jwtSecret string) gin.HandlerFunc {
|
||||
func AuthMiddleware(jwtSecret string, tokenBlacklist *service.TokenBlacklist) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" {
|
||||
|
@ -29,8 +30,20 @@ func AuthMiddleware(jwtSecret string) gin.HandlerFunc {
|
|||
return
|
||||
}
|
||||
|
||||
token, err := jwt.Parse(parts[1], func(token *jwt.Token) (interface{}, error) {
|
||||
tokenStr := parts[1]
|
||||
|
||||
// 检查 token 是否在黑名单中
|
||||
if tokenBlacklist.IsBlacklisted(tokenStr) {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Token has been revoked"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
|
||||
// 添加调试输出
|
||||
log.Debug().Str("token", tokenStr).Msg("Parsing token")
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
log.Error().Str("method", token.Method.Alg()).Msg("Invalid signing method")
|
||||
return nil, jwt.ErrSignatureInvalid
|
||||
}
|
||||
return []byte(jwtSecret), nil
|
||||
|
@ -62,42 +75,43 @@ func AuthMiddleware(jwtSecret string) gin.HandlerFunc {
|
|||
Interface("value", sub).
|
||||
Msg("User ID from token")
|
||||
|
||||
var userID int
|
||||
// 将用户 ID 转换为字符串
|
||||
var userIDStr string
|
||||
switch v := sub.(type) {
|
||||
case string:
|
||||
var err error
|
||||
userID, err = strconv.Atoi(v)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Str("sub", v).Msg("Failed to convert string user ID to int")
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid user ID format"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
userIDStr = v
|
||||
case float64:
|
||||
userID = int(v)
|
||||
userIDStr = strconv.FormatFloat(v, 'f', 0, 64)
|
||||
case json.Number:
|
||||
var err error
|
||||
userID, err = strconv.Atoi(v.String())
|
||||
if err != nil {
|
||||
log.Error().Err(err).Str("sub", v.String()).Msg("Failed to convert json.Number user ID to int")
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid user ID format"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
userIDStr = v.String()
|
||||
default:
|
||||
userIDStr = fmt.Sprintf("%v", v)
|
||||
}
|
||||
|
||||
// 验证用户 ID 是否为有效的数字字符串
|
||||
_, err := strconv.Atoi(userIDStr)
|
||||
if err != nil {
|
||||
log.Error().
|
||||
Str("type", fmt.Sprintf("%T", sub)).
|
||||
Interface("value", sub).
|
||||
Msg("Unexpected user ID type")
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid user ID type"})
|
||||
Err(err).
|
||||
Str("user_id", userIDStr).
|
||||
Msg("Invalid user ID format")
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid user ID format"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// 将 userID 转换为 int64 以确保类型一致性
|
||||
c.Set("user_id", int64(userID))
|
||||
if roles, ok := claims["roles"].([]interface{}); ok {
|
||||
c.Set("user_roles", roles)
|
||||
// 设置用户 ID
|
||||
c.Set("user_id", userIDStr)
|
||||
|
||||
// 设置用户角色
|
||||
if role, ok := claims["role"].(string); ok {
|
||||
log.Debug().Str("role", role).Msg("Found user role")
|
||||
c.Set("user_role", role)
|
||||
} else {
|
||||
log.Error().Interface("role", claims["role"]).Msg("Invalid or missing role claim")
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid role format"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
} else {
|
||||
|
|
|
@ -2,6 +2,7 @@ package middleware
|
|||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
@ -9,16 +10,22 @@ import (
|
|||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"tss-rocks-be/internal/service"
|
||||
)
|
||||
|
||||
func createTestToken(secret string, claims jwt.MapClaims) string {
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
signedToken, _ := token.SignedString([]byte(secret))
|
||||
signedToken, err := token.SignedString([]byte(secret))
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("Failed to sign token: %v", err))
|
||||
}
|
||||
return signedToken
|
||||
}
|
||||
|
||||
func TestAuthMiddleware(t *testing.T) {
|
||||
jwtSecret := "test-secret"
|
||||
tokenBlacklist := service.NewTokenBlacklist()
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
|
@ -55,7 +62,7 @@ func TestAuthMiddleware(t *testing.T) {
|
|||
name: "Valid token",
|
||||
setupAuth: func(req *http.Request) {
|
||||
claims := jwt.MapClaims{
|
||||
"sub": "user123",
|
||||
"sub": "123",
|
||||
"role": "user",
|
||||
"exp": time.Now().Add(time.Hour).Unix(),
|
||||
}
|
||||
|
@ -64,14 +71,14 @@ func TestAuthMiddleware(t *testing.T) {
|
|||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
checkUserData: true,
|
||||
expectedUserID: "user123",
|
||||
expectedUserID: "123",
|
||||
expectedRole: "user",
|
||||
},
|
||||
{
|
||||
name: "Expired token",
|
||||
setupAuth: func(req *http.Request) {
|
||||
claims := jwt.MapClaims{
|
||||
"sub": "user123",
|
||||
"sub": "123",
|
||||
"role": "user",
|
||||
"exp": time.Now().Add(-time.Hour).Unix(),
|
||||
}
|
||||
|
@ -89,18 +96,22 @@ func TestAuthMiddleware(t *testing.T) {
|
|||
router := gin.New()
|
||||
|
||||
// 添加认证中间件
|
||||
router.Use(AuthMiddleware(jwtSecret))
|
||||
router.Use(func(c *gin.Context) {
|
||||
// 设置日志级别为 debug
|
||||
gin.SetMode(gin.DebugMode)
|
||||
c.Next()
|
||||
}, AuthMiddleware(jwtSecret, tokenBlacklist))
|
||||
|
||||
// 测试路由
|
||||
router.GET("/test", func(c *gin.Context) {
|
||||
if tc.checkUserData {
|
||||
userID, exists := c.Get("user_id")
|
||||
assert.True(t, exists)
|
||||
assert.Equal(t, tc.expectedUserID, userID)
|
||||
assert.True(t, exists, "user_id should exist in context")
|
||||
assert.Equal(t, tc.expectedUserID, userID, "user_id should match")
|
||||
|
||||
role, exists := c.Get("user_role")
|
||||
assert.True(t, exists)
|
||||
assert.Equal(t, tc.expectedRole, role)
|
||||
assert.True(t, exists, "user_role should exist in context")
|
||||
assert.Equal(t, tc.expectedRole, role, "user_role should match")
|
||||
}
|
||||
c.Status(http.StatusOK)
|
||||
})
|
||||
|
@ -114,13 +125,13 @@ func TestAuthMiddleware(t *testing.T) {
|
|||
router.ServeHTTP(rec, req)
|
||||
|
||||
// 验证响应
|
||||
assert.Equal(t, tc.expectedStatus, rec.Code)
|
||||
assert.Equal(t, tc.expectedStatus, rec.Code, "HTTP status code should match")
|
||||
|
||||
if tc.expectedBody != nil {
|
||||
var response map[string]string
|
||||
err := json.NewDecoder(rec.Body).Decode(&response)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, tc.expectedBody, response)
|
||||
assert.NoError(t, err, "Response body should be valid JSON")
|
||||
assert.Equal(t, tc.expectedBody, response, "Response body should match")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue