- /health + /ready 엔드포인트 추가 (DB/Redis 상태 확인) - RequestID 미들웨어 + 구조화 JSON 로깅 - 체인 트랜잭션 per-user rate limit (20 req/min) - DB 커넥션 풀 설정 (MaxOpen 25, MaxIdle 10, MaxLifetime 5m) - Graceful Shutdown 시 Redis/MySQL 연결 정리 - Dockerfile HEALTHCHECK 추가 - CI에 go vet + 빌드 검증 단계 추가 (deploy 전 실행) - 보스 레이드 클라이언트 입장 API (JWT 인증) - Player 프로필 모듈 추가 Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
84 lines
2.7 KiB
Go
84 lines
2.7 KiB
Go
package middleware
|
|
|
|
import (
|
|
"context"
|
|
"crypto/subtle"
|
|
"fmt"
|
|
"log"
|
|
"strings"
|
|
|
|
"a301_server/pkg/config"
|
|
"a301_server/pkg/database"
|
|
"github.com/gofiber/fiber/v2"
|
|
"github.com/golang-jwt/jwt/v5"
|
|
)
|
|
|
|
func Auth(c *fiber.Ctx) error {
|
|
header := c.Get("Authorization")
|
|
if !strings.HasPrefix(header, "Bearer ") {
|
|
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "인증이 필요합니다"})
|
|
}
|
|
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 []byte(config.C.JWTSecret), nil
|
|
})
|
|
if err != nil || !token.Valid {
|
|
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "유효하지 않은 토큰입니다"})
|
|
}
|
|
|
|
claims, ok := token.Claims.(jwt.MapClaims)
|
|
if !ok {
|
|
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "유효하지 않은 토큰입니다"})
|
|
}
|
|
userIDFloat, ok := claims["user_id"].(float64)
|
|
if !ok {
|
|
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "유효하지 않은 토큰입니다"})
|
|
}
|
|
username, ok := claims["username"].(string)
|
|
if !ok {
|
|
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "유효하지 않은 토큰입니다"})
|
|
}
|
|
role, ok := claims["role"].(string)
|
|
if !ok {
|
|
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "유효하지 않은 토큰입니다"})
|
|
}
|
|
userID := uint(userIDFloat)
|
|
|
|
// Redis 세션 확인
|
|
ctx, cancel := context.WithTimeout(context.Background(), redisTimeout)
|
|
defer cancel()
|
|
key := fmt.Sprintf("session:%d", userID)
|
|
stored, err := database.RDB.Get(ctx, key).Result()
|
|
if err != nil || stored != tokenStr {
|
|
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "만료되었거나 로그아웃된 세션입니다"})
|
|
}
|
|
|
|
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 c.Status(fiber.StatusForbidden).JSON(fiber.Map{"error": "관리자 권한이 필요합니다"})
|
|
}
|
|
return c.Next()
|
|
}
|
|
|
|
// ServerAuth validates X-API-Key header for server-to-server communication.
|
|
// Uses constant-time comparison to prevent timing attacks.
|
|
func ServerAuth(c *fiber.Ctx) error {
|
|
key := c.Get("X-API-Key")
|
|
expected := config.C.InternalAPIKey
|
|
if key == "" || expected == "" || subtle.ConstantTimeCompare([]byte(key), []byte(expected)) != 1 {
|
|
log.Printf("ServerAuth 실패: IP=%s, Path=%s", c.IP(), c.Path())
|
|
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "유효하지 않은 API 키입니다"})
|
|
}
|
|
return c.Next()
|
|
}
|