package middleware import ( "context" "crypto/subtle" "fmt" "log" "strings" "a301_server/pkg/apperror" "github.com/gofiber/fiber/v2" "github.com/golang-jwt/jwt/v5" "github.com/redis/go-redis/v9" ) // Auth returns a middleware that validates JWT tokens and checks Redis sessions. func Auth(rdb *redis.Client, jwtSecret string) fiber.Handler { secretBytes := []byte(jwtSecret) return func(c *fiber.Ctx) error { header := c.Get("Authorization") if !strings.HasPrefix(header, "Bearer ") { return apperror.ErrUnauthorized } tokenStr := strings.TrimPrefix(header, "Bearer ") token, err := jwt.Parse(tokenStr, func(t *jwt.Token) (any, error) { if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("unexpected signing method") } return secretBytes, nil }) if err != nil || !token.Valid { return apperror.Unauthorized("유효하지 않은 토큰입니다") } claims, ok := token.Claims.(jwt.MapClaims) if !ok { return apperror.Unauthorized("유효하지 않은 토큰입니다") } userIDFloat, ok := claims["user_id"].(float64) if !ok { return apperror.Unauthorized("유효하지 않은 토큰입니다") } username, ok := claims["username"].(string) if !ok { return apperror.Unauthorized("유효하지 않은 토큰입니다") } role, ok := claims["role"].(string) if !ok { return apperror.Unauthorized("유효하지 않은 토큰입니다") } userID := uint(userIDFloat) // Redis 세션 확인 ctx, cancel := context.WithTimeout(context.Background(), redisTimeout) defer cancel() key := fmt.Sprintf("session:%d", userID) stored, err := rdb.Get(ctx, key).Result() if err != nil || stored != tokenStr { return apperror.Unauthorized("만료되었거나 로그아웃된 세션입니다") } c.Locals("userID", userID) c.Locals("username", username) c.Locals("role", role) return c.Next() } } func AdminOnly(c *fiber.Ctx) error { if c.Locals("role") != "admin" { return apperror.ErrForbidden } return c.Next() } // ServerAuth returns a middleware that validates X-API-Key header for server-to-server communication. // Uses constant-time comparison to prevent timing attacks. func ServerAuth(apiKey string) fiber.Handler { expectedBytes := []byte(apiKey) return func(c *fiber.Ctx) error { key := c.Get("X-API-Key") if key == "" || len(expectedBytes) == 0 || subtle.ConstantTimeCompare([]byte(key), expectedBytes) != 1 { log.Printf("ServerAuth 실패: IP=%s, Path=%s", c.IP(), c.Path()) return apperror.Unauthorized("유효하지 않은 API 키입니다") } return c.Next() } }