fix: enforce required auth middleware
This commit is contained in:
@@ -7,6 +7,6 @@ func (r *Routes) Path() string {
|
|||||||
func (r *Routes) Middlewares() []any {
|
func (r *Routes) Middlewares() []any {
|
||||||
return []any{
|
return []any{
|
||||||
r.middlewares.TenantResolver,
|
r.middlewares.TenantResolver,
|
||||||
r.middlewares.Auth,
|
r.middlewares.AuthRequired,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,13 +31,24 @@ func (f *Middlewares) Prepare() error {
|
|||||||
return nil
|
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) {
|
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")
|
authHeader := ctx.Get("Authorization")
|
||||||
if authHeader == "" {
|
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)
|
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")
|
return errorx.ErrUnauthorized.WithCause(err).WithMsg("Invalid token")
|
||||||
}
|
}
|
||||||
|
|
||||||
// get user model
|
// 获取用户信息,确保 token 与账号状态一致。
|
||||||
user, err := services.User.GetModelByID(ctx, claims.UserID)
|
user, err := services.User.GetModelByID(ctx, claims.UserID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errorx.ErrUnauthorized.WithCause(err).WithMsg("UserNotFound")
|
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
|
// Set Context
|
||||||
ctx.Locals(consts.CtxKeyUser, user)
|
ctx.Locals(consts.CtxKeyUser, user)
|
||||||
|
|||||||
Reference in New Issue
Block a user