Files
dns-autoresolver/internal/auth/session_test.go
T

56 lines
1.5 KiB
Go

package auth
import (
"context"
"testing"
"time"
"github.com/google/uuid"
)
type memStore struct {
byHash map[string]uuid.UUID
exp map[string]time.Time
}
func newMem() *memStore { return &memStore{byHash: map[string]uuid.UUID{}, exp: map[string]time.Time{}} }
func (m *memStore) CreateSession(_ context.Context, uid uuid.UUID, h string, e time.Time) error {
m.byHash[h] = uid
m.exp[h] = e
return nil
}
func (m *memStore) GetSessionUser(_ context.Context, h string) (uuid.UUID, error) {
uid, ok := m.byHash[h]
if !ok || time.Now().After(m.exp[h]) {
return uuid.Nil, ErrNoSession
}
return uid, nil
}
func (m *memStore) DeleteSession(_ context.Context, h string) error { delete(m.byHash, h); return nil }
func TestSessionCreateValidateDestroy(t *testing.T) {
s := NewSessions(newMem(), time.Hour)
uid := uuid.New()
token, exp, err := s.Create(context.Background(), uid)
if err != nil || token == "" || exp.Before(time.Now()) {
t.Fatalf("create: %v %q", err, token)
}
got, err := s.Validate(context.Background(), token)
if err != nil || got != uid {
t.Fatalf("validate: %v %v", got, err)
}
if err := s.Destroy(context.Background(), token); err != nil {
t.Fatal(err)
}
if _, err := s.Validate(context.Background(), token); err == nil {
t.Fatal("destroyed session must not validate")
}
}
func TestValidateUnknownToken(t *testing.T) {
s := NewSessions(newMem(), time.Hour)
if _, err := s.Validate(context.Background(), "nope"); err == nil {
t.Fatal("unknown token must error")
}
}