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,165 @@
|
||||
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 and sessions; 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.
|
||||
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 and sessions, and returns how many it deleted. It never
|
||||
// waits for a lock: an account whose row, token, or session is locked by
|
||||
// another transaction is skipped and stays for the next run. 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)
|
||||
}
|
||||
@@ -17,13 +17,22 @@ var (
|
||||
// transaction callback. Nested calls would silently use a second connection
|
||||
// and commit independently of the outer transaction.
|
||||
ErrNestedTransaction = errors.New("transaction already in progress")
|
||||
|
||||
// ErrTransactionConflict reports that PostgreSQL aborted the work with a
|
||||
// deadlock (SQLSTATE 40P01) or a serialization failure (40001). Nothing
|
||||
// was committed. The caller may retry the whole operation, ideally with a
|
||||
// short backoff and a bounded number of attempts; a usecase or job that
|
||||
// retries must stay idempotent.
|
||||
ErrTransactionConflict = errors.New("transaction conflict")
|
||||
)
|
||||
|
||||
// Transactor runs a business operation in one database transaction.
|
||||
type Transactor interface {
|
||||
// WithinTransaction commits when fn returns nil and rolls back when fn
|
||||
// returns an error or panics. The error is returned unchanged in identity
|
||||
// and a panic is re-raised after the rollback. fn must use only the
|
||||
// returns an error or panics. The error keeps its identity for errors.Is
|
||||
// and errors.As; a deadlock or serialization failure, from fn or from the
|
||||
// commit, additionally matches ErrTransactionConflict. A panic is
|
||||
// re-raised after the rollback. fn must use only the
|
||||
// UnitOfWork and context it receives and must not retain them after
|
||||
// returning. Calling WithinTransaction with that context returns
|
||||
// ErrNestedTransaction. After a database error inside fn the transaction is
|
||||
@@ -39,6 +48,7 @@ type Transactor interface {
|
||||
// UnitOfWork exposes repositories bound to one transaction. Product
|
||||
// repositories are added here as their usecases appear.
|
||||
type UnitOfWork interface {
|
||||
IdentityRepositories
|
||||
Outbox() OutboxWriter
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user