feat(middlewares): 添加认证中间件以处理JWT授权
This commit is contained in:
@@ -5,5 +5,7 @@ func (r *Routes) Path() string {
|
||||
}
|
||||
|
||||
func (r *Routes) Middlewares() []any {
|
||||
return nil
|
||||
return []any{
|
||||
r.middlewares.Auth,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,5 +5,7 @@ func (r *Routes) Path() string {
|
||||
}
|
||||
|
||||
func (r *Routes) Middlewares() []any {
|
||||
return []any{}
|
||||
return []any{
|
||||
r.middlewares.Auth,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user