feat: add super admin auth
This commit is contained in:
@@ -3,10 +3,12 @@ package middlewares
|
||||
import (
|
||||
"quyun/v2/app/errorx"
|
||||
"quyun/v2/app/services"
|
||||
"quyun/v2/pkg/consts"
|
||||
"quyun/v2/providers/jwt"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"go.ipao.vip/gen/types"
|
||||
)
|
||||
|
||||
// Middlewares provides reusable Fiber middlewares shared across modules.
|
||||
@@ -53,3 +55,36 @@ func (m *Middlewares) Auth(ctx fiber.Ctx) error {
|
||||
|
||||
return ctx.Next()
|
||||
}
|
||||
|
||||
func (m *Middlewares) SuperAuth(ctx fiber.Ctx) error {
|
||||
authHeader := ctx.Get("Authorization")
|
||||
if authHeader == "" {
|
||||
return errorx.ErrUnauthorized.WithMsg("Missing token")
|
||||
}
|
||||
|
||||
claims, err := m.jwt.Parse(authHeader)
|
||||
if err != nil {
|
||||
return errorx.ErrUnauthorized.WithCause(err).WithMsg("Invalid token")
|
||||
}
|
||||
|
||||
user, err := services.User.GetModelByID(ctx, claims.UserID)
|
||||
if err != nil {
|
||||
return errorx.ErrUnauthorized.WithCause(err).WithMsg("UserNotFound")
|
||||
}
|
||||
|
||||
if !hasRole(user.Roles, consts.RoleSuperAdmin) {
|
||||
return errorx.ErrForbidden.WithMsg("无权限访问")
|
||||
}
|
||||
|
||||
ctx.Locals("__ctx_user", user)
|
||||
return ctx.Next()
|
||||
}
|
||||
|
||||
func hasRole(roles types.Array[consts.Role], role consts.Role) bool {
|
||||
for _, r := range roles {
|
||||
if r == role {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user