Three pieces of authentication work that need to land together so OAuth sign-ins produce a usable session. * `ensureUserIdByEmail` upserts a `users` row on every OAuth sign-in matched case-insensitively on email, then stamps `token.id` with the resulting UUID so workspace-scoped tRPC procedures can resolve membership. Credentials sign-in already returned the DB id from `authorize`; OAuth now does the equivalent. * `ensureUserHasWorkspace` mints a personal workspace (and `owner` member row) on first sign-in for any user that doesn't already belong to one, so fresh OAuth accounts don't land in the app with no tenant scope. Idempotent; slug collisions retry with a random suffix and cap at 5 attempts. * Migration 0004 adds a `UNIQUE (lower(email))` index on `users` to match the lookup pattern and prevent two providers from minting rows that differ only in casing. Existing rows are normalized to lowercase first; the column-level UNIQUE catches any pre-existing duplicates so they get resolved by a human rather than silently merged. Sign-in / sign-up pages add an Authentik SSO button (gated on `AUTH_AUTHENTIK_*` env vars). Layout switches to GitHub+Google on top with Authentik full-width below. Co-authored-by: Cursor <cursoragent@cursor.com>
18 lines
1.1 KiB
SQL
18 lines
1.1 KiB
SQL
-- ============================================================================
|
|
-- 0004 — Case-insensitive uniqueness on users.email.
|
|
-- ============================================================================
|
|
-- Belt-and-braces: keep the existing column-level UNIQUE on `email` and add a
|
|
-- UNIQUE expression index on `lower(email)`. This makes the case-insensitive
|
|
-- lookups in `apps/web/lib/auth.ts` (`ensureUserIdByEmail`, the credentials
|
|
-- `authorize`) safe forever, and prevents OAuth providers from minting two
|
|
-- rows that differ only in casing.
|
|
--
|
|
-- We normalize existing rows to lowercase first. If the data already contains
|
|
-- two rows whose emails differ only in case, the UPDATE will hit the existing
|
|
-- column-level UNIQUE and fail loudly — that's the right behavior, since
|
|
-- merging duplicate human accounts requires a human decision.
|
|
-- ============================================================================
|
|
|
|
UPDATE "users" SET "email" = lower("email") WHERE "email" <> lower("email");
|
|
--> statement-breakpoint
|
|
CREATE UNIQUE INDEX "users_email_lower_unique" ON "users" USING btree (lower("email"));
|