refactor: align framework cleanup with new bootstrap flow
Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
This commit is contained in:
@@ -1,53 +0,0 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/fiber/v2/middleware/keyauth"
|
||||
"go.uber.org/zap"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/response"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/validator"
|
||||
)
|
||||
|
||||
// KeyAuth 创建基于 Redis 的令牌认证中间件
|
||||
func KeyAuth(v *validator.TokenValidator, logger *zap.Logger) fiber.Handler {
|
||||
return keyauth.New(keyauth.Config{
|
||||
KeyLookup: "header:token",
|
||||
Validator: func(c *fiber.Ctx, key string) (bool, error) {
|
||||
// 验证令牌
|
||||
userID, err := v.Validate(key)
|
||||
if err != nil {
|
||||
// 获取请求 ID 用于日志
|
||||
requestID := ""
|
||||
if rid := c.Locals(constants.ContextKeyRequestID); rid != nil {
|
||||
requestID = rid.(string)
|
||||
}
|
||||
|
||||
logger.Warn("令牌验证失败",
|
||||
zap.String("request_id", requestID),
|
||||
zap.Error(err),
|
||||
)
|
||||
return false, err
|
||||
}
|
||||
|
||||
// 在上下文中存储用户 ID
|
||||
c.Locals(constants.ContextKeyUserID, userID)
|
||||
return true, nil
|
||||
},
|
||||
ErrorHandler: func(c *fiber.Ctx, err error) error {
|
||||
// 将错误映射到统一响应格式
|
||||
switch err {
|
||||
case keyauth.ErrMissingOrMalformedAPIKey:
|
||||
return response.Error(c, 400, errors.CodeMissingToken, errors.GetMessage(errors.CodeMissingToken, "zh"))
|
||||
case errors.ErrInvalidToken:
|
||||
return response.Error(c, 400, errors.CodeInvalidToken, errors.GetMessage(errors.CodeInvalidToken, "zh"))
|
||||
case errors.ErrRedisUnavailable:
|
||||
return response.Error(c, 503, errors.CodeAuthServiceUnavailable, errors.GetMessage(errors.CodeAuthServiceUnavailable, "zh"))
|
||||
default:
|
||||
return response.Error(c, 500, errors.CodeInternalError, errors.GetMessage(errors.CodeInternalError, "zh"))
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/response"
|
||||
)
|
||||
|
||||
// RateLimiter 创建基于 IP 的限流中间件
|
||||
@@ -23,7 +22,7 @@ func RateLimiter(max int, expiration time.Duration, storage fiber.Storage) fiber
|
||||
return constants.RedisRateLimitKey(c.IP())
|
||||
},
|
||||
LimitReached: func(c *fiber.Ctx) error {
|
||||
return response.Error(c, 429, errors.CodeTooManyRequests, errors.GetMessage(errors.CodeTooManyRequests, "zh"))
|
||||
return errors.New(errors.CodeTooManyRequests, errors.GetMessage(errors.CodeTooManyRequests, "zh"))
|
||||
},
|
||||
Storage: storage, // 支持内存或 Redis 存储
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user