commit
This commit is contained in:
@@ -2,7 +2,9 @@ package utils
|
||||
|
||||
import (
|
||||
"ai_xhs/config"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
@@ -44,3 +46,45 @@ func ParseToken(tokenString string) (*Claims, error) {
|
||||
|
||||
return nil, errors.New("invalid token")
|
||||
}
|
||||
|
||||
// StoreTokenInRedis 将Token存入Redis
|
||||
func StoreTokenInRedis(ctx context.Context, employeeID int, tokenString string) error {
|
||||
// Redis key: token:employee:{employeeID}
|
||||
key := fmt.Sprintf("token:employee:%d", employeeID)
|
||||
|
||||
// 存储token,过期时间与JWT一致
|
||||
expiration := time.Duration(config.AppConfig.JWT.ExpireHours) * time.Hour
|
||||
return SetCache(ctx, key, tokenString, expiration)
|
||||
}
|
||||
|
||||
// ValidateTokenInRedis 验证Token是否在Redis中存在(校验是否被禁用)
|
||||
func ValidateTokenInRedis(ctx context.Context, employeeID int, tokenString string) error {
|
||||
key := fmt.Sprintf("token:employee:%d", employeeID)
|
||||
|
||||
// 从Redis获取存储的token
|
||||
var storedToken string
|
||||
err := GetCache(ctx, key, &storedToken)
|
||||
if err != nil {
|
||||
return errors.New("token已失效或用户已被禁用")
|
||||
}
|
||||
|
||||
// 比对token是否一致
|
||||
if storedToken != tokenString {
|
||||
return errors.New("token不匹配,用户可能已重新登录")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// RevokeToken 撤销Token(禁用用户)
|
||||
func RevokeToken(ctx context.Context, employeeID int) error {
|
||||
key := fmt.Sprintf("token:employee:%d", employeeID)
|
||||
return DelCache(ctx, key)
|
||||
}
|
||||
|
||||
// RevokeAllUserTokens 撤销用户的所有Token(如果有多设备登录)
|
||||
func RevokeAllUserTokens(ctx context.Context, employeeID int) error {
|
||||
// 当前实现:一个用户只保存一个token
|
||||
// 如果需要支持多设备,可以改为 token:employee:{employeeID}:{deviceID}
|
||||
return RevokeToken(ctx, employeeID)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user