Перенесите реализацию ЛР 4 на стенд ЛР 5
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
// Package store holds the session store implementations.
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"messenger/internal/auth"
|
||||
"messenger/internal/platform/apperr"
|
||||
)
|
||||
|
||||
const keyPrefix = "session:"
|
||||
|
||||
// Sessions keeps one key per session, session:<sha256 of token>, holding the
|
||||
// owner's id. Valkey expires the key itself, so no cleanup job is needed.
|
||||
type Sessions struct {
|
||||
client *redis.Client
|
||||
}
|
||||
|
||||
var _ auth.Repository = (*Sessions)(nil)
|
||||
|
||||
func NewSessions(client *redis.Client) *Sessions {
|
||||
return &Sessions{client: client}
|
||||
}
|
||||
|
||||
// Create sets an absolute expiry (EXAT/PXAT): a restart of the store replays
|
||||
// it from the append-only file and does not extend the session.
|
||||
func (r *Sessions) Create(ctx context.Context, s auth.Session) error {
|
||||
err := r.client.SetArgs(ctx, keyPrefix+s.TokenHash, s.UserID.String(), redis.SetArgs{ExpireAt: s.ExpiresAt}).Err()
|
||||
if err != nil {
|
||||
return unavailable(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Sessions) UserID(ctx context.Context, tokenHash string) (uuid.UUID, error) {
|
||||
raw, err := r.client.Get(ctx, keyPrefix+tokenHash).Result()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return uuid.Nil, auth.ErrUnauthenticated
|
||||
}
|
||||
if err != nil {
|
||||
return uuid.Nil, unavailable(err)
|
||||
}
|
||||
id, err := uuid.Parse(raw)
|
||||
if err != nil {
|
||||
return uuid.Nil, fmt.Errorf("session holds a malformed user id: %w", err)
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func (r *Sessions) Delete(ctx context.Context, tokenHash string) error {
|
||||
if err := r.client.Del(ctx, keyPrefix+tokenHash).Err(); err != nil {
|
||||
return unavailable(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func unavailable(err error) error {
|
||||
return apperr.Wrap(apperr.KindUnavailable, "session store unavailable", err)
|
||||
}
|
||||
Reference in New Issue
Block a user