81 lines
1.8 KiB
Go
81 lines
1.8 KiB
Go
package redis
|
|
|
|
import (
|
|
"context"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/redis/go-redis/v9"
|
|
|
|
"high-loud-apps-labs/internal/domain"
|
|
)
|
|
|
|
const sessionKeyPrefix = "session:"
|
|
|
|
type SessionRepo struct {
|
|
client *redis.Client
|
|
}
|
|
|
|
func NewSessionRepo(client *redis.Client) *SessionRepo {
|
|
return &SessionRepo{client: client}
|
|
}
|
|
|
|
type sessionValue struct {
|
|
UserID string `json:"user_id"`
|
|
ExpiresAt time.Time `json:"expires_at"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
}
|
|
|
|
func (r *SessionRepo) key(tokenHash []byte) string {
|
|
return sessionKeyPrefix + hex.EncodeToString(tokenHash)
|
|
}
|
|
|
|
func (r *SessionRepo) Create(ctx context.Context, s *domain.Session) error {
|
|
ttl := time.Until(s.ExpiresAt)
|
|
if ttl <= 0 {
|
|
return nil
|
|
}
|
|
|
|
data, err := json.Marshal(sessionValue{
|
|
UserID: s.UserID,
|
|
ExpiresAt: s.ExpiresAt.UTC(),
|
|
CreatedAt: s.CreatedAt.UTC(),
|
|
})
|
|
if err != nil {
|
|
return fmt.Errorf("сериализация сессии: %w", err)
|
|
}
|
|
|
|
return mapError(r.client.Set(ctx, r.key(s.TokenHash), data, ttl).Err())
|
|
}
|
|
|
|
func (r *SessionRepo) GetByTokenHash(ctx context.Context, tokenHash []byte) (*domain.Session, error) {
|
|
data, err := r.client.Get(ctx, r.key(tokenHash)).Bytes()
|
|
if err != nil {
|
|
if errors.Is(err, redis.Nil) {
|
|
return nil, &domain.NotFoundError{Entity: "session"}
|
|
}
|
|
return nil, mapError(err)
|
|
}
|
|
|
|
var sv sessionValue
|
|
if err := json.Unmarshal(data, &sv); err != nil {
|
|
return nil, fmt.Errorf("разбор сессии: %w", err)
|
|
}
|
|
|
|
return &domain.Session{
|
|
TokenHash: tokenHash,
|
|
UserID: sv.UserID,
|
|
ExpiresAt: sv.ExpiresAt,
|
|
CreatedAt: sv.CreatedAt,
|
|
}, nil
|
|
}
|
|
|
|
func (r *SessionRepo) DeleteByTokenHash(ctx context.Context, tokenHash []byte) error {
|
|
return mapError(r.client.Del(ctx, r.key(tokenHash)).Err())
|
|
}
|
|
|
|
var _ domain.SessionRepository = (*SessionRepo)(nil)
|