85 lines
2.1 KiB
Go
85 lines
2.1 KiB
Go
// store_memory.go 内存 TokenStore 实现(单测 / Redis 降级;非线程安全的清理采用惰性淘汰)。
|
|
package auth
|
|
|
|
import (
|
|
"context"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
// MemoryTokenStore 内存实现:黑名单 + 失败计数均带过期时间。
|
|
type MemoryTokenStore struct {
|
|
mu sync.Mutex
|
|
blk map[string]time.Time // tokenHash → 过期时刻
|
|
failures map[string]*failEntry
|
|
}
|
|
|
|
type failEntry struct {
|
|
count int64
|
|
deadline time.Time
|
|
}
|
|
|
|
// NewMemoryTokenStore 构造空存储。
|
|
func NewMemoryTokenStore() *MemoryTokenStore {
|
|
return &MemoryTokenStore{blk: map[string]time.Time{}, failures: map[string]*failEntry{}}
|
|
}
|
|
|
|
// Revoke 写入黑名单(ttl<=0 忽略:令牌已自然过期)。
|
|
func (m *MemoryTokenStore) Revoke(_ context.Context, tokenHash string, ttl time.Duration) error {
|
|
if ttl <= 0 {
|
|
return nil
|
|
}
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
// 惰性清理已过期黑名单,防长跑内存增长
|
|
now := time.Now()
|
|
for k, exp := range m.blk {
|
|
if now.After(exp) {
|
|
delete(m.blk, k)
|
|
}
|
|
}
|
|
m.blk[tokenHash] = now.Add(ttl)
|
|
return nil
|
|
}
|
|
|
|
// IsRevoked 是否仍在黑名单(过期视为未注销)。
|
|
func (m *MemoryTokenStore) IsRevoked(_ context.Context, tokenHash string) (bool, error) {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
exp, ok := m.blk[tokenHash]
|
|
return ok && time.Now().Before(exp), nil
|
|
}
|
|
|
|
// IncrFail 失败计数 +1;窗口过期则进入新窗口从 1 起算。
|
|
func (m *MemoryTokenStore) IncrFail(_ context.Context, key string, window time.Duration) (int64, error) {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
now := time.Now()
|
|
e, ok := m.failures[key]
|
|
if !ok || now.After(e.deadline) {
|
|
e = &failEntry{deadline: now.Add(window)}
|
|
m.failures[key] = e
|
|
}
|
|
e.count++
|
|
return e.count, nil
|
|
}
|
|
|
|
// GetFail 当前计数(窗口过期返回 0)。
|
|
func (m *MemoryTokenStore) GetFail(_ context.Context, key string) (int64, error) {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
e, ok := m.failures[key]
|
|
if !ok || time.Now().After(e.deadline) {
|
|
return 0, nil
|
|
}
|
|
return e.count, nil
|
|
}
|
|
|
|
// ResetFail 清零计数。
|
|
func (m *MemoryTokenStore) ResetFail(_ context.Context, key string) error {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
delete(m.failures, key)
|
|
return nil
|
|
}
|