85 lines
2.1 KiB
Go
85 lines
2.1 KiB
Go
package session
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
var (
|
|
ErrSessionNotFound = errors.New("session_not_found")
|
|
ErrRedisDown = errors.New("redis_unavailable")
|
|
)
|
|
|
|
// RedisStore реализует handler.SessionStore (Get/Set/Delete).
|
|
// Криптография токенов живёт в пакете auth — здесь только хранение.
|
|
type RedisStore struct {
|
|
client *redis.Client
|
|
}
|
|
|
|
func NewRedisStore(redisURL string, ttl time.Duration) (*RedisStore, error) {
|
|
opts, err := redis.ParseURL(redisURL)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("parse redis url: %w", err)
|
|
}
|
|
|
|
opts.DialTimeout = 3 * time.Second
|
|
opts.ReadTimeout = 3 * time.Second
|
|
opts.WriteTimeout = 3 * time.Second
|
|
opts.PoolSize = 20
|
|
opts.MinIdleConns = 5
|
|
|
|
client := redis.NewClient(opts)
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
|
|
if err := client.Ping(ctx).Err(); err != nil {
|
|
return nil, fmt.Errorf("redis ping: %w", err)
|
|
}
|
|
|
|
return &RedisStore{client: client}, nil
|
|
}
|
|
|
|
func (s *RedisStore) Close() error {
|
|
return s.client.Close()
|
|
}
|
|
|
|
func (s *RedisStore) Set(ctx context.Context, userID, tokenHash string, ttl time.Duration) error {
|
|
key := fmt.Sprintf("session:%s", tokenHash)
|
|
if err := s.client.Set(ctx, key, userID, ttl).Err(); err != nil {
|
|
return fmt.Errorf("%w: %v", ErrRedisDown, err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *RedisStore) Get(ctx context.Context, tokenHash string) (string, error) {
|
|
if tokenHash == "" {
|
|
return "", ErrSessionNotFound
|
|
}
|
|
key := fmt.Sprintf("session:%s", tokenHash)
|
|
userID, err := s.client.Get(ctx, key).Result()
|
|
if err != nil {
|
|
if errors.Is(err, redis.Nil) {
|
|
return "", ErrSessionNotFound
|
|
}
|
|
return "", fmt.Errorf("%w: %v", ErrRedisDown, err)
|
|
}
|
|
return userID, nil
|
|
}
|
|
|
|
func (s *RedisStore) Delete(ctx context.Context, tokenHash string) error {
|
|
key := fmt.Sprintf("session:%s", tokenHash)
|
|
if err := s.client.Del(ctx, key).Err(); err != nil {
|
|
return fmt.Errorf("%w: %v", ErrRedisDown, err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *RedisStore) IsAvailable(ctx context.Context) bool {
|
|
return s.client.Ping(ctx).Err() == nil
|
|
}
|