57 lines
1.3 KiB
Go
57 lines
1.3 KiB
Go
package service
|
|
|
|
import (
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/golang-jwt/jwt/v5"
|
|
"github.com/rs/zerolog/log"
|
|
)
|
|
|
|
// TokenBlacklist 用于存储已失效的 token
|
|
type TokenBlacklist struct {
|
|
tokens sync.Map
|
|
}
|
|
|
|
// NewTokenBlacklist 创建一个新的 token 黑名单
|
|
func NewTokenBlacklist() *TokenBlacklist {
|
|
bl := &TokenBlacklist{}
|
|
// 启动定期清理过期 token 的 goroutine
|
|
go bl.cleanupExpiredTokens()
|
|
return bl
|
|
}
|
|
|
|
// AddToBlacklist 将 token 添加到黑名单
|
|
func (bl *TokenBlacklist) AddToBlacklist(tokenStr string, claims jwt.MapClaims) {
|
|
// 获取 token 的过期时间
|
|
exp, ok := claims["exp"].(float64)
|
|
if !ok {
|
|
log.Error().Msg("Failed to get token expiration time")
|
|
return
|
|
}
|
|
|
|
// 存储 token 和其过期时间
|
|
bl.tokens.Store(tokenStr, time.Unix(int64(exp), 0))
|
|
}
|
|
|
|
// IsBlacklisted 检查 token 是否在黑名单中
|
|
func (bl *TokenBlacklist) IsBlacklisted(tokenStr string) bool {
|
|
_, exists := bl.tokens.Load(tokenStr)
|
|
return exists
|
|
}
|
|
|
|
// cleanupExpiredTokens 定期清理过期的 token
|
|
func (bl *TokenBlacklist) cleanupExpiredTokens() {
|
|
ticker := time.NewTicker(1 * time.Hour)
|
|
for range ticker.C {
|
|
now := time.Now()
|
|
bl.tokens.Range(func(key, value interface{}) bool {
|
|
if expTime, ok := value.(time.Time); ok {
|
|
if now.After(expTime) {
|
|
bl.tokens.Delete(key)
|
|
}
|
|
}
|
|
return true
|
|
})
|
|
}
|
|
}
|