Files
mtusi2026lab5/internal/storage/postgres/session_repository.go
T
2026-10-29 23:36:12 +03:00

95 lines
2.5 KiB
Go

package postgres
import (
"context"
"errors"
"fmt"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/storage/postgres/internal/sqlcgen"
)
type SessionRepository struct {
store *Store
}
func (r *SessionRepository) Credentials(ctx context.Context, username string) (domain.UserCredentials, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
row, err := r.store.queries.GetUserByUsername(ctx, username)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return domain.UserCredentials{}, fmt.Errorf("%w: username %q", domain.ErrUnauthenticated, username)
}
return domain.UserCredentials{}, fmt.Errorf("load credentials: %w", mapError(err))
}
return domain.UserCredentials{
User: domain.User{
ID: row.ID,
Username: row.Username,
DisplayName: row.DisplayName,
CreatedAt: toUTCTime(row.CreatedAt),
},
PasswordHash: row.PasswordHash,
}, nil
}
func (r *SessionRepository) Create(ctx context.Context, session domain.NewSession) (domain.Session, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
row, err := r.store.queries.CreateSession(ctx, sqlcgen.CreateSessionParams{
TokenHash: session.TokenHash,
UserID: session.UserID,
ExpiresAt: session.ExpiresAt,
})
if err != nil {
return domain.Session{}, fmt.Errorf("create session: %w", mapError(err))
}
return domain.Session{ExpiresAt: toUTCTime(row.ExpiresAt)}, nil
}
func (r *SessionRepository) Resolve(ctx context.Context, tokenHash []byte) (domain.Session, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
row, err := r.store.queries.GetSessionUser(ctx, tokenHash)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return domain.Session{}, fmt.Errorf("%w: session not found or expired", domain.ErrUnauthenticated)
}
return domain.Session{}, fmt.Errorf("resolve session: %w", mapError(err))
}
return domain.Session{
ExpiresAt: toUTCTime(row.ExpiresAt),
User: domain.User{
ID: row.ID,
Username: row.Username,
DisplayName: row.DisplayName,
CreatedAt: toUTCTime(row.CreatedAt),
},
}, nil
}
func (r *SessionRepository) Revoke(ctx context.Context, userID uuid.UUID, tokenHash []byte) error {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
if err := r.store.queries.DeleteSession(
ctx, sqlcgen.DeleteSessionParams{TokenHash: tokenHash, UserID: userID},
); err != nil {
return fmt.Errorf("revoke session: %w", mapError(err))
}
return nil
}