From d87eac7d94fa9526896bfbaf9eb93ec736731a24 Mon Sep 17 00:00:00 2001 From: Rogee Date: Tue, 30 Dec 2025 18:06:16 +0800 Subject: [PATCH] =?UTF-8?q?feat(middlewares):=20=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E8=AE=A4=E8=AF=81=E4=B8=AD=E9=97=B4=E4=BB=B6=E4=BB=A5=E5=A4=84?= =?UTF-8?q?=E7=90=86JWT=E6=8E=88=E6=9D=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/http/super/v1/routes.manual.go | 4 +++- backend/app/http/v1/routes.manual.go | 4 +++- backend/app/middlewares/middlewares.go | 26 +++++++++++++++++++++- 3 files changed, 31 insertions(+), 3 deletions(-) diff --git a/backend/app/http/super/v1/routes.manual.go b/backend/app/http/super/v1/routes.manual.go index 2fc1a43..f151216 100644 --- a/backend/app/http/super/v1/routes.manual.go +++ b/backend/app/http/super/v1/routes.manual.go @@ -5,5 +5,7 @@ func (r *Routes) Path() string { } func (r *Routes) Middlewares() []any { - return nil + return []any{ + r.middlewares.Auth, + } } diff --git a/backend/app/http/v1/routes.manual.go b/backend/app/http/v1/routes.manual.go index 4802231..195c778 100644 --- a/backend/app/http/v1/routes.manual.go +++ b/backend/app/http/v1/routes.manual.go @@ -5,5 +5,7 @@ func (r *Routes) Path() string { } func (r *Routes) Middlewares() []any { - return []any{} + return []any{ + r.middlewares.Auth, + } } diff --git a/backend/app/middlewares/middlewares.go b/backend/app/middlewares/middlewares.go index fd68101..96bc75d 100644 --- a/backend/app/middlewares/middlewares.go +++ b/backend/app/middlewares/middlewares.go @@ -1,8 +1,12 @@ package middlewares import ( - log "github.com/sirupsen/logrus" + "quyun/v2/app/errorx" + "quyun/v2/pkg/consts" "quyun/v2/providers/jwt" + + "github.com/gofiber/fiber/v3" + log "github.com/sirupsen/logrus" ) // Middlewares provides reusable Fiber middlewares shared across modules. @@ -19,3 +23,23 @@ func (f *Middlewares) Prepare() error { f.log = log.WithField("module", "middleware") return nil } + +func (m *Middlewares) Auth(ctx fiber.Ctx) error { + authHeader := ctx.Get("Authorization") + if authHeader == "" { + return ctx.Next() + } + + claims, err := m.jwt.Parse(authHeader) + if err != nil { + return errorx.ErrUnauthorized.WithCause(err).WithMsg("Invalid token") + } + + // Set Context + ctx.Locals(consts.CtxKeyUser, claims.UserID) + if claims.TenantID > 0 { + ctx.Locals(consts.CtxKeyTenant, claims.TenantID) + } + + return ctx.Next() +}