forked from mtusi2026/mtusi2026lab2
уровень 5 трек 1
This commit is contained in:
@@ -0,0 +1,73 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package sessionstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("session not found or expired")
|
||||
ErrUnavailable = errors.New("session store unavailable")
|
||||
)
|
||||
|
||||
type Store interface {
|
||||
Create(ctx context.Context, token, userID string, ttl time.Duration) (time.Time, error)
|
||||
GetUserID(ctx context.Context, token string) (string, error)
|
||||
Delete(ctx context.Context, token string) (bool, error)
|
||||
}
|
||||
Reference in New Issue
Block a user