2017-08-03 12:13:53 +00:00
|
|
|
package main
|
|
|
|
|
2020-01-24 15:33:14 +00:00
|
|
|
import (
|
|
|
|
"os"
|
|
|
|
"strconv"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/gofrs/uuid/v3"
|
|
|
|
)
|
|
|
|
|
|
|
|
type memStorageSecret struct {
|
|
|
|
Expiry time.Time
|
|
|
|
Secret string
|
|
|
|
}
|
2017-08-03 12:13:53 +00:00
|
|
|
|
|
|
|
type storageMem struct {
|
2020-01-24 15:33:14 +00:00
|
|
|
store map[string]memStorageSecret
|
2017-08-03 12:13:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func newStorageMem() storage {
|
|
|
|
return &storageMem{
|
2020-01-24 15:33:14 +00:00
|
|
|
store: make(map[string]memStorageSecret),
|
2017-08-03 12:13:53 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s storageMem) Create(secret string) (string, error) {
|
2018-10-06 18:08:21 +00:00
|
|
|
id := uuid.Must(uuid.NewV4()).String()
|
2020-01-24 15:33:14 +00:00
|
|
|
s.store[id] = memStorageSecret{
|
|
|
|
Expiry: s.expiry(),
|
|
|
|
Secret: secret,
|
|
|
|
}
|
2017-08-03 12:13:53 +00:00
|
|
|
|
|
|
|
return id, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s storageMem) ReadAndDestroy(id string) (string, error) {
|
|
|
|
secret, ok := s.store[id]
|
|
|
|
if !ok {
|
|
|
|
return "", errSecretNotFound
|
|
|
|
}
|
|
|
|
|
2020-01-24 15:33:14 +00:00
|
|
|
defer delete(s.store, id)
|
|
|
|
|
2020-01-26 15:53:34 +00:00
|
|
|
if !secret.Expiry.IsZero() && secret.Expiry.Before(time.Now()) {
|
2020-01-24 15:33:14 +00:00
|
|
|
return "", errSecretNotFound
|
|
|
|
}
|
|
|
|
|
|
|
|
return secret.Secret, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s storageMem) expiry() time.Time {
|
|
|
|
exp := os.Getenv("SECRET_EXPIRY")
|
|
|
|
if exp == "" {
|
|
|
|
return time.Time{}
|
|
|
|
}
|
|
|
|
|
|
|
|
e, err := strconv.ParseInt(exp, 10, 64)
|
|
|
|
if err != nil {
|
|
|
|
return time.Time{}
|
|
|
|
}
|
|
|
|
|
|
|
|
return time.Now().Add(time.Duration(e) * time.Second)
|
2017-08-03 12:13:53 +00:00
|
|
|
}
|