All checks were successful
Server CI/CD / deploy (push) Successful in 7s
- middleware: JWT MapClaims 타입 단언 패닉 → ok 패턴으로 방어 - auth/service: Redis Set 오류 처리, 지갑 생성 실패 시 유저 롤백 - auth/service: EnsureAdmin 지갑 생성 추가, Logout 리프레시 토큰도 삭제 - auth/service: 리프레시 토큰 발급(7일) 및 로테이션, REFRESH_SECRET 분리 - auth/handler: Login 응답에 refreshToken 포함, Refresh 핸들러 추가 - auth/handler: Logout 에러 처리 추가 - download/service: hashGameExeFromZip io.Copy 오류 처리 - download/handler: Content-Disposition mime.FormatMediaType으로 헤더 인젝션 방어 - announcement/handler: Update 빈 body 400 반환 - config: REFRESH_SECRET 환경변수 추가 - routes: POST /api/auth/refresh 엔드포인트 추가 - main: INTERNAL_API_KEY 미설정 시 경고 출력 - .env.example: 누락 환경변수 7개 보완 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
77 lines
2.4 KiB
Go
77 lines
2.4 KiB
Go
package middleware
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"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 세션 확인
|
|
key := fmt.Sprintf("session:%d", userID)
|
|
stored, err := database.RDB.Get(context.Background(), 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.
|
|
func ServerAuth(c *fiber.Ctx) error {
|
|
key := c.Get("X-API-Key")
|
|
if key == "" || config.C.InternalAPIKey == "" || key != config.C.InternalAPIKey {
|
|
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "유효하지 않은 API 키입니다"})
|
|
}
|
|
return c.Next()
|
|
}
|