refactor: introduce DTOs for claims, session, and request handling
feat: add token validation service method refactor: update middleware to use structured DTOs feat: implement session info propagation through context refactor: replace ad-hoc structs with DTOs in middleware chore: organize auth-related data structures
This commit is contained in:
@@ -21,6 +21,7 @@ import (
|
||||
"context"
|
||||
"easywish/config"
|
||||
"easywish/internal/database"
|
||||
"easywish/internal/dto"
|
||||
"easywish/internal/utils/enums"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -34,14 +35,6 @@ import (
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
type Claims struct {
|
||||
Username string `json:"username"`
|
||||
Role enums.Role `json:"role"`
|
||||
Type enums.JwtTokenType `json:"type"`
|
||||
Session string `json:"session"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
// XXX: cluttered; move cache & database check to auth service
|
||||
func AuthMiddleware(log *zap.Logger, dbctx database.DbContext, redisClient *redis.Client) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
@@ -49,8 +42,12 @@ func AuthMiddleware(log *zap.Logger, dbctx database.DbContext, redisClient *redi
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
|
||||
if authHeader == "" {
|
||||
c.Set("username", nil)
|
||||
c.Set("role", enums.GuestRole)
|
||||
|
||||
c.Set("session_info", dto.SessionInfo{
|
||||
Username: "",
|
||||
Session: "",
|
||||
Role: enums.GuestRole},
|
||||
)
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
@@ -59,7 +56,7 @@ func AuthMiddleware(log *zap.Logger, dbctx database.DbContext, redisClient *redi
|
||||
|
||||
token, err := jwt.ParseWithClaims(
|
||||
tokenString,
|
||||
&Claims{},
|
||||
&dto.UserClaims{},
|
||||
func(token *jwt.Token) (any, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||
@@ -77,7 +74,7 @@ func AuthMiddleware(log *zap.Logger, dbctx database.DbContext, redisClient *redi
|
||||
return
|
||||
}
|
||||
|
||||
if claims, ok := token.Claims.(*Claims); ok && token.Valid {
|
||||
if claims, ok := token.Claims.(*dto.UserClaims); ok && token.Valid {
|
||||
|
||||
if claims.Type != enums.JwtAccessTokenType {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Not an access token"})
|
||||
@@ -142,8 +139,12 @@ func AuthMiddleware(log *zap.Logger, dbctx database.DbContext, redisClient *redi
|
||||
return
|
||||
}
|
||||
|
||||
c.Set("username", claims.Username)
|
||||
c.Set("role", claims.Role)
|
||||
c.Set("session_info", dto.SessionInfo{
|
||||
Username: claims.Username,
|
||||
Session: claims.Session,
|
||||
Role: claims.Role,
|
||||
})
|
||||
|
||||
c.Next()
|
||||
} else {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid claims"})
|
||||
|
||||
Reference in New Issue
Block a user