feat(identity): store users, email tokens, and sessions
This commit is contained in:
1 parent
15e2e50561
commit
e7d0d92ef9
30 files changed
+4792
-32
No files matched your search
@@ -0,0 +1,54 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const (
|
||||
deadlockDetectedCode = "40P01"
|
||||
serializationFailureCode = "40001"
|
||||
)
|
||||
|
||||
// databaseError keeps only the SQLSTATE and constraint name of a PostgreSQL
|
||||
// error. The message and detail of a pgconn.PgError can quote row values, such
|
||||
// as an email address or a password hash, so repositories that handle
|
||||
// personal data return this type instead.
|
||||
type databaseError struct {
|
||||
code string
|
||||
constraint string
|
||||
}
|
||||
|
||||
func (err *databaseError) Error() string {
|
||||
if err.constraint == "" {
|
||||
return "PostgreSQL error SQLSTATE " + err.code
|
||||
}
|
||||
return "PostgreSQL error SQLSTATE " + err.code + " on constraint " + err.constraint
|
||||
}
|
||||
|
||||
// SQLState matches the method of pgconn.PgError, so callers can read the code
|
||||
// from either type.
|
||||
func (err *databaseError) SQLState() string { return err.code }
|
||||
|
||||
// sqlStateError is implemented by pgconn.PgError and databaseError.
|
||||
type sqlStateError interface {
|
||||
error
|
||||
SQLState() string
|
||||
}
|
||||
|
||||
// markTransactionConflict makes a deadlock or serialization failure also
|
||||
// match outbound.ErrTransactionConflict and returns other errors unchanged.
|
||||
func markTransactionConflict(err error) error {
|
||||
var stateError sqlStateError
|
||||
if err == nil || errors.Is(err, outbound.ErrTransactionConflict) || !errors.As(err, &stateError) {
|
||||
return err
|
||||
}
|
||||
switch code := stateError.SQLState(); code {
|
||||
case deadlockDetectedCode, serializationFailureCode:
|
||||
return fmt.Errorf("postgres.markTransactionConflict - SQLSTATE %s: %w: %w", code, outbound.ErrTransactionConflict, err)
|
||||
default:
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,566 @@
|
||||
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"
|
||||
|
||||
// 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 (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))
|
||||
}
|
||||
return userFromRow(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) 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", mapIdentityError(err))
|
||||
}
|
||||
return deleted, nil
|
||||
}
|
||||
|
||||
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) 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)
|
||||
}
|
||||
err := repository.queries.InsertEmailToken(ctx, 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 err != nil {
|
||||
return fmt.Errorf("emailTokenRepository.Insert - insert email token: %w", mapIdentityError(err))
|
||||
}
|
||||
return 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(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
|
||||
}
|
||||
return domain.EmailToken{
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
func TestMapIdentityErrorRecognizesIdentityConstraints(t *testing.T) {
|
||||
tests := []struct {
|
||||
code string
|
||||
constraint string
|
||||
want error
|
||||
}{
|
||||
{code: uniqueViolationCode, constraint: "users_email_normalized_key", want: outbound.ErrEmailTaken},
|
||||
{code: uniqueViolationCode, constraint: "email_tokens_token_hash_key", want: outbound.ErrTokenHashConflict},
|
||||
{code: uniqueViolationCode, constraint: "sessions_token_hash_key", want: outbound.ErrTokenHashConflict},
|
||||
{code: foreignKeyViolationCode, constraint: "email_tokens_user_id_fkey", want: outbound.ErrUserNotFound},
|
||||
{code: foreignKeyViolationCode, constraint: "sessions_user_id_fkey", want: outbound.ErrUserNotFound},
|
||||
}
|
||||
for _, test := range tests {
|
||||
err := mapIdentityError(&pgconn.PgError{Code: test.code, ConstraintName: test.constraint, Detail: "Key (x)=(secret) already exists."})
|
||||
if !errors.Is(err, test.want) {
|
||||
t.Fatalf("mapIdentityError(%s %s) = %v, want %v", test.code, test.constraint, err, test.want)
|
||||
}
|
||||
if !strings.Contains(err.Error(), test.constraint) || strings.Contains(err.Error(), "secret") {
|
||||
t.Fatalf("mapIdentityError(%s) = %v, want the constraint name and no detail", test.constraint, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMapIdentityErrorDropsMessageAndDetailOfOtherPostgreSQLErrors(t *testing.T) {
|
||||
original := fmt.Errorf("wrapped: %w", &pgconn.PgError{
|
||||
Code: "23514",
|
||||
ConstraintName: "users_password_hash_format",
|
||||
Message: `new row violates check constraint "users_password_hash_format" for value secret@example.com`,
|
||||
Detail: "Failing row contains (secret@example.com, $argon2id$v=19$...).",
|
||||
})
|
||||
err := mapIdentityError(original)
|
||||
var pgError *pgconn.PgError
|
||||
if errors.As(err, &pgError) {
|
||||
t.Fatalf("mapIdentityError() kept the PgError: %v", err)
|
||||
}
|
||||
var stateError sqlStateError
|
||||
if !errors.As(err, &stateError) || stateError.SQLState() != "23514" {
|
||||
t.Fatalf("mapIdentityError() = %v, want SQLSTATE 23514", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "users_password_hash_format") ||
|
||||
strings.Contains(err.Error(), "secret") || strings.Contains(err.Error(), "argon2id") {
|
||||
t.Fatalf("mapIdentityError() = %q, want only the code and constraint", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMapIdentityErrorKeepsNonPostgreSQLErrors(t *testing.T) {
|
||||
for _, original := range []error{
|
||||
errors.New(`duplicate key value violates unique constraint "users_email_normalized_key"`),
|
||||
pgx.ErrNoRows,
|
||||
context.Canceled,
|
||||
} {
|
||||
if err := mapIdentityError(original); err != original { //nolint:errorlint // Identity is the property under test.
|
||||
t.Fatalf("mapIdentityError(%v) = %v, want the original error", original, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMarkTransactionConflictClassifiesDeadlocksAndSerializationFailures(t *testing.T) {
|
||||
for _, original := range []error{
|
||||
&pgconn.PgError{Code: deadlockDetectedCode},
|
||||
fmt.Errorf("statement: %w", &pgconn.PgError{Code: serializationFailureCode}),
|
||||
&databaseError{code: deadlockDetectedCode},
|
||||
mapIdentityError(&pgconn.PgError{Code: serializationFailureCode}),
|
||||
} {
|
||||
err := markTransactionConflict(original)
|
||||
if !errors.Is(err, outbound.ErrTransactionConflict) || !errors.Is(err, original) {
|
||||
t.Fatalf("markTransactionConflict(%v) = %v, want ErrTransactionConflict wrapping the original", original, err)
|
||||
}
|
||||
if strings.Count(markTransactionConflict(err).Error(), "markTransactionConflict") != 1 {
|
||||
t.Fatalf("markTransactionConflict() wrapped an already classified error again: %v", markTransactionConflict(err))
|
||||
}
|
||||
}
|
||||
for _, original := range []error{
|
||||
nil,
|
||||
&pgconn.PgError{Code: uniqueViolationCode},
|
||||
&pgconn.PgError{Code: "55P03"},
|
||||
errors.New("connection reset"),
|
||||
} {
|
||||
if err := markTransactionConflict(original); err != original { //nolint:errorlint // Identity is the property under test.
|
||||
t.Fatalf("markTransactionConflict(%v) = %v, want the original error", original, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdentityStoreRefusesATransactionContext(t *testing.T) {
|
||||
// A nil pool proves that the guard runs before any statement.
|
||||
store := &IdentityStore{queries: sqlc.New(standaloneDB{})}
|
||||
ctx := context.WithValue(t.Context(), transactionContextKey{}, true)
|
||||
at := time.Now()
|
||||
checks := map[string]error{
|
||||
"GetByID": errorOf(store.Users().GetByID(ctx, uuid.New())),
|
||||
"DeleteUnverifiedRegisteredBefore": errorOf(store.Users().DeleteUnverifiedRegisteredBefore(ctx, at, 1)),
|
||||
"Consume": errorOf(store.EmailTokens().Consume(ctx, domain.SecretTokenHash{1}, domain.EmailTokenPurposeEmailVerification, at)),
|
||||
"InvalidateActive": errorOf(store.EmailTokens().InvalidateActive(ctx, uuid.New(), domain.EmailTokenPurposeEmailVerification, at)),
|
||||
"Touch": store.Sessions().Touch(ctx, uuid.New(), at, time.Hour),
|
||||
}
|
||||
for name, err := range checks {
|
||||
if !errors.Is(err, outbound.ErrNestedTransaction) {
|
||||
t.Fatalf("%s() error = %v, want ErrNestedTransaction", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// errorOf drops the value of a two-result call.
|
||||
func errorOf[T any](_ T, err error) error { return err }
|
||||
|
||||
func TestRepositoriesRejectInvalidInputBeforeTheDatabase(t *testing.T) {
|
||||
// A nil query set proves that validation happens before any statement.
|
||||
ctx := t.Context()
|
||||
users, tokens, sessions := userRepository{}, emailTokenRepository{}, sessionRepository{}
|
||||
now, id, hash := time.Now(), uuid.New(), domain.SecretTokenHash{1}
|
||||
purpose := domain.EmailTokenPurposeEmailVerification
|
||||
checks := []struct {
|
||||
name string
|
||||
err error
|
||||
want error
|
||||
}{
|
||||
{name: "Create(zero user)", err: users.Create(ctx, domain.User{}), want: domain.ErrInvalidUser},
|
||||
{name: "MarkEmailVerified(zero time)", err: errorOf(users.MarkEmailVerified(ctx, id, 1, time.Time{})), want: domain.ErrInvalidUser},
|
||||
{name: "DeleteUnverifiedRegisteredBefore(zero cutoff)", err: errorOf(users.DeleteUnverifiedRegisteredBefore(ctx, time.Time{}, 1)), want: domain.ErrInvalidUser},
|
||||
{name: "Insert(zero token)", err: tokens.Insert(ctx, domain.EmailToken{}), want: domain.ErrInvalidEmailToken},
|
||||
{name: "Consume(zero time)", err: errorOf(tokens.Consume(ctx, hash, purpose, time.Time{})), want: domain.ErrInvalidEmailToken},
|
||||
{name: "InvalidateActive(zero time)", err: errorOf(tokens.InvalidateActive(ctx, id, purpose, time.Time{})), want: domain.ErrInvalidEmailToken},
|
||||
{name: "Create(zero session)", err: sessions.Create(ctx, domain.Session{}), want: domain.ErrInvalidSession},
|
||||
{name: "FindActive(zero idle timeout)", err: errorOf(sessions.FindActive(ctx, hash, now, 0)), want: domain.ErrInvalidSession},
|
||||
{name: "FindActive(zero time)", err: errorOf(sessions.FindActive(ctx, hash, time.Time{}, time.Hour)), want: domain.ErrInvalidSession},
|
||||
{name: "Touch(negative idle timeout)", err: sessions.Touch(ctx, id, now, -time.Second), want: domain.ErrInvalidSession},
|
||||
{name: "Touch(zero time)", err: sessions.Touch(ctx, id, time.Time{}, time.Hour), want: domain.ErrInvalidSession},
|
||||
{name: "Revoke(zero time)", err: sessions.Revoke(ctx, id, time.Time{}), want: domain.ErrInvalidSession},
|
||||
{name: "RevokeAllForUser(zero time)", err: errorOf(sessions.RevokeAllForUser(ctx, id, time.Time{})), want: domain.ErrInvalidSession},
|
||||
}
|
||||
for _, check := range checks {
|
||||
if !errors.Is(check.err, check.want) {
|
||||
t.Fatalf("%s error = %v, want %v", check.name, check.err, check.want)
|
||||
}
|
||||
}
|
||||
if _, err := users.DeleteUnverifiedRegisteredBefore(ctx, now, 0); err == nil {
|
||||
t.Fatal("DeleteUnverifiedRegisteredBefore(limit 0) error = nil, want an error")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,689 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: identity.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const consumeEmailToken = `-- name: ConsumeEmailToken :one
|
||||
UPDATE email_tokens AS token
|
||||
SET consumed_at = $1
|
||||
FROM users AS owner
|
||||
WHERE
|
||||
token.token_hash = $2
|
||||
AND token.purpose = $3
|
||||
AND token.consumed_at IS NULL
|
||||
AND token.invalidated_at IS NULL
|
||||
AND token.expires_at > $1
|
||||
AND owner.id = token.user_id
|
||||
AND owner.registration_version = token.registration_version
|
||||
RETURNING
|
||||
token.id,
|
||||
token.user_id,
|
||||
token.purpose,
|
||||
token.token_hash,
|
||||
token.registration_version,
|
||||
token.created_at,
|
||||
token.expires_at,
|
||||
token.consumed_at,
|
||||
token.invalidated_at
|
||||
`
|
||||
|
||||
type ConsumeEmailTokenParams struct {
|
||||
ConsumedAt pgtype.Timestamptz
|
||||
TokenHash []byte
|
||||
Purpose string
|
||||
}
|
||||
|
||||
// Consumes a token in one statement. Concurrent callers queue on the token
|
||||
// row lock; under READ COMMITTED each waiter re-checks the WHERE clause
|
||||
// against the committed row, so exactly one of them updates it. The join
|
||||
// compares the registration version with the account row as the statement
|
||||
// reads it, without locking that row, so it rejects a token from an earlier
|
||||
// registration that already committed but not one that commits afterwards.
|
||||
// The confirmation guarantee therefore needs MarkUserEmailVerified with the
|
||||
// returned registration version in the same transaction, rolled back when it
|
||||
// matches no row.
|
||||
func (q *Queries) ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (EmailToken, error) {
|
||||
row := q.db.QueryRow(ctx, consumeEmailToken, arg.ConsumedAt, arg.TokenHash, arg.Purpose)
|
||||
var i EmailToken
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.UserID,
|
||||
&i.Purpose,
|
||||
&i.TokenHash,
|
||||
&i.RegistrationVersion,
|
||||
&i.CreatedAt,
|
||||
&i.ExpiresAt,
|
||||
&i.ConsumedAt,
|
||||
&i.InvalidatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const deleteUnverifiedUsersRegisteredBefore = `-- name: DeleteUnverifiedUsersRegisteredBefore :execrows
|
||||
WITH candidate AS (
|
||||
SELECT stale.id
|
||||
FROM users AS stale
|
||||
WHERE
|
||||
stale.email_verified_at IS NULL
|
||||
AND stale.last_registered_at < $1
|
||||
ORDER BY stale.last_registered_at
|
||||
LIMIT $2
|
||||
FOR UPDATE SKIP LOCKED
|
||||
),
|
||||
|
||||
locked_token AS (
|
||||
SELECT token.user_id
|
||||
FROM email_tokens AS token
|
||||
WHERE token.user_id IN (SELECT candidate.id FROM candidate)
|
||||
FOR UPDATE SKIP LOCKED
|
||||
),
|
||||
|
||||
locked_session AS (
|
||||
SELECT session.user_id
|
||||
FROM sessions AS session
|
||||
WHERE session.user_id IN (SELECT candidate.id FROM candidate)
|
||||
FOR UPDATE SKIP LOCKED
|
||||
),
|
||||
|
||||
deletable AS (
|
||||
SELECT candidate.id
|
||||
FROM candidate
|
||||
WHERE
|
||||
(
|
||||
SELECT count(*) FROM email_tokens AS token
|
||||
WHERE token.user_id = candidate.id
|
||||
) = (
|
||||
SELECT count(*) FROM locked_token
|
||||
WHERE locked_token.user_id = candidate.id
|
||||
)
|
||||
AND (
|
||||
SELECT count(*) FROM sessions AS session
|
||||
WHERE session.user_id = candidate.id
|
||||
) = (
|
||||
SELECT count(*) FROM locked_session
|
||||
WHERE locked_session.user_id = candidate.id
|
||||
)
|
||||
)
|
||||
|
||||
DELETE FROM users
|
||||
USING deletable
|
||||
WHERE users.id = deletable.id
|
||||
`
|
||||
|
||||
type DeleteUnverifiedUsersRegisteredBeforeParams struct {
|
||||
Cutoff pgtype.Timestamptz
|
||||
BatchLimit int32
|
||||
}
|
||||
|
||||
// Deletes one batch of accounts that stayed unverified since before cutoff,
|
||||
// oldest first, with their tokens and sessions. Every lock is taken with SKIP
|
||||
// LOCKED, so the statement never waits: an account whose row is locked, for
|
||||
// example by a re-registration or a token insert, is skipped, and so is an
|
||||
// account with any token or session row locked, for example by a
|
||||
// confirmation that consumed a token. Skipped accounts stay for the next run.
|
||||
// Taking the account lock before the token locks is the reverse of the
|
||||
// documented order, which is safe only because no lock here waits.
|
||||
// An account qualifies only when every token and session row visible to the
|
||||
// statement was locked above.
|
||||
func (q *Queries) DeleteUnverifiedUsersRegisteredBefore(ctx context.Context, arg DeleteUnverifiedUsersRegisteredBeforeParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, deleteUnverifiedUsersRegisteredBefore, arg.Cutoff, arg.BatchLimit)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const getActiveSessionByTokenHash = `-- name: GetActiveSessionByTokenHash :one
|
||||
SELECT
|
||||
id,
|
||||
user_id,
|
||||
token_hash,
|
||||
created_at,
|
||||
last_seen_at,
|
||||
expires_at,
|
||||
revoked_at
|
||||
FROM sessions
|
||||
WHERE
|
||||
token_hash = $1
|
||||
AND revoked_at IS NULL
|
||||
AND expires_at > $2
|
||||
AND last_seen_at > $3
|
||||
`
|
||||
|
||||
type GetActiveSessionByTokenHashParams struct {
|
||||
TokenHash []byte
|
||||
At pgtype.Timestamptz
|
||||
IdleCutoff pgtype.Timestamptz
|
||||
}
|
||||
|
||||
func (q *Queries) GetActiveSessionByTokenHash(ctx context.Context, arg GetActiveSessionByTokenHashParams) (Session, error) {
|
||||
row := q.db.QueryRow(ctx, getActiveSessionByTokenHash, arg.TokenHash, arg.At, arg.IdleCutoff)
|
||||
var i Session
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.UserID,
|
||||
&i.TokenHash,
|
||||
&i.CreatedAt,
|
||||
&i.LastSeenAt,
|
||||
&i.ExpiresAt,
|
||||
&i.RevokedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getEmailTokenState = `-- name: GetEmailTokenState :one
|
||||
SELECT
|
||||
token.consumed_at,
|
||||
token.invalidated_at,
|
||||
token.expires_at,
|
||||
owner.registration_version = token.registration_version AS current_registration
|
||||
FROM email_tokens AS token
|
||||
INNER JOIN users AS owner ON token.user_id = owner.id
|
||||
WHERE
|
||||
token.token_hash = $1
|
||||
AND token.purpose = $2
|
||||
`
|
||||
|
||||
type GetEmailTokenStateParams struct {
|
||||
TokenHash []byte
|
||||
Purpose string
|
||||
}
|
||||
|
||||
type GetEmailTokenStateRow struct {
|
||||
ConsumedAt pgtype.Timestamptz
|
||||
InvalidatedAt pgtype.Timestamptz
|
||||
ExpiresAt pgtype.Timestamptz
|
||||
CurrentRegistration bool
|
||||
}
|
||||
|
||||
// Explains why ConsumeEmailToken matched no row.
|
||||
func (q *Queries) GetEmailTokenState(ctx context.Context, arg GetEmailTokenStateParams) (GetEmailTokenStateRow, error) {
|
||||
row := q.db.QueryRow(ctx, getEmailTokenState, arg.TokenHash, arg.Purpose)
|
||||
var i GetEmailTokenStateRow
|
||||
err := row.Scan(
|
||||
&i.ConsumedAt,
|
||||
&i.InvalidatedAt,
|
||||
&i.ExpiresAt,
|
||||
&i.CurrentRegistration,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getUserByEmailNormalized = `-- name: GetUserByEmailNormalized :one
|
||||
SELECT
|
||||
id,
|
||||
email,
|
||||
email_normalized,
|
||||
password_hash,
|
||||
scenario,
|
||||
onboarding_step,
|
||||
email_verified_at,
|
||||
registration_version,
|
||||
last_registered_at,
|
||||
version,
|
||||
created_at,
|
||||
updated_at
|
||||
FROM users
|
||||
WHERE email_normalized = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetUserByEmailNormalized(ctx context.Context, emailNormalized string) (User, error) {
|
||||
row := q.db.QueryRow(ctx, getUserByEmailNormalized, emailNormalized)
|
||||
var i User
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Email,
|
||||
&i.EmailNormalized,
|
||||
&i.PasswordHash,
|
||||
&i.Scenario,
|
||||
&i.OnboardingStep,
|
||||
&i.EmailVerifiedAt,
|
||||
&i.RegistrationVersion,
|
||||
&i.LastRegisteredAt,
|
||||
&i.Version,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getUserByID = `-- name: GetUserByID :one
|
||||
SELECT
|
||||
id,
|
||||
email,
|
||||
email_normalized,
|
||||
password_hash,
|
||||
scenario,
|
||||
onboarding_step,
|
||||
email_verified_at,
|
||||
registration_version,
|
||||
last_registered_at,
|
||||
version,
|
||||
created_at,
|
||||
updated_at
|
||||
FROM users
|
||||
WHERE id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetUserByID(ctx context.Context, id pgtype.UUID) (User, error) {
|
||||
row := q.db.QueryRow(ctx, getUserByID, id)
|
||||
var i User
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Email,
|
||||
&i.EmailNormalized,
|
||||
&i.PasswordHash,
|
||||
&i.Scenario,
|
||||
&i.OnboardingStep,
|
||||
&i.EmailVerifiedAt,
|
||||
&i.RegistrationVersion,
|
||||
&i.LastRegisteredAt,
|
||||
&i.Version,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertEmailToken = `-- name: InsertEmailToken :exec
|
||||
INSERT INTO email_tokens (
|
||||
id,
|
||||
user_id,
|
||||
purpose,
|
||||
token_hash,
|
||||
registration_version,
|
||||
created_at,
|
||||
expires_at
|
||||
) VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4,
|
||||
$5,
|
||||
$6,
|
||||
$7
|
||||
)
|
||||
`
|
||||
|
||||
type InsertEmailTokenParams struct {
|
||||
ID pgtype.UUID
|
||||
UserID pgtype.UUID
|
||||
Purpose string
|
||||
TokenHash []byte
|
||||
RegistrationVersion int64
|
||||
CreatedAt pgtype.Timestamptz
|
||||
ExpiresAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
func (q *Queries) InsertEmailToken(ctx context.Context, arg InsertEmailTokenParams) error {
|
||||
_, err := q.db.Exec(ctx, insertEmailToken,
|
||||
arg.ID,
|
||||
arg.UserID,
|
||||
arg.Purpose,
|
||||
arg.TokenHash,
|
||||
arg.RegistrationVersion,
|
||||
arg.CreatedAt,
|
||||
arg.ExpiresAt,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const insertSession = `-- name: InsertSession :exec
|
||||
INSERT INTO sessions (
|
||||
id,
|
||||
user_id,
|
||||
token_hash,
|
||||
created_at,
|
||||
last_seen_at,
|
||||
expires_at
|
||||
) VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4,
|
||||
$5,
|
||||
$6
|
||||
)
|
||||
`
|
||||
|
||||
type InsertSessionParams struct {
|
||||
ID pgtype.UUID
|
||||
UserID pgtype.UUID
|
||||
TokenHash []byte
|
||||
CreatedAt pgtype.Timestamptz
|
||||
LastSeenAt pgtype.Timestamptz
|
||||
ExpiresAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
func (q *Queries) InsertSession(ctx context.Context, arg InsertSessionParams) error {
|
||||
_, err := q.db.Exec(ctx, insertSession,
|
||||
arg.ID,
|
||||
arg.UserID,
|
||||
arg.TokenHash,
|
||||
arg.CreatedAt,
|
||||
arg.LastSeenAt,
|
||||
arg.ExpiresAt,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const insertUser = `-- name: InsertUser :exec
|
||||
INSERT INTO users (
|
||||
id,
|
||||
email,
|
||||
email_normalized,
|
||||
password_hash,
|
||||
scenario,
|
||||
onboarding_step,
|
||||
email_verified_at,
|
||||
registration_version,
|
||||
last_registered_at,
|
||||
version,
|
||||
created_at,
|
||||
updated_at
|
||||
) VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4,
|
||||
$5,
|
||||
$6,
|
||||
$7,
|
||||
$8,
|
||||
$9,
|
||||
$10,
|
||||
$11,
|
||||
$12
|
||||
)
|
||||
`
|
||||
|
||||
type InsertUserParams struct {
|
||||
ID pgtype.UUID
|
||||
Email string
|
||||
EmailNormalized string
|
||||
PasswordHash string
|
||||
Scenario string
|
||||
OnboardingStep string
|
||||
EmailVerifiedAt pgtype.Timestamptz
|
||||
RegistrationVersion int64
|
||||
LastRegisteredAt pgtype.Timestamptz
|
||||
Version int64
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
func (q *Queries) InsertUser(ctx context.Context, arg InsertUserParams) error {
|
||||
_, err := q.db.Exec(ctx, insertUser,
|
||||
arg.ID,
|
||||
arg.Email,
|
||||
arg.EmailNormalized,
|
||||
arg.PasswordHash,
|
||||
arg.Scenario,
|
||||
arg.OnboardingStep,
|
||||
arg.EmailVerifiedAt,
|
||||
arg.RegistrationVersion,
|
||||
arg.LastRegisteredAt,
|
||||
arg.Version,
|
||||
arg.CreatedAt,
|
||||
arg.UpdatedAt,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const invalidateActiveEmailTokens = `-- name: InvalidateActiveEmailTokens :execrows
|
||||
UPDATE email_tokens
|
||||
SET invalidated_at = $1
|
||||
WHERE
|
||||
user_id = $2
|
||||
AND purpose = $3
|
||||
AND consumed_at IS NULL
|
||||
AND invalidated_at IS NULL
|
||||
`
|
||||
|
||||
type InvalidateActiveEmailTokensParams struct {
|
||||
InvalidatedAt pgtype.Timestamptz
|
||||
UserID pgtype.UUID
|
||||
Purpose string
|
||||
}
|
||||
|
||||
func (q *Queries) InvalidateActiveEmailTokens(ctx context.Context, arg InvalidateActiveEmailTokensParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, invalidateActiveEmailTokens, arg.InvalidatedAt, arg.UserID, arg.Purpose)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const markUserEmailVerified = `-- name: MarkUserEmailVerified :one
|
||||
UPDATE users
|
||||
SET
|
||||
email_verified_at = $1,
|
||||
updated_at = $1,
|
||||
version = version + 1
|
||||
WHERE
|
||||
id = $2
|
||||
AND registration_version = $3
|
||||
AND email_verified_at IS NULL
|
||||
RETURNING
|
||||
id,
|
||||
email,
|
||||
email_normalized,
|
||||
password_hash,
|
||||
scenario,
|
||||
onboarding_step,
|
||||
email_verified_at,
|
||||
registration_version,
|
||||
last_registered_at,
|
||||
version,
|
||||
created_at,
|
||||
updated_at
|
||||
`
|
||||
|
||||
type MarkUserEmailVerifiedParams struct {
|
||||
VerifiedAt pgtype.Timestamptz
|
||||
ID pgtype.UUID
|
||||
RegistrationVersion int64
|
||||
}
|
||||
|
||||
// Verifies the email only for the registration version the consumed token
|
||||
// was issued for.
|
||||
func (q *Queries) MarkUserEmailVerified(ctx context.Context, arg MarkUserEmailVerifiedParams) (User, error) {
|
||||
row := q.db.QueryRow(ctx, markUserEmailVerified, arg.VerifiedAt, arg.ID, arg.RegistrationVersion)
|
||||
var i User
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Email,
|
||||
&i.EmailNormalized,
|
||||
&i.PasswordHash,
|
||||
&i.Scenario,
|
||||
&i.OnboardingStep,
|
||||
&i.EmailVerifiedAt,
|
||||
&i.RegistrationVersion,
|
||||
&i.LastRegisteredAt,
|
||||
&i.Version,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const revokeSession = `-- name: RevokeSession :execrows
|
||||
UPDATE sessions
|
||||
SET revoked_at = $1
|
||||
WHERE
|
||||
id = $2
|
||||
AND revoked_at IS NULL
|
||||
`
|
||||
|
||||
type RevokeSessionParams struct {
|
||||
RevokedAt pgtype.Timestamptz
|
||||
ID pgtype.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) RevokeSession(ctx context.Context, arg RevokeSessionParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, revokeSession, arg.RevokedAt, arg.ID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const revokeUserSessions = `-- name: RevokeUserSessions :execrows
|
||||
UPDATE sessions
|
||||
SET revoked_at = $1
|
||||
WHERE
|
||||
user_id = $2
|
||||
AND revoked_at IS NULL
|
||||
`
|
||||
|
||||
type RevokeUserSessionsParams struct {
|
||||
RevokedAt pgtype.Timestamptz
|
||||
UserID pgtype.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) RevokeUserSessions(ctx context.Context, arg RevokeUserSessionsParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, revokeUserSessions, arg.RevokedAt, arg.UserID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const touchSession = `-- name: TouchSession :one
|
||||
WITH active_session AS (
|
||||
SELECT candidate.id
|
||||
FROM sessions AS candidate
|
||||
WHERE
|
||||
candidate.id = $1
|
||||
AND candidate.revoked_at IS NULL
|
||||
AND candidate.expires_at > $2
|
||||
AND candidate.last_seen_at > $3
|
||||
),
|
||||
|
||||
touched AS (
|
||||
UPDATE sessions
|
||||
SET last_seen_at = $2
|
||||
WHERE
|
||||
sessions.id = $1
|
||||
AND sessions.revoked_at IS NULL
|
||||
AND sessions.expires_at > $2
|
||||
AND sessions.last_seen_at > $3
|
||||
AND sessions.last_seen_at < $4
|
||||
RETURNING sessions.id
|
||||
)
|
||||
|
||||
SELECT
|
||||
exists(SELECT 1 FROM active_session) AS active,
|
||||
exists(SELECT 1 FROM touched) AS touched
|
||||
`
|
||||
|
||||
type TouchSessionParams struct {
|
||||
ID pgtype.UUID
|
||||
At pgtype.Timestamptz
|
||||
IdleCutoff pgtype.Timestamptz
|
||||
TouchCutoff pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type TouchSessionRow struct {
|
||||
Active bool
|
||||
Touched bool
|
||||
}
|
||||
|
||||
// Records activity on an active session and reports whether it is active.
|
||||
// The row is written only when last_seen_at is older than touch_cutoff, so
|
||||
// frequent requests do not rewrite it. last_seen_at never moves back, and a
|
||||
// revoked, expired, or idle session is not revived; the update re-checks
|
||||
// those conditions against a concurrent change.
|
||||
func (q *Queries) TouchSession(ctx context.Context, arg TouchSessionParams) (TouchSessionRow, error) {
|
||||
row := q.db.QueryRow(ctx, touchSession,
|
||||
arg.ID,
|
||||
arg.At,
|
||||
arg.IdleCutoff,
|
||||
arg.TouchCutoff,
|
||||
)
|
||||
var i TouchSessionRow
|
||||
err := row.Scan(&i.Active, &i.Touched)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const updateUserRegistration = `-- name: UpdateUserRegistration :one
|
||||
UPDATE users
|
||||
SET
|
||||
email = $1,
|
||||
password_hash = $2,
|
||||
scenario = $3,
|
||||
onboarding_step = $4,
|
||||
registration_version = registration_version + 1,
|
||||
last_registered_at = $5,
|
||||
updated_at = $6,
|
||||
version = version + 1
|
||||
WHERE
|
||||
id = $7
|
||||
AND version = $8
|
||||
AND email_verified_at IS NULL
|
||||
RETURNING
|
||||
id,
|
||||
email,
|
||||
email_normalized,
|
||||
password_hash,
|
||||
scenario,
|
||||
onboarding_step,
|
||||
email_verified_at,
|
||||
registration_version,
|
||||
last_registered_at,
|
||||
version,
|
||||
created_at,
|
||||
updated_at
|
||||
`
|
||||
|
||||
type UpdateUserRegistrationParams struct {
|
||||
Email string
|
||||
PasswordHash string
|
||||
Scenario string
|
||||
OnboardingStep string
|
||||
LastRegisteredAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
ID pgtype.UUID
|
||||
ExpectedVersion int64
|
||||
}
|
||||
|
||||
// Replaces the registration of an unverified account and advances the
|
||||
// registration version in the same statement, so no caller can choose it.
|
||||
// The version check rejects a writer that read an older row; a verified
|
||||
// account never changes.
|
||||
func (q *Queries) UpdateUserRegistration(ctx context.Context, arg UpdateUserRegistrationParams) (User, error) {
|
||||
row := q.db.QueryRow(ctx, updateUserRegistration,
|
||||
arg.Email,
|
||||
arg.PasswordHash,
|
||||
arg.Scenario,
|
||||
arg.OnboardingStep,
|
||||
arg.LastRegisteredAt,
|
||||
arg.UpdatedAt,
|
||||
arg.ID,
|
||||
arg.ExpectedVersion,
|
||||
)
|
||||
var i User
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Email,
|
||||
&i.EmailNormalized,
|
||||
&i.PasswordHash,
|
||||
&i.Scenario,
|
||||
&i.OnboardingStep,
|
||||
&i.EmailVerifiedAt,
|
||||
&i.RegistrationVersion,
|
||||
&i.LastRegisteredAt,
|
||||
&i.Version,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -8,6 +8,18 @@ import (
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
type EmailToken struct {
|
||||
ID pgtype.UUID
|
||||
UserID pgtype.UUID
|
||||
Purpose string
|
||||
TokenHash []byte
|
||||
RegistrationVersion int64
|
||||
CreatedAt pgtype.Timestamptz
|
||||
ExpiresAt pgtype.Timestamptz
|
||||
ConsumedAt pgtype.Timestamptz
|
||||
InvalidatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type OutboxEvent struct {
|
||||
Position pgtype.Int8
|
||||
EventID pgtype.UUID
|
||||
@@ -20,3 +32,28 @@ type OutboxEvent struct {
|
||||
OccurredAt pgtype.Timestamptz
|
||||
PublishedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
ID pgtype.UUID
|
||||
UserID pgtype.UUID
|
||||
TokenHash []byte
|
||||
CreatedAt pgtype.Timestamptz
|
||||
LastSeenAt pgtype.Timestamptz
|
||||
ExpiresAt pgtype.Timestamptz
|
||||
RevokedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type User struct {
|
||||
ID pgtype.UUID
|
||||
Email string
|
||||
EmailNormalized string
|
||||
PasswordHash string
|
||||
Scenario string
|
||||
OnboardingStep string
|
||||
EmailVerifiedAt pgtype.Timestamptz
|
||||
RegistrationVersion int64
|
||||
LastRegisteredAt pgtype.Timestamptz
|
||||
Version int64
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
}
|
||||
@@ -6,11 +6,59 @@ package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
type Querier interface {
|
||||
// Consumes a token in one statement. Concurrent callers queue on the token
|
||||
// row lock; under READ COMMITTED each waiter re-checks the WHERE clause
|
||||
// against the committed row, so exactly one of them updates it. The join
|
||||
// compares the registration version with the account row as the statement
|
||||
// reads it, without locking that row, so it rejects a token from an earlier
|
||||
// registration that already committed but not one that commits afterwards.
|
||||
// The confirmation guarantee therefore needs MarkUserEmailVerified with the
|
||||
// returned registration version in the same transaction, rolled back when it
|
||||
// matches no row.
|
||||
ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (EmailToken, error)
|
||||
// Deletes one batch of accounts that stayed unverified since before cutoff,
|
||||
// oldest first, with their tokens and sessions. Every lock is taken with SKIP
|
||||
// LOCKED, so the statement never waits: an account whose row is locked, for
|
||||
// example by a re-registration or a token insert, is skipped, and so is an
|
||||
// account with any token or session row locked, for example by a
|
||||
// confirmation that consumed a token. Skipped accounts stay for the next run.
|
||||
// Taking the account lock before the token locks is the reverse of the
|
||||
// documented order, which is safe only because no lock here waits.
|
||||
// An account qualifies only when every token and session row visible to the
|
||||
// statement was locked above.
|
||||
DeleteUnverifiedUsersRegisteredBefore(ctx context.Context, arg DeleteUnverifiedUsersRegisteredBeforeParams) (int64, error)
|
||||
GetActiveSessionByTokenHash(ctx context.Context, arg GetActiveSessionByTokenHashParams) (Session, error)
|
||||
// Explains why ConsumeEmailToken matched no row.
|
||||
GetEmailTokenState(ctx context.Context, arg GetEmailTokenStateParams) (GetEmailTokenStateRow, error)
|
||||
GetUserByEmailNormalized(ctx context.Context, emailNormalized string) (User, error)
|
||||
GetUserByID(ctx context.Context, id pgtype.UUID) (User, error)
|
||||
InsertEmailToken(ctx context.Context, arg InsertEmailTokenParams) error
|
||||
InsertOutboxEvent(ctx context.Context, arg InsertOutboxEventParams) error
|
||||
InsertSession(ctx context.Context, arg InsertSessionParams) error
|
||||
InsertUser(ctx context.Context, arg InsertUserParams) error
|
||||
InvalidateActiveEmailTokens(ctx context.Context, arg InvalidateActiveEmailTokensParams) (int64, error)
|
||||
// Verifies the email only for the registration version the consumed token
|
||||
// was issued for.
|
||||
MarkUserEmailVerified(ctx context.Context, arg MarkUserEmailVerifiedParams) (User, error)
|
||||
Ping(ctx context.Context) (int32, error)
|
||||
RevokeSession(ctx context.Context, arg RevokeSessionParams) (int64, error)
|
||||
RevokeUserSessions(ctx context.Context, arg RevokeUserSessionsParams) (int64, error)
|
||||
// Records activity on an active session and reports whether it is active.
|
||||
// The row is written only when last_seen_at is older than touch_cutoff, so
|
||||
// frequent requests do not rewrite it. last_seen_at never moves back, and a
|
||||
// revoked, expired, or idle session is not revived; the update re-checks
|
||||
// those conditions against a concurrent change.
|
||||
TouchSession(ctx context.Context, arg TouchSessionParams) (TouchSessionRow, error)
|
||||
// Replaces the registration of an unverified account and advances the
|
||||
// registration version in the same statement, so no caller can choose it.
|
||||
// The version check rejects a writer that read an older row; a verified
|
||||
// account never changes.
|
||||
UpdateUserRegistration(ctx context.Context, arg UpdateUserRegistrationParams) (User, error)
|
||||
}
|
||||
|
||||
var _ Querier = (*Queries)(nil)
|
||||
@@ -66,6 +66,7 @@ func (transactor *Transactor) WithinTransaction(
|
||||
fnErr := fn(context.WithValue(ctx, transactionContextKey{}, true), &UnitOfWork{tx: tx, queries: sqlc.New(tx)})
|
||||
finished = true
|
||||
if fnErr != nil {
|
||||
fnErr = markTransactionConflict(fnErr)
|
||||
if rollbackErr := rollback(ctx, tx); rollbackErr != nil {
|
||||
return errors.Join(fnErr, fmt.Errorf("Transactor.WithinTransaction - roll back transaction: %w", rollbackErr))
|
||||
}
|
||||
@@ -75,7 +76,7 @@ func (transactor *Transactor) WithinTransaction(
|
||||
// pgx reports pgx.ErrTxCommitRollback when fn ignored a statement error
|
||||
// and PostgreSQL rolled the aborted transaction back instead. After a
|
||||
// network error the commit outcome is unknown; see outbound.Transactor.
|
||||
return fmt.Errorf("Transactor.WithinTransaction - commit transaction: %w", err)
|
||||
return fmt.Errorf("Transactor.WithinTransaction - commit transaction: %w", markTransactionConflict(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user