做完了一部分,备份一下,防止以外删除
This commit is contained in:
65
pkg/validator/token.go
Normal file
65
pkg/validator/token.go
Normal file
@@ -0,0 +1,65 @@
|
||||
package validator
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
"go.uber.org/zap"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
)
|
||||
|
||||
// TokenValidator 令牌验证器
|
||||
type TokenValidator struct {
|
||||
redis *redis.Client
|
||||
logger *zap.Logger
|
||||
}
|
||||
|
||||
// NewTokenValidator 创建新的令牌验证器
|
||||
func NewTokenValidator(rdb *redis.Client, logger *zap.Logger) *TokenValidator {
|
||||
return &TokenValidator{
|
||||
redis: rdb,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// Validate 验证令牌并返回用户 ID
|
||||
func (v *TokenValidator) Validate(token string) (string, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
|
||||
defer cancel()
|
||||
|
||||
// 检查 Redis 可用性(失败关闭策略)
|
||||
if err := v.redis.Ping(ctx).Err(); err != nil {
|
||||
v.logger.Error("Redis 不可用",
|
||||
zap.Error(err),
|
||||
)
|
||||
return "", errors.ErrRedisUnavailable
|
||||
}
|
||||
|
||||
// 从 Redis 获取用户 ID
|
||||
userID, err := v.redis.Get(ctx, constants.RedisAuthTokenKey(token)).Result()
|
||||
if err == redis.Nil {
|
||||
// 令牌不存在或已过期
|
||||
return "", errors.ErrInvalidToken
|
||||
}
|
||||
if err != nil {
|
||||
v.logger.Error("Redis 获取失败",
|
||||
zap.Error(err),
|
||||
zap.String("token_key", constants.RedisAuthTokenKey(token)),
|
||||
)
|
||||
return "", err
|
||||
}
|
||||
|
||||
return userID, nil
|
||||
}
|
||||
|
||||
// IsAvailable 检查 Redis 是否可用
|
||||
func (v *TokenValidator) IsAvailable() bool {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
|
||||
defer cancel()
|
||||
|
||||
err := v.redis.Ping(ctx).Err()
|
||||
return err == nil
|
||||
}
|
||||
Reference in New Issue
Block a user