From 7536e5d9af70d683df35caf5e90caf83952e6820 Mon Sep 17 00:00:00 2001 From: 1e99 <1e99@1e99.eu> Date: Wed, 30 Oct 2024 11:51:20 +0100 Subject: [PATCH] store passwords on disk using JSON instead of gob --- storage/dir.go | 19 ++++++++++++------- storage/ram.go | 11 ++++++++--- storage/storage.go | 5 ----- 3 files changed, 20 insertions(+), 15 deletions(-) diff --git a/storage/dir.go b/storage/dir.go index 4c4fd39..0f0e6b9 100644 --- a/storage/dir.go +++ b/storage/dir.go @@ -1,7 +1,7 @@ package storage import ( - "encoding/gob" + "encoding/json" "log" "os" "path" @@ -20,6 +20,11 @@ type dir struct { path string } +type dirEntry struct { + Password []byte `json:"password"` + ExpiresAt time.Time `json:"expires-at"` +} + func (store *dir) Create(password []byte, expiresAt time.Time) (string, error) { for range 1000 { id := generateId(24) @@ -39,12 +44,12 @@ func (store *dir) Create(password []byte, expiresAt time.Time) (string, error) { defer file.Close() - entry := entry{ + entry := dirEntry{ Password: password, ExpiresAt: expiresAt, } - err = gob.NewEncoder(file).Encode(&entry) + err = json.NewEncoder(file).Encode(&entry) if err != nil { log.Printf("%s", err) return "", err @@ -72,8 +77,8 @@ func (store *dir) Get(id string) ([]byte, error) { defer file.Close() - var entry entry - err = gob.NewDecoder(file).Decode(&entry) + var entry dirEntry + err = json.NewDecoder(file).Decode(&entry) if err != nil { return nil, err } @@ -113,8 +118,8 @@ func (store *dir) ClearExpired() error { defer file.Close() - var entry entry - err = gob.NewDecoder(file).Decode(&entry) + var entry dirEntry + err = json.NewDecoder(file).Decode(&entry) if err != nil { return err } diff --git a/storage/ram.go b/storage/ram.go index 597361d..b9f3c9a 100644 --- a/storage/ram.go +++ b/storage/ram.go @@ -7,7 +7,7 @@ import ( func NewRamStore() Store { store := &ram{ - passwords: make(map[string]entry), + passwords: make(map[string]ramEntry), lock: sync.Mutex{}, } @@ -15,10 +15,15 @@ func NewRamStore() Store { } type ram struct { - passwords map[string]entry + passwords map[string]ramEntry lock sync.Mutex } +type ramEntry struct { + Password []byte + ExpiresAt time.Time +} + func (store *ram) Create(password []byte, expiresAt time.Time) (string, error) { store.lock.Lock() defer store.lock.Unlock() @@ -30,7 +35,7 @@ func (store *ram) Create(password []byte, expiresAt time.Time) (string, error) { continue } - store.passwords[id] = entry{ + store.passwords[id] = ramEntry{ Password: password, ExpiresAt: expiresAt, } diff --git a/storage/storage.go b/storage/storage.go index d3e1d8f..efdf67e 100644 --- a/storage/storage.go +++ b/storage/storage.go @@ -14,11 +14,6 @@ var ( ErrFull = errors.New("storage is filled") ) -type entry struct { - Password []byte - ExpiresAt time.Time -} - type Store interface { Create(password []byte, expiresAt time.Time) (string, error) Get(id string) ([]byte, error)