2024-10-29 23:08:11 +00:00
|
|
|
package storage
|
|
|
|
|
|
|
|
import (
|
|
|
|
"math/rand/v2"
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
func NewRamStore() Store {
|
|
|
|
store := &ram{
|
|
|
|
passwords: make(map[string]entry),
|
|
|
|
lock: sync.Mutex{},
|
2024-10-29 23:21:25 +00:00
|
|
|
close: make(chan bool),
|
2024-10-29 23:08:11 +00:00
|
|
|
}
|
|
|
|
|
2024-10-29 23:21:25 +00:00
|
|
|
go store.clearExpired()
|
2024-10-29 23:08:11 +00:00
|
|
|
return store
|
|
|
|
}
|
|
|
|
|
|
|
|
type ram struct {
|
|
|
|
passwords map[string]entry
|
|
|
|
lock sync.Mutex
|
2024-10-29 23:21:25 +00:00
|
|
|
close chan bool
|
2024-10-29 23:08:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (store *ram) CreatePassword(password []byte, expiresAt time.Time) (string, error) {
|
|
|
|
store.lock.Lock()
|
|
|
|
defer store.lock.Unlock()
|
|
|
|
|
|
|
|
for range 1000 {
|
|
|
|
id := store.generateId(24)
|
|
|
|
_, found := store.passwords[id]
|
|
|
|
if found {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
store.passwords[id] = entry{
|
|
|
|
password: password,
|
|
|
|
expiresAt: expiresAt,
|
|
|
|
}
|
|
|
|
|
|
|
|
return id, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return "", ErrFull
|
|
|
|
}
|
|
|
|
|
|
|
|
func (store *ram) GetPassword(id string) ([]byte, error) {
|
|
|
|
store.lock.Lock()
|
|
|
|
defer store.lock.Unlock()
|
|
|
|
|
|
|
|
password, found := store.passwords[id]
|
|
|
|
if !found {
|
|
|
|
return nil, ErrNotFound
|
|
|
|
}
|
|
|
|
|
|
|
|
delete(store.passwords, id)
|
|
|
|
return password.password, nil
|
|
|
|
}
|
|
|
|
|
2024-10-29 23:21:25 +00:00
|
|
|
func (store *ram) Close() error {
|
|
|
|
store.close <- true
|
|
|
|
return nil
|
|
|
|
}
|
2024-10-29 23:08:11 +00:00
|
|
|
|
2024-10-29 23:21:25 +00:00
|
|
|
func (store *ram) clearExpired() error {
|
|
|
|
ticker := time.NewTicker(20 * time.Second)
|
|
|
|
defer ticker.Stop()
|
|
|
|
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-store.close:
|
|
|
|
return nil
|
|
|
|
case <-ticker.C:
|
|
|
|
store.lock.Lock()
|
|
|
|
defer store.lock.Unlock()
|
|
|
|
time := time.Now()
|
|
|
|
|
|
|
|
for id, password := range store.passwords {
|
|
|
|
if time.After(password.expiresAt) {
|
|
|
|
delete(store.passwords, id)
|
|
|
|
}
|
|
|
|
}
|
2024-10-29 23:08:11 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (store *ram) generateId(length int) string {
|
|
|
|
runes := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
|
|
|
|
|
|
|
|
str := make([]rune, length)
|
|
|
|
for i := range str {
|
|
|
|
str[i] = runes[rand.IntN(len(runes))]
|
|
|
|
}
|
|
|
|
|
|
|
|
return string(str)
|
|
|
|
}
|