feat(identity): store users, email tokens, and sessions

This commit is contained in:
shira committed 2026-10-06 00:15:22 +03:00
1 parent 15e2e50561
commit e7d0d92ef9
30 files changed
+4792 -32

No files matched your search

@@ -0,0 +1,167 @@
-- +goose Up
-- Identity storage: accounts, one-time email tokens, and server-side sessions.
-- Passwords, raw email tokens, and raw session tokens are never stored; only
-- an Argon2id PHC string and SHA-256 digests are. Every timestamp comes from
-- the application clock, so expiry checks and the stored deadlines use one
-- clock. Enum-like columns are text with CHECK constraints rather than
-- PostgreSQL enum types: a new value then changes one constraint in a later
-- migration, which can also be rolled back, while an enum value cannot be
-- removed and cannot be used in the transaction that adds it.
CREATE TABLE users (
-- UUIDv7 generated in Go.
id uuid NOT NULL,
-- Delivery form: trimmed ASCII, letter case as typed.
email text NOT NULL,
-- Comparison key computed in Go: the delivery form with A-Z lowercased.
email_normalized text NOT NULL,
-- Argon2id PHC string; never the password.
password_hash text NOT NULL,
scenario text NOT NULL,
onboarding_step text NOT NULL,
email_verified_at timestamptz,
-- Advanced on every registration of the unverified email. Email tokens
-- are bound to the version they were issued for.
registration_version bigint NOT NULL,
-- Time of the latest registration; the planned cleanup of unverified
-- accounts counts its deadline from here.
last_registered_at timestamptz NOT NULL,
-- Optimistic concurrency version, advanced on every update.
version bigint NOT NULL,
created_at timestamptz NOT NULL,
updated_at timestamptz NOT NULL,
CONSTRAINT users_pkey PRIMARY KEY (id),
CONSTRAINT users_email_normalized_key UNIQUE (email_normalized),
-- Addresses are ASCII until the mailer supports SMTPUTF8: one byte per
-- character in the UTF-8 database encoding.
CONSTRAINT users_email_ascii CHECK (
char_length(email) BETWEEN 3 AND 254
AND octet_length(email) = char_length(email)
),
-- translate() maps A-Z by code point, independent of the collation,
-- unlike lower().
CONSTRAINT users_email_normalized_rule CHECK (
email_normalized = translate(
email,
'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'abcdefghijklmnopqrstuvwxyz'
)
),
CONSTRAINT users_password_hash_format CHECK (
char_length(password_hash) <= 512
AND password_hash
~ '^\$argon2id\$v=19\$m=[0-9]+,t=[0-9]+,p=[0-9]+\$[A-Za-z0-9+/]+\$[A-Za-z0-9+/]+$'
),
CONSTRAINT users_scenario_onboarding_step CHECK (
(
scenario = 'candidate'
AND onboarding_step IN (
'candidate_consents',
'candidate_profile',
'candidate_questionnaire',
'candidate_assessment',
'completed'
)
)
OR (
scenario = 'employer'
AND onboarding_step IN ('employer_company', 'completed')
)
),
CONSTRAINT users_registration_version_positive CHECK (
registration_version > 0
),
CONSTRAINT users_version_positive CHECK (version > 0),
CONSTRAINT users_timestamps_after_creation CHECK (
updated_at >= created_at
AND last_registered_at >= created_at
AND (email_verified_at IS NULL OR email_verified_at >= created_at)
)
);
-- Supports the planned cleanup of accounts that stay unverified after their
-- latest registration. Verified accounts are not indexed.
CREATE INDEX users_unverified_last_registered_at_idx
ON users (last_registered_at)
WHERE email_verified_at IS NULL;
CREATE TABLE email_tokens (
-- UUIDv7 generated in Go.
id uuid NOT NULL,
user_id uuid NOT NULL,
purpose text NOT NULL,
-- SHA-256 of the raw token as 32 raw bytes: half the size of hex text,
-- with an exact length check and no letter-case or encoding variants.
token_hash bytea NOT NULL,
registration_version bigint NOT NULL,
created_at timestamptz NOT NULL,
expires_at timestamptz NOT NULL,
consumed_at timestamptz,
-- Set when a re-registration or a resend replaces the token.
invalidated_at timestamptz,
CONSTRAINT email_tokens_pkey PRIMARY KEY (id),
CONSTRAINT email_tokens_token_hash_key UNIQUE (token_hash),
CONSTRAINT email_tokens_user_id_fkey FOREIGN KEY (user_id)
REFERENCES users (id) ON DELETE CASCADE,
CONSTRAINT email_tokens_purpose_known CHECK (
purpose IN ('email_verification')
),
CONSTRAINT email_tokens_token_hash_sha256 CHECK (
octet_length(token_hash) = 32
),
CONSTRAINT email_tokens_registration_version_positive CHECK (
registration_version > 0
),
CONSTRAINT email_tokens_expiry_after_creation CHECK (
expires_at > created_at
),
-- A token ends at most once: either consumed or invalidated.
CONSTRAINT email_tokens_single_outcome CHECK (
consumed_at IS NULL OR invalidated_at IS NULL
),
CONSTRAINT email_tokens_outcome_after_creation CHECK (
(consumed_at IS NULL OR consumed_at >= created_at)
AND (invalidated_at IS NULL OR invalidated_at >= created_at)
)
);
-- Serves invalidation of a user's tokens for one purpose and the cascade
-- delete of a user's tokens.
CREATE INDEX email_tokens_user_id_purpose_idx
ON email_tokens (user_id, purpose);
CREATE TABLE sessions (
-- UUIDv7 generated in Go; internal only, never sent to the client.
id uuid NOT NULL,
user_id uuid NOT NULL,
-- SHA-256 of the raw session token that the cookie carries.
token_hash bytea NOT NULL,
created_at timestamptz NOT NULL,
-- The idle timeout counts from here.
last_seen_at timestamptz NOT NULL,
-- Absolute deadline fixed at creation.
expires_at timestamptz NOT NULL,
revoked_at timestamptz,
CONSTRAINT sessions_pkey PRIMARY KEY (id),
CONSTRAINT sessions_token_hash_key UNIQUE (token_hash),
CONSTRAINT sessions_user_id_fkey FOREIGN KEY (user_id)
REFERENCES users (id) ON DELETE CASCADE,
CONSTRAINT sessions_token_hash_sha256 CHECK (
octet_length(token_hash) = 32
),
CONSTRAINT sessions_expiry_after_creation CHECK (expires_at > created_at),
CONSTRAINT sessions_last_seen_after_creation CHECK (
last_seen_at >= created_at
),
CONSTRAINT sessions_revoked_after_creation CHECK (
revoked_at IS NULL OR revoked_at >= created_at
)
);
-- Serves revocation of all of a user's sessions and the cascade delete.
CREATE INDEX sessions_user_id_idx
ON sessions (user_id);
-- +goose Down
DROP TABLE sessions;
DROP TABLE email_tokens;
DROP TABLE users;
+333
View File
@@ -0,0 +1,333 @@
-- 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 (
sqlc.arg(id),
sqlc.arg(email),
sqlc.arg(email_normalized),
sqlc.arg(password_hash),
sqlc.arg(scenario),
sqlc.arg(onboarding_step),
sqlc.narg(email_verified_at),
sqlc.arg(registration_version),
sqlc.arg(last_registered_at),
sqlc.arg(version),
sqlc.arg(created_at),
sqlc.arg(updated_at)
);
-- 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 = sqlc.arg(id);
-- 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 = sqlc.arg(email_normalized);
-- 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.
-- name: UpdateUserRegistration :one
UPDATE users
SET
email = sqlc.arg(email),
password_hash = sqlc.arg(password_hash),
scenario = sqlc.arg(scenario),
onboarding_step = sqlc.arg(onboarding_step),
registration_version = registration_version + 1,
last_registered_at = sqlc.arg(last_registered_at),
updated_at = sqlc.arg(updated_at),
version = version + 1
WHERE
id = sqlc.arg(id)
AND version = sqlc.arg(expected_version)
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;
-- Verifies the email only for the registration version the consumed token
-- was issued for.
-- name: MarkUserEmailVerified :one
UPDATE users
SET
email_verified_at = sqlc.arg(verified_at),
updated_at = sqlc.arg(verified_at),
version = version + 1
WHERE
id = sqlc.arg(id)
AND registration_version = sqlc.arg(registration_version)
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;
-- 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.
-- 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 < sqlc.arg(cutoff)
ORDER BY stale.last_registered_at
LIMIT sqlc.arg(batch_limit)
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
),
-- An account qualifies only when every token and session row visible to the
-- statement was locked above.
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;
-- name: InsertEmailToken :exec
INSERT INTO email_tokens (
id,
user_id,
purpose,
token_hash,
registration_version,
created_at,
expires_at
) VALUES (
sqlc.arg(id),
sqlc.arg(user_id),
sqlc.arg(purpose),
sqlc.arg(token_hash),
sqlc.arg(registration_version),
sqlc.arg(created_at),
sqlc.arg(expires_at)
);
-- name: InvalidateActiveEmailTokens :execrows
UPDATE email_tokens
SET invalidated_at = sqlc.arg(invalidated_at)
WHERE
user_id = sqlc.arg(user_id)
AND purpose = sqlc.arg(purpose)
AND consumed_at IS NULL
AND invalidated_at IS NULL;
-- 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.
-- name: ConsumeEmailToken :one
UPDATE email_tokens AS token
SET consumed_at = sqlc.arg(consumed_at)
FROM users AS owner
WHERE
token.token_hash = sqlc.arg(token_hash)
AND token.purpose = sqlc.arg(purpose)
AND token.consumed_at IS NULL
AND token.invalidated_at IS NULL
AND token.expires_at > sqlc.arg(consumed_at)
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;
-- Explains why ConsumeEmailToken matched no row.
-- 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 = sqlc.arg(token_hash)
AND token.purpose = sqlc.arg(purpose);
-- name: InsertSession :exec
INSERT INTO sessions (
id,
user_id,
token_hash,
created_at,
last_seen_at,
expires_at
) VALUES (
sqlc.arg(id),
sqlc.arg(user_id),
sqlc.arg(token_hash),
sqlc.arg(created_at),
sqlc.arg(last_seen_at),
sqlc.arg(expires_at)
);
-- name: GetActiveSessionByTokenHash :one
SELECT
id,
user_id,
token_hash,
created_at,
last_seen_at,
expires_at,
revoked_at
FROM sessions
WHERE
token_hash = sqlc.arg(token_hash)
AND revoked_at IS NULL
AND expires_at > sqlc.arg(at)
AND last_seen_at > sqlc.arg(idle_cutoff);
-- 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.
-- name: TouchSession :one
WITH active_session AS (
SELECT candidate.id
FROM sessions AS candidate
WHERE
candidate.id = sqlc.arg(id)
AND candidate.revoked_at IS NULL
AND candidate.expires_at > sqlc.arg(at)
AND candidate.last_seen_at > sqlc.arg(idle_cutoff)
),
touched AS (
UPDATE sessions
SET last_seen_at = sqlc.arg(at)
WHERE
sessions.id = sqlc.arg(id)
AND sessions.revoked_at IS NULL
AND sessions.expires_at > sqlc.arg(at)
AND sessions.last_seen_at > sqlc.arg(idle_cutoff)
AND sessions.last_seen_at < sqlc.arg(touch_cutoff)
RETURNING sessions.id
)
SELECT
exists(SELECT 1 FROM active_session) AS active,
exists(SELECT 1 FROM touched) AS touched;
-- name: RevokeSession :execrows
UPDATE sessions
SET revoked_at = sqlc.arg(revoked_at)
WHERE
id = sqlc.arg(id)
AND revoked_at IS NULL;
-- name: RevokeUserSessions :execrows
UPDATE sessions
SET revoked_at = sqlc.arg(revoked_at)
WHERE
user_id = sqlc.arg(user_id)
AND revoked_at IS NULL;