Files
lincodex/backend/internal/adapter/secondary/postgres/identity.go
T

728 lines
27 KiB
Go

package postgres
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// PostgreSQL stores timestamps with microsecond precision, so a stored time
// is the written time truncated to microseconds.
const (
foreignKeyViolationCode = "23503"
// restrictViolationCode is raised by an ON DELETE RESTRICT foreign key.
restrictViolationCode = "23001"
// consentSubjectForeignKey restricts the delete of an account with
// consent records.
consentSubjectForeignKey = "consent_records_subject_id_fkey"
// sessionTouchInterval is the minimum age of last_seen_at before Touch
// writes it again. It bounds session writes to one per minute per session
// at the cost of ending an idle session up to a minute early.
sessionTouchInterval = time.Minute
)
type constraintViolation struct {
code string
constraint string
}
// identityConstraintErrors maps the identity constraints whose violation is a
// caller-visible outcome to port sentinels. Matching uses SQLSTATE and the
// constraint name from the migration, never the error text.
var identityConstraintErrors = map[constraintViolation]error{
{uniqueViolationCode, "users_email_normalized_key"}: outbound.ErrEmailTaken,
{uniqueViolationCode, "email_tokens_token_hash_key"}: outbound.ErrTokenHashConflict,
{uniqueViolationCode, "sessions_token_hash_key"}: outbound.ErrTokenHashConflict,
{foreignKeyViolationCode, "email_tokens_user_id_fkey"}: outbound.ErrUserNotFound,
{foreignKeyViolationCode, "sessions_user_id_fkey"}: outbound.ErrUserNotFound,
}
// mapIdentityError turns a known identity constraint violation into its port
// sentinel and keeps the constraint name. Any other PostgreSQL error is
// replaced by its SQLSTATE and constraint name, because its message and
// detail can quote row values such as an email address or a password hash.
// Deadlocks and serialization failures also match ErrTransactionConflict.
// Errors that do not come from PostgreSQL pass through.
func mapIdentityError(err error) error {
var pgError *pgconn.PgError
if !errors.As(err, &pgError) {
return err
}
if sentinel, ok := identityConstraintErrors[constraintViolation{code: pgError.Code, constraint: pgError.ConstraintName}]; ok {
return fmt.Errorf("postgres.mapIdentityError - violate constraint %s: %w", pgError.ConstraintName, sentinel)
}
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
}
// IdentityStore provides the identity repositories outside a transaction.
// Every call runs as its own statement on a pool connection. A call with a
// context that belongs to a Transactor callback fails with
// outbound.ErrNestedTransaction instead of committing independently of that
// transaction; use the UnitOfWork accessors there.
type IdentityStore struct {
queries *sqlc.Queries
}
func NewIdentityStore(pool *pgxpool.Pool) *IdentityStore {
return &IdentityStore{queries: sqlc.New(standaloneDB{pool: pool})}
}
var (
_ outbound.IdentityRepositories = (*IdentityStore)(nil)
_ outbound.IdentityRepositories = (*UnitOfWork)(nil)
)
func (store *IdentityStore) Users() outbound.UserRepository {
return userRepository{queries: store.queries}
}
func (store *IdentityStore) EmailTokens() outbound.EmailTokenRepository {
return emailTokenRepository{queries: store.queries}
}
func (store *IdentityStore) Sessions() outbound.SessionRepository {
return sessionRepository{queries: store.queries}
}
func (store *IdentityStore) IdempotencyRecords() outbound.IdempotencyRepository {
return idempotencyRepository{queries: store.queries}
}
func (unit *UnitOfWork) IdempotencyRecords() outbound.IdempotencyRepository {
return idempotencyRepository{queries: unit.queries}
}
func (unit *UnitOfWork) Users() outbound.UserRepository {
return userRepository{queries: unit.queries}
}
func (unit *UnitOfWork) EmailTokens() outbound.EmailTokenRepository {
return emailTokenRepository{queries: unit.queries}
}
func (unit *UnitOfWork) Sessions() outbound.SessionRepository {
return sessionRepository{queries: unit.queries}
}
// standaloneDB runs statements on the pool and refuses a context that belongs
// to a Transactor callback, where a pool statement would silently bypass the
// surrounding transaction.
type standaloneDB struct {
pool *pgxpool.Pool
}
func (db standaloneDB) Exec(ctx context.Context, sql string, arguments ...any) (pgconn.CommandTag, error) {
if err := refuseTransactionContext(ctx); err != nil {
return pgconn.CommandTag{}, err
}
return db.pool.Exec(ctx, sql, arguments...)
}
func (db standaloneDB) Query(ctx context.Context, sql string, arguments ...any) (pgx.Rows, error) {
if err := refuseTransactionContext(ctx); err != nil {
return nil, err
}
return db.pool.Query(ctx, sql, arguments...)
}
func (db standaloneDB) QueryRow(ctx context.Context, sql string, arguments ...any) pgx.Row {
if err := refuseTransactionContext(ctx); err != nil {
return errorRow{err: err}
}
return db.pool.QueryRow(ctx, sql, arguments...)
}
func refuseTransactionContext(ctx context.Context) error {
if ctx.Value(transactionContextKey{}) != nil {
return fmt.Errorf("postgres.refuseTransactionContext - run a pool statement inside a transaction callback: %w", outbound.ErrNestedTransaction)
}
return nil
}
// errorRow reports err from Scan, as pgx does for a failed QueryRow.
type errorRow struct {
err error
}
func (row errorRow) Scan(...any) error { return row.err }
// requireTime rejects the zero time, which would make every deadline check
// pass or fail silently.
func requireTime(location string, at time.Time, sentinel error) error {
if at.IsZero() {
return fmt.Errorf("%s - time must be set: %w", location, sentinel)
}
return nil
}
type userRepository struct {
queries *sqlc.Queries
}
func (repository userRepository) Create(ctx context.Context, user domain.User) error {
if user.ID == uuid.Nil || user.Email.IsZero() || user.PasswordHash.IsZero() {
return fmt.Errorf("userRepository.Create - user was not built by domain.NewUser: %w", domain.ErrInvalidUser)
}
err := repository.queries.InsertUser(ctx, sqlc.InsertUserParams{
ID: pgUUID(user.ID),
Email: user.Email.Address(),
EmailNormalized: user.Email.Normalized(),
PasswordHash: user.PasswordHash.PHC(),
Scenario: string(user.Scenario),
OnboardingStep: string(user.OnboardingStep),
EmailVerifiedAt: pgOptionalTime(user.EmailVerifiedAt),
RegistrationVersion: user.RegistrationVersion,
LastRegisteredAt: pgTime(user.LastRegisteredAt),
Version: user.Version,
CreatedAt: pgTime(user.CreatedAt),
UpdatedAt: pgTime(user.UpdatedAt),
})
if err != nil {
return fmt.Errorf("userRepository.Create - insert user: %w", mapIdentityError(err))
}
return nil
}
func (repository userRepository) GetByID(ctx context.Context, id uuid.UUID) (domain.User, error) {
row, err := repository.queries.GetUserByID(ctx, pgUUID(id))
if err != nil {
return domain.User{}, fmt.Errorf("userRepository.GetByID - select user: %w", mapNoRows(err, outbound.ErrUserNotFound))
}
return userFromRow(row)
}
func (repository userRepository) GetByEmail(ctx context.Context, email domain.EmailAddress) (domain.User, error) {
row, err := repository.queries.GetUserByEmailNormalized(ctx, email.Normalized())
if err != nil {
return domain.User{}, fmt.Errorf("userRepository.GetByEmail - select user: %w", mapNoRows(err, outbound.ErrUserNotFound))
}
return userFromRow(row)
}
func (repository userRepository) UpdateRegistration(ctx context.Context, user domain.User) (domain.User, error) {
if err := requireTime("userRepository.UpdateRegistration", user.LastRegisteredAt, domain.ErrInvalidUser); err != nil {
return domain.User{}, err
}
row, err := repository.queries.UpdateUserRegistration(ctx, sqlc.UpdateUserRegistrationParams{
ID: pgUUID(user.ID),
ExpectedVersion: user.Version,
Email: user.Email.Address(),
PasswordHash: user.PasswordHash.PHC(),
Scenario: string(user.Scenario),
OnboardingStep: string(user.OnboardingStep),
LastRegisteredAt: pgTime(user.LastRegisteredAt),
UpdatedAt: pgTime(user.UpdatedAt),
})
if err != nil {
return domain.User{}, fmt.Errorf("userRepository.UpdateRegistration - update user: %w", mapNoRows(err, outbound.ErrUserVersionConflict))
}
// The statement returns the users columns through a CTE, so sqlc gives
// it its own row type with the same fields.
return userFromRow(sqlc.User(row))
}
func (repository userRepository) AdvanceRegistration(
ctx context.Context,
id uuid.UUID,
expectedVersion int64,
at time.Time,
) (domain.User, error) {
if err := requireTime("userRepository.AdvanceRegistration", at, domain.ErrInvalidUser); err != nil {
return domain.User{}, err
}
row, err := repository.queries.AdvanceUserRegistration(ctx, sqlc.AdvanceUserRegistrationParams{
ID: pgUUID(id),
ExpectedVersion: expectedVersion,
RegisteredAt: pgTime(at),
})
if err != nil {
return domain.User{}, fmt.Errorf("userRepository.AdvanceRegistration - update user: %w", mapNoRows(err, outbound.ErrUserVersionConflict))
}
return userFromRow(sqlc.User(row))
}
func (repository userRepository) MarkEmailVerified(
ctx context.Context,
id uuid.UUID,
registrationVersion int64,
at time.Time,
) (domain.User, error) {
if err := requireTime("userRepository.MarkEmailVerified", at, domain.ErrInvalidUser); err != nil {
return domain.User{}, err
}
row, err := repository.queries.MarkUserEmailVerified(ctx, sqlc.MarkUserEmailVerifiedParams{
ID: pgUUID(id),
RegistrationVersion: registrationVersion,
VerifiedAt: pgTime(at),
})
if err != nil {
return domain.User{}, fmt.Errorf("userRepository.MarkEmailVerified - update user: %w", mapNoRows(err, outbound.ErrUserVersionConflict))
}
return userFromRow(row)
}
func (repository userRepository) ConfirmEmail(
ctx context.Context,
id uuid.UUID,
registrationVersion int64,
pending domain.PendingRegistration,
at time.Time,
) (domain.User, error) {
const location = "userRepository.ConfirmEmail"
if err := requireTime(location, at, domain.ErrInvalidUser); err != nil {
return domain.User{}, err
}
if pending.PasswordHash.IsZero() || !pending.Scenario.AllowsStep(pending.OnboardingStep) {
return domain.User{}, fmt.Errorf("%s - pending registration was not built by domain.NewPendingRegistration: %w", location, domain.ErrInvalidUser)
}
row, err := repository.queries.ConfirmUserEmail(ctx, sqlc.ConfirmUserEmailParams{
ID: pgUUID(id),
RegistrationVersion: registrationVersion,
PasswordHash: pending.PasswordHash.PHC(),
Scenario: string(pending.Scenario),
OnboardingStep: string(pending.OnboardingStep),
VerifiedAt: pgTime(at),
})
if err != nil {
return domain.User{}, fmt.Errorf("%s - apply pending registration: %w", location, mapNoRows(err, outbound.ErrUserVersionConflict))
}
return userFromRow(row)
}
func (repository userRepository) DeleteUnverifiedRegisteredBefore(ctx context.Context, cutoff time.Time, limit int32) (int64, error) {
if err := requireTime("userRepository.DeleteUnverifiedRegisteredBefore", cutoff, domain.ErrInvalidUser); err != nil {
return 0, err
}
if limit <= 0 {
return 0, errors.New("userRepository.DeleteUnverifiedRegisteredBefore - limit must be positive")
}
deleted, err := repository.queries.DeleteUnverifiedUsersRegisteredBefore(ctx, sqlc.DeleteUnverifiedUsersRegisteredBeforeParams{
Cutoff: pgTime(cutoff),
BatchLimit: limit,
})
if err != nil {
return 0, fmt.Errorf("userRepository.DeleteUnverifiedRegisteredBefore - delete users: %w", mapCleanupError(err))
}
return deleted, nil
}
// mapCleanupError reports the restricting consent foreign key as a
// transaction conflict. The cleanup checks consent rows in its statement
// snapshot, so a consent committed for a candidate account after the
// snapshot but before the account lock passes that check and then fails
// the foreign key at the end of the statement. Nothing was deleted, and the
// next run sees the consent and skips or removes the account.
func mapCleanupError(err error) error {
var pgError *pgconn.PgError
if errors.As(err, &pgError) && pgError.Code == restrictViolationCode && pgError.ConstraintName == consentSubjectForeignKey {
return fmt.Errorf("postgres.mapCleanupError - consent recorded concurrently: %w: %w",
outbound.ErrTransactionConflict, &databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
}
return mapIdentityError(err)
}
func userFromRow(row sqlc.User) (domain.User, error) {
email, err := domain.RestoreEmailAddress(row.Email, row.EmailNormalized)
if err != nil {
return domain.User{}, fmt.Errorf("postgres.userFromRow - decode email: %w", err)
}
passwordHash, err := domain.NewPasswordHash(row.PasswordHash)
if err != nil {
return domain.User{}, fmt.Errorf("postgres.userFromRow - decode password hash: %w", err)
}
scenario, err := domain.ParseScenario(row.Scenario)
if err != nil {
return domain.User{}, fmt.Errorf("postgres.userFromRow - decode scenario: %w", err)
}
step, err := domain.ParseOnboardingStep(row.OnboardingStep)
if err != nil {
return domain.User{}, fmt.Errorf("postgres.userFromRow - decode onboarding step: %w", err)
}
return domain.User{
ID: uuid.UUID(row.ID.Bytes),
Email: email,
PasswordHash: passwordHash,
Scenario: scenario,
OnboardingStep: step,
EmailVerifiedAt: optionalTime(row.EmailVerifiedAt),
RegistrationVersion: row.RegistrationVersion,
LastRegisteredAt: row.LastRegisteredAt.Time,
Version: row.Version,
CreatedAt: row.CreatedAt.Time,
UpdatedAt: row.UpdatedAt.Time,
}, nil
}
type emailTokenRepository struct {
queries *sqlc.Queries
}
func (repository emailTokenRepository) FindByHash(
ctx context.Context,
hash domain.SecretTokenHash,
purpose domain.EmailTokenPurpose,
) (domain.EmailToken, error) {
const location = "emailTokenRepository.FindByHash"
if hash.IsZero() {
return domain.EmailToken{}, fmt.Errorf("%s - token hash must be set: %w", location, domain.ErrInvalidEmailToken)
}
if _, err := domain.ParseEmailTokenPurpose(string(purpose)); err != nil {
return domain.EmailToken{}, fmt.Errorf("%s - validate purpose: %w", location, err)
}
row, err := repository.queries.GetEmailTokenByHash(ctx, sqlc.GetEmailTokenByHashParams{
TokenHash: hash[:],
Purpose: string(purpose),
})
if err != nil {
return domain.EmailToken{}, fmt.Errorf("%s - select email token: %w", location, mapNoRows(err, outbound.ErrEmailTokenNotFound))
}
owner, err := repository.queries.GetUserByID(ctx, row.UserID)
if err != nil {
return domain.EmailToken{}, fmt.Errorf("%s - read token owner: %w", location, mapNoRows(err, outbound.ErrEmailTokenInvalidated))
}
if owner.RegistrationVersion != row.RegistrationVersion {
return domain.EmailToken{}, fmt.Errorf("%s - token belongs to an earlier registration: %w", location, outbound.ErrEmailTokenInvalidated)
}
return emailTokenFromRow(row)
}
func (repository emailTokenRepository) Insert(ctx context.Context, token domain.EmailToken) error {
if token.ID == uuid.Nil || token.TokenHash.IsZero() {
return fmt.Errorf("emailTokenRepository.Insert - token was not built by domain.NewEmailToken: %w", domain.ErrInvalidEmailToken)
}
params := sqlc.InsertEmailTokenParams{
ID: pgUUID(token.ID),
UserID: pgUUID(token.UserID),
Purpose: string(token.Purpose),
TokenHash: token.TokenHash[:],
RegistrationVersion: token.RegistrationVersion,
CreatedAt: pgTime(token.CreatedAt),
ExpiresAt: pgTime(token.ExpiresAt),
}
if pending := token.Pending; pending != nil {
params.PendingPasswordHash = pgtype.Text{String: pending.PasswordHash.PHC(), Valid: true}
params.PendingScenario = pgtype.Text{String: string(pending.Scenario), Valid: true}
params.PendingOnboardingStep = pgtype.Text{String: string(pending.OnboardingStep), Valid: true}
}
if err := repository.queries.InsertEmailToken(ctx, params); err != nil {
return fmt.Errorf("emailTokenRepository.Insert - insert email token: %w", mapIdentityError(err))
}
return nil
}
func (repository emailTokenRepository) LatestPending(
ctx context.Context,
userID uuid.UUID,
registrationVersion int64,
) (domain.PendingRegistration, bool, error) {
row, err := repository.queries.GetLatestPendingRegistration(ctx, sqlc.GetLatestPendingRegistrationParams{
UserID: pgUUID(userID),
Purpose: string(domain.EmailTokenPurposeEmailVerification),
RegistrationVersion: registrationVersion,
})
if errors.Is(err, pgx.ErrNoRows) {
return domain.PendingRegistration{}, false, nil
}
if err != nil {
return domain.PendingRegistration{}, false, fmt.Errorf("emailTokenRepository.LatestPending - select pending registration: %w", mapIdentityError(err))
}
pending, err := pendingFromColumns(row.PendingPasswordHash, row.PendingScenario, row.PendingOnboardingStep)
if err != nil {
return domain.PendingRegistration{}, false, err
}
return *pending, true, nil
}
// pendingFromColumns decodes the pending credentials of a token row; nil when
// the token carries none.
func pendingFromColumns(hash, scenario, step pgtype.Text) (*domain.PendingRegistration, error) {
if !hash.Valid {
return nil, nil
}
passwordHash, err := domain.NewPasswordHash(hash.String)
if err != nil {
return nil, fmt.Errorf("postgres.pendingFromColumns - decode password hash: %w", err)
}
parsedScenario, err := domain.ParseScenario(scenario.String)
if err != nil {
return nil, fmt.Errorf("postgres.pendingFromColumns - decode scenario: %w", err)
}
parsedStep, err := domain.ParseOnboardingStep(step.String)
if err != nil {
return nil, fmt.Errorf("postgres.pendingFromColumns - decode onboarding step: %w", err)
}
return &domain.PendingRegistration{PasswordHash: passwordHash, Scenario: parsedScenario, OnboardingStep: parsedStep}, nil
}
func (repository emailTokenRepository) InvalidateActive(
ctx context.Context,
userID uuid.UUID,
purpose domain.EmailTokenPurpose,
at time.Time,
) (int64, error) {
if err := requireTime("emailTokenRepository.InvalidateActive", at, domain.ErrInvalidEmailToken); err != nil {
return 0, err
}
invalidated, err := repository.queries.InvalidateActiveEmailTokens(ctx, sqlc.InvalidateActiveEmailTokensParams{
UserID: pgUUID(userID),
Purpose: string(purpose),
InvalidatedAt: pgTime(at),
})
if err != nil {
return 0, fmt.Errorf("emailTokenRepository.InvalidateActive - update email tokens: %w", mapIdentityError(err))
}
return invalidated, nil
}
func (repository emailTokenRepository) Consume(
ctx context.Context,
hash domain.SecretTokenHash,
purpose domain.EmailTokenPurpose,
at time.Time,
) (domain.EmailToken, error) {
if err := requireTime("emailTokenRepository.Consume", at, domain.ErrInvalidEmailToken); err != nil {
return domain.EmailToken{}, err
}
row, err := repository.queries.ConsumeEmailToken(ctx, sqlc.ConsumeEmailTokenParams{
TokenHash: hash[:],
Purpose: string(purpose),
ConsumedAt: pgTime(at),
})
if err == nil {
return emailTokenFromRow(sqlc.EmailToken(row))
}
if !errors.Is(err, pgx.ErrNoRows) {
return domain.EmailToken{}, fmt.Errorf("emailTokenRepository.Consume - update email token: %w", mapIdentityError(err))
}
if err := repository.explainUnconsumable(ctx, hash, purpose, at); err != nil {
return domain.EmailToken{}, fmt.Errorf("emailTokenRepository.Consume - consume email token: %w", err)
}
return domain.EmailToken{}, errors.New("emailTokenRepository.Consume - token became consumable after a failed attempt")
}
// explainUnconsumable classifies a token that the atomic consume did not
// match. A nil result means the token is consumable again, which only a
// concurrent transaction that changed and then rolled back the row can cause.
func (repository emailTokenRepository) explainUnconsumable(
ctx context.Context,
hash domain.SecretTokenHash,
purpose domain.EmailTokenPurpose,
at time.Time,
) error {
state, err := repository.queries.GetEmailTokenState(ctx, sqlc.GetEmailTokenStateParams{
TokenHash: hash[:],
Purpose: string(purpose),
})
if err != nil {
return fmt.Errorf("emailTokenRepository.explainUnconsumable - select token state: %w", mapNoRows(err, outbound.ErrEmailTokenNotFound))
}
switch {
case state.ConsumedAt.Valid:
return outbound.ErrEmailTokenConsumed
case state.InvalidatedAt.Valid || !state.CurrentRegistration:
return outbound.ErrEmailTokenInvalidated
case !state.ExpiresAt.Time.After(at):
return outbound.ErrEmailTokenExpired
default:
return nil
}
}
func emailTokenFromRow(row sqlc.EmailToken) (domain.EmailToken, error) {
purpose, err := domain.ParseEmailTokenPurpose(row.Purpose)
if err != nil {
return domain.EmailToken{}, fmt.Errorf("postgres.emailTokenFromRow - decode purpose: %w", err)
}
hash, err := tokenHashFromBytes(row.TokenHash)
if err != nil {
return domain.EmailToken{}, err
}
pending, err := pendingFromColumns(row.PendingPasswordHash, row.PendingScenario, row.PendingOnboardingStep)
if err != nil {
return domain.EmailToken{}, err
}
return domain.EmailToken{
Pending: pending,
ID: uuid.UUID(row.ID.Bytes),
UserID: uuid.UUID(row.UserID.Bytes),
Purpose: purpose,
TokenHash: hash,
RegistrationVersion: row.RegistrationVersion,
CreatedAt: row.CreatedAt.Time,
ExpiresAt: row.ExpiresAt.Time,
ConsumedAt: optionalTime(row.ConsumedAt),
InvalidatedAt: optionalTime(row.InvalidatedAt),
}, nil
}
type sessionRepository struct {
queries *sqlc.Queries
}
func (repository sessionRepository) Create(ctx context.Context, session domain.Session) error {
if session.ID == uuid.Nil || session.TokenHash.IsZero() {
return fmt.Errorf("sessionRepository.Create - session was not built by domain.NewSession: %w", domain.ErrInvalidSession)
}
err := repository.queries.InsertSession(ctx, sqlc.InsertSessionParams{
ID: pgUUID(session.ID),
UserID: pgUUID(session.UserID),
TokenHash: session.TokenHash[:],
CreatedAt: pgTime(session.CreatedAt),
LastSeenAt: pgTime(session.LastSeenAt),
ExpiresAt: pgTime(session.ExpiresAt),
})
if err != nil {
return fmt.Errorf("sessionRepository.Create - insert session: %w", mapIdentityError(err))
}
return nil
}
func (repository sessionRepository) FindActive(
ctx context.Context,
hash domain.SecretTokenHash,
at time.Time,
idleTimeout time.Duration,
) (domain.Session, error) {
if err := validateSessionCheck("sessionRepository.FindActive", at, idleTimeout); err != nil {
return domain.Session{}, err
}
row, err := repository.queries.GetActiveSessionByTokenHash(ctx, sqlc.GetActiveSessionByTokenHashParams{
TokenHash: hash[:],
At: pgTime(at),
IdleCutoff: pgTime(at.Add(-idleTimeout)),
})
if err != nil {
return domain.Session{}, fmt.Errorf("sessionRepository.FindActive - select session: %w", mapNoRows(err, outbound.ErrSessionNotFound))
}
return sessionFromRow(row)
}
func (repository sessionRepository) Touch(ctx context.Context, id uuid.UUID, at time.Time, idleTimeout time.Duration) error {
if err := validateSessionCheck("sessionRepository.Touch", at, idleTimeout); err != nil {
return err
}
result, err := repository.queries.TouchSession(ctx, sqlc.TouchSessionParams{
ID: pgUUID(id),
At: pgTime(at),
IdleCutoff: pgTime(at.Add(-idleTimeout)),
TouchCutoff: pgTime(at.Add(-sessionTouchInterval)),
})
if err != nil {
return fmt.Errorf("sessionRepository.Touch - update session: %w", mapIdentityError(err))
}
if !result.Active {
return fmt.Errorf("sessionRepository.Touch - update session: %w", outbound.ErrSessionNotFound)
}
return nil
}
func validateSessionCheck(location string, at time.Time, idleTimeout time.Duration) error {
if err := requireTime(location, at, domain.ErrInvalidSession); err != nil {
return err
}
if idleTimeout <= 0 {
return fmt.Errorf("%s - idle timeout must be positive: %w", location, domain.ErrInvalidSession)
}
return nil
}
func (repository sessionRepository) Revoke(ctx context.Context, id uuid.UUID, at time.Time) error {
if err := requireTime("sessionRepository.Revoke", at, domain.ErrInvalidSession); err != nil {
return err
}
revoked, err := repository.queries.RevokeSession(ctx, sqlc.RevokeSessionParams{
ID: pgUUID(id),
RevokedAt: pgTime(at),
})
if err != nil {
return fmt.Errorf("sessionRepository.Revoke - update session: %w", mapIdentityError(err))
}
if revoked == 0 {
return fmt.Errorf("sessionRepository.Revoke - update session: %w", outbound.ErrSessionNotFound)
}
return nil
}
func (repository sessionRepository) RevokeAllForUser(ctx context.Context, userID uuid.UUID, at time.Time) (int64, error) {
if err := requireTime("sessionRepository.RevokeAllForUser", at, domain.ErrInvalidSession); err != nil {
return 0, err
}
revoked, err := repository.queries.RevokeUserSessions(ctx, sqlc.RevokeUserSessionsParams{
UserID: pgUUID(userID),
RevokedAt: pgTime(at),
})
if err != nil {
return 0, fmt.Errorf("sessionRepository.RevokeAllForUser - update sessions: %w", mapIdentityError(err))
}
return revoked, nil
}
func sessionFromRow(row sqlc.Session) (domain.Session, error) {
hash, err := tokenHashFromBytes(row.TokenHash)
if err != nil {
return domain.Session{}, err
}
return domain.Session{
ID: uuid.UUID(row.ID.Bytes),
UserID: uuid.UUID(row.UserID.Bytes),
TokenHash: hash,
CreatedAt: row.CreatedAt.Time,
LastSeenAt: row.LastSeenAt.Time,
ExpiresAt: row.ExpiresAt.Time,
RevokedAt: optionalTime(row.RevokedAt),
}, nil
}
func tokenHashFromBytes(stored []byte) (domain.SecretTokenHash, error) {
var hash domain.SecretTokenHash
if len(stored) != len(hash) {
return hash, errors.New("postgres.tokenHashFromBytes - stored token hash is not a SHA-256 digest")
}
copy(hash[:], stored)
return hash, nil
}
// mapNoRows replaces pgx.ErrNoRows with the port sentinel for a missing or
// unmatched row and maps other errors with mapIdentityError.
func mapNoRows(err, sentinel error) error {
if errors.Is(err, pgx.ErrNoRows) {
return sentinel
}
return mapIdentityError(err)
}
func pgUUID(id uuid.UUID) pgtype.UUID {
return pgtype.UUID{Bytes: id, Valid: true}
}
func pgTime(value time.Time) pgtype.Timestamptz {
return pgtype.Timestamptz{Time: value, Valid: true}
}
func pgOptionalTime(value *time.Time) pgtype.Timestamptz {
if value == nil {
return pgtype.Timestamptz{}
}
return pgTime(*value)
}
func optionalTime(value pgtype.Timestamptz) *time.Time {
if !value.Valid {
return nil
}
return &value.Time
}