forked from mtusi2026/mtusi2026lab6
chore: import lab5 baseline
This commit is contained in:
@@ -0,0 +1,163 @@
|
||||
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/mtusi2026lab5/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[:])
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package session_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/session"
|
||||
)
|
||||
|
||||
type SessionSuite struct {
|
||||
suite.Suite
|
||||
store *session.Store
|
||||
}
|
||||
|
||||
func TestSessionSuite(t *testing.T) {
|
||||
suite.Run(t, new(SessionSuite))
|
||||
}
|
||||
|
||||
func (s *SessionSuite) SetupSuite() {
|
||||
rawURL := strings.TrimSpace(os.Getenv("TEST_CACHE_URL"))
|
||||
if rawURL == "" {
|
||||
path := strings.TrimSpace(os.Getenv("TEST_CACHE_URL_FILE"))
|
||||
if path == "" {
|
||||
s.T().Skip("set TEST_CACHE_URL or TEST_CACHE_URL_FILE to run integration tests")
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
s.Require().NoError(err)
|
||||
rawURL = strings.TrimSpace(string(data))
|
||||
}
|
||||
store, err := session.New(rawURL)
|
||||
s.Require().NoError(err)
|
||||
s.store = store
|
||||
}
|
||||
|
||||
func (s *SessionSuite) TearDownSuite() {
|
||||
if s.store != nil {
|
||||
s.Require().NoError(s.store.Close())
|
||||
}
|
||||
}
|
||||
|
||||
func (s *SessionSuite) TestSessionLifecycle() {
|
||||
userID := uuid.NewString()
|
||||
token, expiresAt, err := s.store.Create(context.Background(), userID, time.Minute)
|
||||
s.Require().NoError(err)
|
||||
s.NotEmpty(token)
|
||||
s.True(expiresAt.After(time.Now()))
|
||||
|
||||
actualUserID, err := s.store.UserID(context.Background(), token)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(userID, actualUserID)
|
||||
s.Require().NoError(s.store.Delete(context.Background(), token))
|
||||
|
||||
_, err = s.store.UserID(context.Background(), token)
|
||||
s.ErrorIs(err, session.ErrNotFound)
|
||||
}
|
||||
|
||||
func (s *SessionSuite) TestSessionExpires() {
|
||||
token, _, err := s.store.Create(context.Background(), uuid.NewString(), time.Second)
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Eventually(func() bool {
|
||||
_, err = s.store.UserID(context.Background(), token)
|
||||
return errors.Is(err, session.ErrNotFound)
|
||||
}, 3*time.Second, 50*time.Millisecond)
|
||||
}
|
||||
Reference in New Issue
Block a user