Files
2026-10-31 20:10:31 +03:00

104 lines
2.4 KiB
Go

// Package session stores bearer sessions in Redis. Tokens are hashed before
// they become keys, and the configured TTL is absolute.
package session
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"strings"
"time"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
)
var ErrNotFound = errors.New("session not found")
const keyPrefix = "messenger:session:"
type Store struct {
client *redis.Client
ttl time.Duration
timeout time.Duration
}
func New(rawURL string, ttl, timeout time.Duration) (*Store, error) {
options, err := redis.ParseURL(rawURL)
if err != nil {
return nil, fmt.Errorf("parse CACHE_URL: %w", err)
}
options.PoolSize = 10
options.DialTimeout = timeout
options.ReadTimeout = timeout
options.WriteTimeout = timeout
options.MaxRetries = 0
return &Store{
client: redis.NewClient(options),
ttl: ttl,
timeout: timeout,
}, nil
}
func (s *Store) Close() error {
return s.client.Close()
}
func (s *Store) Ping(ctx context.Context) error {
pingCtx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
return s.client.Ping(pingCtx).Err()
}
func (s *Store) Create(ctx context.Context, userID uuid.UUID) (string, time.Time, error) {
raw := make([]byte, 32)
if _, err := rand.Read(raw); err != nil {
return "", time.Time{}, fmt.Errorf("generate token: %w", err)
}
token := base64.RawURLEncoding.EncodeToString(raw)
expiresAt := time.Now().UTC().Add(s.ttl)
opCtx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
if err := s.client.Set(opCtx, keyFor(token), userID.String(), s.ttl).Err(); err != nil {
return "", time.Time{}, err
}
return token, expiresAt, nil
}
func (s *Store) Lookup(ctx context.Context, token string) (uuid.UUID, error) {
opCtx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
value, err := s.client.Get(opCtx, keyFor(token)).Result()
if errors.Is(err, redis.Nil) {
return uuid.Nil, ErrNotFound
}
if err != nil {
return uuid.Nil, err
}
userID, err := uuid.Parse(value)
if err != nil {
return uuid.Nil, ErrNotFound
}
return userID, nil
}
func (s *Store) Revoke(ctx context.Context, token string) error {
opCtx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
return s.client.Del(opCtx, keyFor(token)).Err()
}
func keyFor(token string) string {
sum := sha256.Sum256([]byte(strings.TrimSpace(token)))
return keyPrefix + hex.EncodeToString(sum[:])
}