81 lines
1.2 KiB
Go
81 lines
1.2 KiB
Go
package password
|
|
|
|
import (
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
func NewRamStorage() Storage {
|
|
storage := &ram{
|
|
passwords: make(map[string]ramEntry),
|
|
lock: sync.Mutex{},
|
|
}
|
|
|
|
return storage
|
|
}
|
|
|
|
type ram struct {
|
|
passwords map[string]ramEntry
|
|
lock sync.Mutex
|
|
}
|
|
|
|
type ramEntry struct {
|
|
Password []byte
|
|
ExpiresAt time.Time
|
|
}
|
|
|
|
func (s *ram) Create(password []byte, expiresAt time.Time) (string, error) {
|
|
s.lock.Lock()
|
|
defer s.lock.Unlock()
|
|
|
|
for range 1000 {
|
|
id := generateId(24)
|
|
_, found := s.passwords[id]
|
|
if found {
|
|
continue
|
|
}
|
|
|
|
s.passwords[id] = ramEntry{
|
|
Password: password,
|
|
ExpiresAt: expiresAt,
|
|
}
|
|
|
|
return id, nil
|
|
}
|
|
|
|
return "", ErrFull
|
|
}
|
|
|
|
func (s *ram) Get(id string) ([]byte, error) {
|
|
s.lock.Lock()
|
|
defer s.lock.Unlock()
|
|
|
|
password, found := s.passwords[id]
|
|
if !found {
|
|
return nil, ErrNotFound
|
|
}
|
|
|
|
return password.Password, nil
|
|
}
|
|
|
|
func (s *ram) Delete(id string) error {
|
|
delete(s.passwords, id)
|
|
return nil
|
|
}
|
|
|
|
func (s *ram) ClearExpired() error {
|
|
s.lock.Lock()
|
|
defer s.lock.Unlock()
|
|
time := time.Now()
|
|
|
|
for id, password := range s.passwords {
|
|
if time.After(password.ExpiresAt) {
|
|
err := s.Delete(id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|