Chore: project init
This commit is contained in:
54
pkg/middleware/auth.go
Normal file
54
pkg/middleware/auth.go
Normal file
@@ -0,0 +1,54 @@
|
||||
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 := token.Claims.(jwt.MapClaims)
|
||||
userID := uint(claims["user_id"].(float64))
|
||||
username := claims["username"].(string)
|
||||
role := claims["role"].(string)
|
||||
|
||||
// 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()
|
||||
}
|
||||
Reference in New Issue
Block a user