Files
mtusi2026lab4/internal/httpapi/sessionstore_test.go
T
2026-10-28 14:12:41 +03:00

74 lines
1.2 KiB
Go

package httpapi
import (
"context"
"sync"
"time"
"mtusi2026/internal/sessionstore"
)
type memorySession struct {
userID string
expiresAt time.Time
}
type memorySessionStore struct {
mu sync.Mutex
sessions map[string]memorySession
}
func newMemorySessionStore() *memorySessionStore {
return &memorySessionStore{
sessions: make(map[string]memorySession),
}
}
func (s *memorySessionStore) Create(
_ context.Context,
token string,
userID string,
ttl time.Duration,
) (time.Time, error) {
s.mu.Lock()
defer s.mu.Unlock()
expiresAt := time.Now().UTC().Add(ttl)
s.sessions[token] = memorySession{
userID: userID,
expiresAt: expiresAt,
}
return expiresAt, nil
}
func (s *memorySessionStore) GetUserID(
_ context.Context,
token string,
) (string, error) {
s.mu.Lock()
defer s.mu.Unlock()
session, ok := s.sessions[token]
if !ok || !time.Now().UTC().Before(session.expiresAt) {
delete(s.sessions, token)
return "", sessionstore.ErrNotFound
}
return session.userID, nil
}
func (s *memorySessionStore) Delete(
_ context.Context,
token string,
) (bool, error) {
s.mu.Lock()
defer s.mu.Unlock()
if _, ok := s.sessions[token]; !ok {
return false, nil
}
delete(s.sessions, token)
return true, nil
}