177 lines
8.7 KiB
Go
177 lines
8.7 KiB
Go
package outbound
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"lincodex/backend/internal/domain"
|
|
)
|
|
|
|
var (
|
|
// ErrUserNotFound reports that no account matches, including an insert
|
|
// that references an account deleted in the meantime.
|
|
ErrUserNotFound = errors.New("user not found")
|
|
|
|
// ErrEmailTaken reports that another account already has the same
|
|
// normalized email.
|
|
ErrEmailTaken = errors.New("email already registered")
|
|
|
|
// ErrUserVersionConflict reports that a conditional account update matched
|
|
// no row: the expected version is stale, the email is already verified,
|
|
// or the registration version has moved on. Read the account again.
|
|
ErrUserVersionConflict = errors.New("user changed concurrently")
|
|
|
|
// ErrTokenHashConflict reports a second token or session with the same
|
|
// hash. With 256-bit random tokens it signals a broken generator, not a
|
|
// retryable condition.
|
|
ErrTokenHashConflict = errors.New("token hash already stored")
|
|
|
|
// ErrEmailTokenNotFound reports that no token of the purpose has the hash.
|
|
ErrEmailTokenNotFound = errors.New("email token not found")
|
|
|
|
// ErrEmailTokenConsumed reports a token that was already consumed.
|
|
ErrEmailTokenConsumed = errors.New("email token already consumed")
|
|
|
|
// ErrEmailTokenInvalidated reports a token replaced by a later resend or
|
|
// re-registration, or issued for an earlier registration version.
|
|
ErrEmailTokenInvalidated = errors.New("email token invalidated")
|
|
|
|
// ErrEmailTokenExpired reports a token past its lifetime that was neither
|
|
// consumed nor invalidated.
|
|
ErrEmailTokenExpired = errors.New("email token expired")
|
|
|
|
// ErrSessionNotFound reports a session that does not exist, is revoked,
|
|
// is past its absolute deadline, or is idle longer than the timeout.
|
|
ErrSessionNotFound = errors.New("session not found")
|
|
)
|
|
|
|
// IdentityRepositories exposes the identity repositories. UnitOfWork binds
|
|
// them to one transaction; an adapter may also provide them outside a
|
|
// transaction, where every call is its own statement. Every method that takes
|
|
// a time rejects the zero time.
|
|
//
|
|
// Lock order: an operation that changes both an account and its email tokens
|
|
// locks the tokens first and the account second, as Consume and
|
|
// MarkEmailVerified do in a confirmation. A re-registration or a resend
|
|
// therefore calls InvalidateActive before UpdateRegistration or Insert; the
|
|
// opposite order can deadlock against a concurrent confirmation. The only
|
|
// exception is DeleteUnverifiedRegisteredBefore, which locks the account
|
|
// before its tokens, sessions, and deliveries; it is safe because every lock it takes uses
|
|
// SKIP LOCKED and never waits. A deadlock that still happens, for example
|
|
// between callers that ignore this order, aborts one transaction with
|
|
// ErrTransactionConflict, and the caller may retry it.
|
|
type IdentityRepositories interface {
|
|
Users() UserRepository
|
|
EmailTokens() EmailTokenRepository
|
|
Sessions() SessionRepository
|
|
}
|
|
|
|
// UserRepository stores accounts. Lookups by email use the normalized form.
|
|
type UserRepository interface {
|
|
// Create returns an error wrapping ErrEmailTaken when the normalized email
|
|
// already belongs to an account.
|
|
Create(ctx context.Context, user domain.User) error
|
|
|
|
// GetByID returns ErrUserNotFound when no account has the ID.
|
|
GetByID(ctx context.Context, id uuid.UUID) (domain.User, error)
|
|
|
|
// GetByEmail returns ErrUserNotFound when no account has the normalized
|
|
// email.
|
|
GetByEmail(ctx context.Context, email domain.EmailAddress) (domain.User, error)
|
|
|
|
// UpdateRegistration stores user as returned by domain.User.ReRegister.
|
|
// It applies only when the stored version still equals user.Version and
|
|
// the email is unverified. The same statement advances Version and
|
|
// RegistrationVersion by one, so callers never choose the registration
|
|
// version; the returned account carries the new values. Otherwise it
|
|
// returns ErrUserVersionConflict.
|
|
//
|
|
// The same statement deletes the C1 records with the source
|
|
// registration that the earlier registration of this account stored,
|
|
// because the earlier registrant's consent must never stand for the new
|
|
// one. The registration usecase (TASK-053) must record the new C1 with
|
|
// ConsentLedger().Grant in the same transaction; a version conflict
|
|
// deletes nothing.
|
|
UpdateRegistration(ctx context.Context, user domain.User) (domain.User, error)
|
|
|
|
// MarkEmailVerified sets the verification time when the account is still
|
|
// unverified and still has registrationVersion, and returns the stored
|
|
// account. Otherwise it returns ErrUserVersionConflict. A confirmation
|
|
// calls it after EmailTokenRepository.Consume in the same transaction; see
|
|
// Consume.
|
|
MarkEmailVerified(ctx context.Context, id uuid.UUID, registrationVersion int64, at time.Time) (domain.User, error)
|
|
|
|
// DeleteUnverifiedRegisteredBefore deletes at most limit accounts that are
|
|
// unverified and were last registered before cutoff, oldest first, with
|
|
// their tokens, sessions, mail deliveries, and consent records, and
|
|
// returns how many it deleted. It never waits for a lock: an account
|
|
// whose row, token, session, delivery, or consent record is locked by
|
|
// another transaction is skipped and stays for the next run. A consent
|
|
// recorded for a candidate account after the statement started fails the
|
|
// restricting foreign key; the run then returns an error matching
|
|
// ErrTransactionConflict, deletes nothing, and may be repeated. A cleanup
|
|
// job repeats it until the result is below limit and runs again later.
|
|
DeleteUnverifiedRegisteredBefore(ctx context.Context, cutoff time.Time, limit int32) (int64, error)
|
|
}
|
|
|
|
// EmailTokenRepository stores email token hashes. It never receives a raw
|
|
// token.
|
|
type EmailTokenRepository interface {
|
|
// Insert returns ErrUserNotFound when the account does not exist and
|
|
// ErrTokenHashConflict for a duplicate hash.
|
|
Insert(ctx context.Context, token domain.EmailToken) error
|
|
|
|
// InvalidateActive marks every unconsumed, not yet invalidated token of
|
|
// the user and purpose as invalidated at the given time, and returns how
|
|
// many it marked.
|
|
InvalidateActive(ctx context.Context, userID uuid.UUID, purpose domain.EmailTokenPurpose, at time.Time) (int64, error)
|
|
|
|
// Consume atomically marks the token consumed at the given time and
|
|
// returns it. Of concurrent calls with the same hash exactly one succeeds;
|
|
// the others wait for its transaction and then fail. It fails with
|
|
// ErrEmailTokenNotFound, ErrEmailTokenConsumed, ErrEmailTokenInvalidated,
|
|
// or ErrEmailTokenExpired, in that order of precedence.
|
|
//
|
|
// Consume compares the token's registration version with the account only
|
|
// as its statement reads the account, without locking it, so a
|
|
// re-registration that commits right after it is not detected. Binding the
|
|
// token to the current registration therefore requires a confirmation to
|
|
// call Users().MarkEmailVerified(token.UserID, token.RegistrationVersion)
|
|
// in the same transaction and to roll back when it returns
|
|
// ErrUserVersionConflict; the rollback also restores the token. The
|
|
// confirmation usecase maps that outcome to verification_token_invalid.
|
|
Consume(ctx context.Context, hash domain.SecretTokenHash, purpose domain.EmailTokenPurpose, at time.Time) (domain.EmailToken, error)
|
|
}
|
|
|
|
// SessionRepository stores server-side sessions by the hash of their token.
|
|
type SessionRepository interface {
|
|
// Create returns ErrUserNotFound when the account does not exist and
|
|
// ErrTokenHashConflict for a duplicate hash.
|
|
Create(ctx context.Context, session domain.Session) error
|
|
|
|
// FindActive returns the session with the hash when it is not revoked,
|
|
// its absolute deadline is after at, and it was last seen less than
|
|
// idleTimeout before at. Otherwise it returns ErrSessionNotFound.
|
|
FindActive(ctx context.Context, hash domain.SecretTokenHash, at time.Time, idleTimeout time.Duration) (domain.Session, error)
|
|
|
|
// Touch records activity at the given time on a session that is still
|
|
// active by the same rules as FindActive and returns ErrSessionNotFound
|
|
// when it is not. To avoid a write on every request, the adapter stores
|
|
// the new time only when the stored last_seen_at is at least a short
|
|
// interval older (one minute in PostgreSQL), so the idle timeout can end
|
|
// a session up to that interval early. last_seen_at never moves back.
|
|
Touch(ctx context.Context, id uuid.UUID, at time.Time, idleTimeout time.Duration) error
|
|
|
|
// Revoke revokes the session at the given time. It returns
|
|
// ErrSessionNotFound when the session does not exist or is already
|
|
// revoked.
|
|
Revoke(ctx context.Context, id uuid.UUID, at time.Time) error
|
|
|
|
// RevokeAllForUser revokes every unrevoked session of the user and returns
|
|
// how many it revoked.
|
|
RevokeAllForUser(ctx context.Context, userID uuid.UUID, at time.Time) (int64, error)
|
|
}
|