feat: 完善后端脚手架基础能力
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var revokedTokens sync.Map
|
||||
|
||||
func RevokeToken(ctx context.Context, tokenID string, ttl time.Duration) error {
|
||||
if tokenID == "" || ttl <= 0 {
|
||||
return nil
|
||||
}
|
||||
if redisClient != nil {
|
||||
return redisClient.client.Set(ctx, "jwt:revoked:"+tokenID, "1", ttl).Err()
|
||||
}
|
||||
revokedTokens.Store(tokenID, time.Now().Add(ttl))
|
||||
return nil
|
||||
}
|
||||
|
||||
func IsTokenRevoked(ctx context.Context, tokenID string) (bool, error) {
|
||||
if tokenID == "" {
|
||||
return false, fmt.Errorf("token 缺少 jti")
|
||||
}
|
||||
if redisClient != nil {
|
||||
count, err := redisClient.client.Exists(ctx, "jwt:revoked:"+tokenID).Result()
|
||||
return count > 0, err
|
||||
}
|
||||
value, ok := revokedTokens.Load(tokenID)
|
||||
if !ok {
|
||||
return false, nil
|
||||
}
|
||||
expiresAt := value.(time.Time)
|
||||
if time.Now().After(expiresAt) {
|
||||
revokedTokens.Delete(tokenID)
|
||||
return false, nil
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
Reference in New Issue
Block a user