forked from mtusi2026/mtusi2026lab4
164 lines
3.9 KiB
Go
164 lines
3.9 KiB
Go
package session
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/valkey-io/valkey-go"
|
|
|
|
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/model"
|
|
)
|
|
|
|
const (
|
|
tokenLength = 32
|
|
keyPrefix = "session:"
|
|
)
|
|
|
|
var (
|
|
ErrNotFound = model.ErrSessionNotFound
|
|
ErrInvalidToken = model.ErrInvalidToken
|
|
ErrInvalidRecord = errors.New("invalid session record")
|
|
ErrInvalidTTL = errors.New("invalid session TTL")
|
|
ErrTokenGeneration = errors.New("session token generation failed")
|
|
ErrStore = model.ErrUnavailable
|
|
)
|
|
|
|
type record struct {
|
|
UserID string `json:"user_id"`
|
|
ExpiresAt time.Time `json:"expires_at"`
|
|
}
|
|
|
|
type Store struct {
|
|
client valkey.Client
|
|
}
|
|
|
|
func New(rawURL string) (*Store, error) {
|
|
option, err := valkey.ParseURL(rawURL)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%w: parse Valkey URL: %w", ErrStore, err)
|
|
}
|
|
|
|
client, err := valkey.NewClient(option)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%w: create Valkey client: %w", ErrStore, err)
|
|
}
|
|
|
|
return &Store{client: client}, nil
|
|
}
|
|
|
|
func (s *Store) Create(ctx context.Context, userID string, ttl time.Duration) (string, time.Time, error) {
|
|
if strings.TrimSpace(userID) == "" {
|
|
return "", time.Time{}, ErrInvalidRecord
|
|
}
|
|
if ttl < time.Second {
|
|
return "", time.Time{}, ErrInvalidTTL
|
|
}
|
|
|
|
token, err := newToken()
|
|
if err != nil {
|
|
return "", time.Time{}, err
|
|
}
|
|
|
|
record := record{
|
|
UserID: userID,
|
|
ExpiresAt: time.Now().UTC().Add(ttl).Truncate(time.Microsecond),
|
|
}
|
|
payload, err := json.Marshal(record)
|
|
if err != nil {
|
|
return "", time.Time{}, fmt.Errorf("%w: encode session: %w", ErrStore, err)
|
|
}
|
|
|
|
command := s.client.B().Set().Key(s.key(token)).Value(valkey.BinaryString(payload)).Ex(ttl).Build()
|
|
if err := s.client.Do(ctx, command).Error(); err != nil {
|
|
return "", time.Time{}, fmt.Errorf("%w: create session: %w", ErrStore, err)
|
|
}
|
|
|
|
return token, record.ExpiresAt, nil
|
|
}
|
|
|
|
func newToken() (string, error) {
|
|
random := make([]byte, tokenLength)
|
|
if _, err := rand.Read(random); err != nil {
|
|
return "", fmt.Errorf("%w: %v", ErrTokenGeneration, err)
|
|
}
|
|
return base64.RawURLEncoding.EncodeToString(random), nil
|
|
}
|
|
|
|
func (s *Store) UserID(ctx context.Context, token string) (string, error) {
|
|
key, err := s.sessionKey(token)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
payload, err := s.client.Do(ctx, s.client.B().Get().Key(key).Build()).AsBytes()
|
|
if valkey.IsValkeyNil(err) {
|
|
return "", ErrNotFound
|
|
}
|
|
if err != nil {
|
|
return "", fmt.Errorf("%w: get session: %w", ErrStore, err)
|
|
}
|
|
|
|
var record record
|
|
if err := json.Unmarshal(payload, &record); err != nil {
|
|
return "", fmt.Errorf("%w: decode session: %w", ErrStore, err)
|
|
}
|
|
if strings.TrimSpace(record.UserID) == "" || record.ExpiresAt.IsZero() {
|
|
return "", fmt.Errorf("%w: %w", ErrStore, ErrInvalidRecord)
|
|
}
|
|
if !record.ExpiresAt.After(time.Now()) {
|
|
return "", ErrNotFound
|
|
}
|
|
|
|
return record.UserID, nil
|
|
}
|
|
|
|
func (s *Store) Delete(ctx context.Context, token string) error {
|
|
key, err := s.sessionKey(token)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
deleted, err := s.client.Do(ctx, s.client.B().Del().Key(key).Build()).AsInt64()
|
|
if err != nil {
|
|
return fmt.Errorf("%w: delete session: %w", ErrStore, err)
|
|
}
|
|
if deleted == 0 {
|
|
return ErrNotFound
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (s *Store) Ping(ctx context.Context) error {
|
|
if err := s.client.Do(ctx, s.client.B().Ping().Build()).Error(); err != nil {
|
|
return fmt.Errorf("%w: ping Valkey: %w", ErrStore, err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *Store) Close() error {
|
|
s.client.Close()
|
|
return nil
|
|
}
|
|
|
|
func (s *Store) sessionKey(token string) (string, error) {
|
|
decoded, err := base64.RawURLEncoding.Strict().DecodeString(token)
|
|
if err != nil || len(decoded) != tokenLength {
|
|
return "", ErrInvalidToken
|
|
}
|
|
return s.key(token), nil
|
|
}
|
|
|
|
func (s *Store) key(token string) string {
|
|
digest := sha256.Sum256([]byte(token))
|
|
return keyPrefix + hex.EncodeToString(digest[:])
|
|
}
|