80 lines
2.1 KiB
Go
80 lines
2.1 KiB
Go
package redis
|
|
|
|
import (
|
|
"github.com/redis/go-redis/extra/redisotel/v9"
|
|
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/redis/go-redis/v9"
|
|
|
|
"github.com/charawein/mtusi2026lab6/internal/domain"
|
|
"github.com/charawein/mtusi2026lab6/internal/repository"
|
|
)
|
|
|
|
type SessionRepository struct {
|
|
client *redis.Client
|
|
}
|
|
|
|
func NewSessionRepository(client *redis.Client) *SessionRepository {
|
|
return &SessionRepository{client: client}
|
|
}
|
|
|
|
func (r *SessionRepository) Create(ctx context.Context, s *domain.Session) error {
|
|
key := "session:" + s.Token
|
|
ttl := time.Until(s.ExpiresAt)
|
|
if ttl <= 0 {
|
|
return fmt.Errorf("session already expired")
|
|
}
|
|
if err := r.client.Set(ctx, key, s.UserID, ttl).Err(); err != nil {
|
|
return fmt.Errorf("set session: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (r *SessionRepository) GetByToken(ctx context.Context, token string) (*domain.Session, error) {
|
|
key := "session:" + token
|
|
userID, err := r.client.Get(ctx, key).Result()
|
|
if err != nil {
|
|
if errors.Is(err, redis.Nil) {
|
|
return nil, repository.ErrNotFound
|
|
}
|
|
return nil, fmt.Errorf("get session: %w", err)
|
|
}
|
|
ttl, err := r.client.TTL(ctx, key).Result()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("ttl: %w", err)
|
|
}
|
|
return &domain.Session{
|
|
Token: token,
|
|
UserID: userID,
|
|
ExpiresAt: time.Now().UTC().Add(ttl),
|
|
}, nil
|
|
}
|
|
|
|
func (r *SessionRepository) Delete(ctx context.Context, token string) error {
|
|
return r.client.Del(ctx, "session:"+token).Err()
|
|
}
|
|
|
|
func (r *SessionRepository) DeleteExpired(ctx context.Context) error {
|
|
return nil
|
|
}
|
|
|
|
func NewClient(ctx context.Context, url string) (*redis.Client, error) {
|
|
opts, err := redis.ParseURL(url)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("parse redis url: %w", err)
|
|
}
|
|
client := redis.NewClient(opts)
|
|
// Spans команд Redis (имя команды; аргументы — ключи сессий — не пишутся).
|
|
if err := redisotel.InstrumentTracing(client, redisotel.WithDBStatement(false)); err != nil {
|
|
return nil, fmt.Errorf("redis tracing: %w", err)
|
|
}
|
|
if err := client.Ping(ctx).Err(); err != nil {
|
|
return nil, fmt.Errorf("ping redis: %w", err)
|
|
}
|
|
return client, nil
|
|
}
|