fix: enforce required auth middleware
This commit is contained in:
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,25 +31,42 @@ 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 == "" {
|
||||
if requireToken {
|
||||
return errorx.ErrUnauthorized.WithMsg("Missing token")
|
||||
}
|
||||
return ctx.Next()
|
||||
}
|
||||
|
||||
claims, err := m.jwt.Parse(authHeader)
|
||||
if err != nil {
|
||||
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)
|
||||
|
||||
Reference in New Issue
Block a user