From 56e60e0972241bcbc17356b0783b10deb3d63524 Mon Sep 17 00:00:00 2001 From: Rogee Date: Tue, 13 Jan 2026 10:36:48 +0800 Subject: [PATCH] fix: enforce required auth middleware --- backend/app/http/v1/routes.manual.go | 2 +- backend/app/middlewares/middlewares.go | 25 +++++++++++++++++++++---- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/backend/app/http/v1/routes.manual.go b/backend/app/http/v1/routes.manual.go index 7f3e7a3..a01bcb9 100644 --- a/backend/app/http/v1/routes.manual.go +++ b/backend/app/http/v1/routes.manual.go @@ -7,6 +7,6 @@ func (r *Routes) Path() string { func (r *Routes) Middlewares() []any { return []any{ r.middlewares.TenantResolver, - r.middlewares.Auth, + r.middlewares.AuthRequired, } } diff --git a/backend/app/middlewares/middlewares.go b/backend/app/middlewares/middlewares.go index 46f7a66..6da38f0 100644 --- a/backend/app/middlewares/middlewares.go +++ b/backend/app/middlewares/middlewares.go @@ -31,13 +31,24 @@ func (f *Middlewares) Prepare() error { return nil } -func (m *Middlewares) Auth(ctx fiber.Ctx) error { +func (m *Middlewares) AuthOptional(ctx fiber.Ctx) error { + return m.authenticate(ctx, false) +} + +func (m *Middlewares) AuthRequired(ctx fiber.Ctx) error { if isPublicRoute(ctx) { - return ctx.Next() + return m.AuthOptional(ctx) } + return m.authenticate(ctx, true) +} + +func (m *Middlewares) authenticate(ctx fiber.Ctx, requireToken bool) error { authHeader := ctx.Get("Authorization") if authHeader == "" { - return errorx.ErrUnauthorized.WithMsg("Missing token") + if requireToken { + return errorx.ErrUnauthorized.WithMsg("Missing token") + } + return ctx.Next() } claims, err := m.jwt.Parse(authHeader) @@ -45,11 +56,17 @@ func (m *Middlewares) Auth(ctx fiber.Ctx) error { return errorx.ErrUnauthorized.WithCause(err).WithMsg("Invalid token") } - // get user model + // 获取用户信息,确保 token 与账号状态一致。 user, err := services.User.GetModelByID(ctx, claims.UserID) if err != nil { return errorx.ErrUnauthorized.WithCause(err).WithMsg("UserNotFound") } + if user.Status == consts.UserStatusBanned { + return errorx.ErrAccountDisabled + } + if user.Status == consts.UserStatusBanned { + return errorx.ErrAccountDisabled + } // Set Context ctx.Locals(consts.CtxKeyUser, user)