diff --git a/local/controller/membership.go b/local/controller/membership.go index 8daabb4..1136cdc 100644 --- a/local/controller/membership.go +++ b/local/controller/membership.go @@ -34,7 +34,7 @@ func NewMembershipController(service *service.MembershipService, auth *middlewar } routeGroups.Auth.Post("/login", mc.Login) - routeGroups.Auth.Post("/open-token", mc.GenerateOpenToken) + routeGroups.Auth.Post("/open-token", mc.auth.Authenticate, mc.GenerateOpenToken) usersGroup := routeGroups.Membership usersGroup.Use(mc.auth.Authenticate) diff --git a/local/middleware/auth.go b/local/middleware/auth.go index d3b26c2..bef899e 100644 --- a/local/middleware/auth.go +++ b/local/middleware/auth.go @@ -52,20 +52,28 @@ func NewAuthMiddleware(ms *service.MembershipService, cache *cache.InMemoryCache // Authenticate is a middleware for JWT authentication with enhanced security. func (m *AuthMiddleware) AuthenticateOpen(ctx *fiber.Ctx) error { - return m.AuthenticateWithHandler(m.openJWTHandler.JWTHandler, ctx) + return m.AuthenticateWithHandler(m.openJWTHandler.JWTHandler, true, ctx) } // Authenticate is a middleware for JWT authentication with enhanced security. func (m *AuthMiddleware) Authenticate(ctx *fiber.Ctx) error { - return m.AuthenticateWithHandler(m.jwtHandler, ctx) + return m.AuthenticateWithHandler(m.jwtHandler, false, ctx) } -func (m *AuthMiddleware) AuthenticateWithHandler(jwtHandler *jwt.JWTHandler, ctx *fiber.Ctx) error { +func (m *AuthMiddleware) AuthenticateWithHandler(jwtHandler *jwt.JWTHandler, isOpenToken bool, ctx *fiber.Ctx) error { // Log authentication attempt ip := ctx.IP() userAgent := ctx.Get("User-Agent") authHeader := ctx.Get("Authorization") + + if jwtHandler.IsOpenToken && !isOpenToken { + logging.Error("Authentication failed: attempting to authenticate with open token") + return ctx.Status(fiber.StatusUnauthorized).JSON(fiber.Map{ + "error": "Wrong token type used", + }) + } + if authHeader == "" { logging.Error("Authentication failed: missing Authorization header from IP %s", ip) return ctx.Status(fiber.StatusUnauthorized).JSON(fiber.Map{ diff --git a/local/utl/jwt/jwt.go b/local/utl/jwt/jwt.go index 04eb0f0..d9c0509 100644 --- a/local/utl/jwt/jwt.go +++ b/local/utl/jwt/jwt.go @@ -18,7 +18,8 @@ type Claims struct { } type JWTHandler struct { - SecretKey []byte + SecretKey []byte + IsOpenToken bool } type OpenJWTHandler struct { @@ -28,6 +29,7 @@ type OpenJWTHandler struct { // NewJWTHandler creates a new JWTHandler instance with the provided secret key. func NewOpenJWTHandler(jwtSecret string) *OpenJWTHandler { jwtHandler := NewJWTHandler(jwtSecret) + jwtHandler.IsOpenToken = true return &OpenJWTHandler{ JWTHandler: jwtHandler, }