forked from mtusi2026/mtusi2026lab3
74 lines
1.6 KiB
Go
74 lines
1.6 KiB
Go
package sessionstore
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
type RedisStore struct {
|
|
client *redis.Client
|
|
}
|
|
|
|
func NewRedis(client *redis.Client) *RedisStore {
|
|
return &RedisStore{client: client}
|
|
}
|
|
|
|
func NewRedisClient(ctx context.Context, addr string) (*redis.Client, error) {
|
|
client := redis.NewClient(&redis.Options{
|
|
Addr: addr,
|
|
})
|
|
|
|
if err := client.Ping(ctx).Err(); err != nil {
|
|
_ = client.Close()
|
|
return nil, fmt.Errorf("%w: redis ping: %v", ErrUnavailable, err)
|
|
}
|
|
|
|
return client, nil
|
|
}
|
|
|
|
func sessionKey(token string) string {
|
|
return "session:" + token
|
|
}
|
|
|
|
func (s *RedisStore) Create(
|
|
ctx context.Context,
|
|
token string,
|
|
userID string,
|
|
ttl time.Duration,
|
|
) (time.Time, error) {
|
|
if ttl <= 0 {
|
|
return time.Time{}, fmt.Errorf("invalid session ttl: %s", ttl)
|
|
}
|
|
|
|
if err := s.client.Set(ctx, sessionKey(token), userID, ttl).Err(); err != nil {
|
|
return time.Time{}, fmt.Errorf("%w: create session: %v", ErrUnavailable, err)
|
|
}
|
|
|
|
return time.Now().UTC().Add(ttl), nil
|
|
}
|
|
|
|
func (s *RedisStore) GetUserID(ctx context.Context, token string) (string, error) {
|
|
userID, err := s.client.Get(ctx, sessionKey(token)).Result()
|
|
if errors.Is(err, redis.Nil) {
|
|
return "", ErrNotFound
|
|
}
|
|
if err != nil {
|
|
return "", fmt.Errorf("%w: get session: %v", ErrUnavailable, err)
|
|
}
|
|
|
|
return userID, nil
|
|
}
|
|
|
|
func (s *RedisStore) Delete(ctx context.Context, token string) (bool, error) {
|
|
n, err := s.client.Del(ctx, sessionKey(token)).Result()
|
|
if err != nil {
|
|
return false, fmt.Errorf("%w: delete session: %v", ErrUnavailable, err)
|
|
}
|
|
|
|
return n > 0, nil
|
|
}
|