32 lines
528 B
Go
32 lines
528 B
Go
package security
|
|
|
|
import (
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
type NonceStore struct {
|
|
mu sync.Mutex
|
|
m map[string]int64
|
|
ttl time.Duration
|
|
}
|
|
|
|
func NewNonceStore(ttl time.Duration) *NonceStore {
|
|
return &NonceStore{m: map[string]int64{}, ttl: ttl}
|
|
}
|
|
|
|
func (s *NonceStore) Use(nonce string, now time.Time) bool {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if exp, ok := s.m[nonce]; ok && exp >= now.Unix() {
|
|
return false
|
|
}
|
|
s.m[nonce] = now.Add(s.ttl).Unix()
|
|
for k, v := range s.m {
|
|
if v < now.Unix() {
|
|
delete(s.m, k)
|
|
}
|
|
}
|
|
return true
|
|
}
|