Files
mtusi2026lab2/internal/storage/session_cache.go
T

94 lines
1.6 KiB
Go

package storage
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
)
type SessionCache struct {
client *redis.Client
}
func NewSessionCache(redisURL string) (*SessionCache, error) {
options, err := redis.ParseURL(redisURL)
if err != nil {
return nil, fmt.Errorf("invalid redis URL: %w", err)
}
options.DialTimeout = 2 * time.Second
options.ReadTimeout = 2 * time.Second
options.WriteTimeout = 2 * time.Second
options.MaxRetries = 0
return &SessionCache{
client: redis.NewClient(options),
}, nil
}
func (c *SessionCache) Close() error {
return c.client.Close()
}
func (c *SessionCache) Ping(ctx context.Context) error {
return c.client.Ping(ctx).Err()
}
func cacheKey(token string) string {
sum := sha256.Sum256([]byte(token))
return "session:" + hex.EncodeToString(sum[:])
}
func (c *SessionCache) Set(
ctx context.Context,
token string,
userID uuid.UUID,
expiresAt time.Time,
) error {
ttl := time.Until(expiresAt)
if ttl <= 0 {
return nil
}
return c.client.Set(
ctx,
cacheKey(token),
userID.String(),
ttl,
).Err()
}
func (c *SessionCache) Get(
ctx context.Context,
token string,
) (uuid.UUID, bool, error) {
value, err := c.client.Get(ctx, cacheKey(token)).Result()
if errors.Is(err, redis.Nil) {
return uuid.Nil, false, nil
}
if err != nil {
return uuid.Nil, false, err
}
userID, err := uuid.Parse(value)
if err != nil {
return uuid.Nil, false, err
}
return userID, true, nil
}
func (c *SessionCache) Delete(
ctx context.Context,
token string,
) error {
return c.client.Del(ctx, cacheKey(token)).Err()
}