auth: case-insensitive emails, Authentik SSO, first-signin workspace provisioning
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>
This commit is contained in:
parent
c582d621ce
commit
875b1cfc87
7 changed files with 2675 additions and 46 deletions
|
|
@ -4,7 +4,7 @@ import { Suspense, useState } from "react";
|
|||
import Link from "next/link";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
import { signIn } from "next-auth/react";
|
||||
import { Loader2, Lock, Mail, Sparkles } from "lucide-react";
|
||||
import { Loader2, Lock, Mail, ShieldCheck, Sparkles } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
function SignInForm() {
|
||||
|
|
@ -130,47 +130,60 @@ function SignInForm() {
|
|||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div className="space-y-3">
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void signIn("github", { callbackUrl })}
|
||||
className={cn(
|
||||
"flex items-center justify-center gap-2 rounded-lg border border-border bg-background py-2.5 text-sm font-medium transition",
|
||||
"hover:border-[hsl(var(--primary)/0.4)] hover:bg-muted/50",
|
||||
)}
|
||||
>
|
||||
<svg className="h-4 w-4" viewBox="0 0 24 24" fill="currentColor" aria-hidden>
|
||||
<path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z" />
|
||||
</svg>
|
||||
GitHub
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void signIn("google", { callbackUrl })}
|
||||
className={cn(
|
||||
"flex items-center justify-center gap-2 rounded-lg border border-border bg-background py-2.5 text-sm font-medium transition",
|
||||
"hover:border-[hsl(var(--teal)/0.45)] hover:bg-muted/50",
|
||||
)}
|
||||
>
|
||||
<svg className="h-4 w-4" viewBox="0 0 24 24" aria-hidden>
|
||||
<path
|
||||
fill="#4285F4"
|
||||
d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"
|
||||
/>
|
||||
<path
|
||||
fill="#34A853"
|
||||
d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
|
||||
/>
|
||||
<path
|
||||
fill="#FBBC05"
|
||||
d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"
|
||||
/>
|
||||
<path
|
||||
fill="#EA4335"
|
||||
d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"
|
||||
/>
|
||||
</svg>
|
||||
Google
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void signIn("github", { callbackUrl })}
|
||||
onClick={() => void signIn("authentik", { callbackUrl })}
|
||||
className={cn(
|
||||
"flex items-center justify-center gap-2 rounded-lg border border-border bg-background py-2.5 text-sm font-medium transition",
|
||||
"flex w-full items-center justify-center gap-2 rounded-lg border border-border bg-background py-2.5 text-sm font-medium transition",
|
||||
"hover:border-[hsl(var(--primary)/0.4)] hover:bg-muted/50",
|
||||
)}
|
||||
>
|
||||
<svg className="h-4 w-4" viewBox="0 0 24 24" fill="currentColor" aria-hidden>
|
||||
<path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z" />
|
||||
</svg>
|
||||
GitHub
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void signIn("google", { callbackUrl })}
|
||||
className={cn(
|
||||
"flex items-center justify-center gap-2 rounded-lg border border-border bg-background py-2.5 text-sm font-medium transition",
|
||||
"hover:border-[hsl(var(--teal)/0.45)] hover:bg-muted/50",
|
||||
)}
|
||||
>
|
||||
<svg className="h-4 w-4" viewBox="0 0 24 24" aria-hidden>
|
||||
<path
|
||||
fill="#4285F4"
|
||||
d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"
|
||||
/>
|
||||
<path
|
||||
fill="#34A853"
|
||||
d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
|
||||
/>
|
||||
<path
|
||||
fill="#FBBC05"
|
||||
d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"
|
||||
/>
|
||||
<path
|
||||
fill="#EA4335"
|
||||
d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"
|
||||
/>
|
||||
</svg>
|
||||
Google
|
||||
<ShieldCheck className="h-4 w-4 text-[hsl(var(--primary))]" aria-hidden />
|
||||
Authentik SSO
|
||||
</button>
|
||||
</div>
|
||||
|
||||
|
|
|
|||
|
|
@ -2,7 +2,8 @@
|
|||
|
||||
import { useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { Loader2, Mail, Sparkles, User, Lock } from "lucide-react";
|
||||
import { signIn } from "next-auth/react";
|
||||
import { Loader2, Lock, Mail, ShieldCheck, Sparkles, User } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export default function SignUpPage() {
|
||||
|
|
@ -134,6 +135,27 @@ export default function SignUpPage() {
|
|||
</button>
|
||||
</form>
|
||||
|
||||
<div className="relative my-8">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
<span className="w-full border-t border-border" />
|
||||
</div>
|
||||
<div className="relative flex justify-center text-xs uppercase tracking-wide">
|
||||
<span className="bg-card/90 px-2 text-muted-foreground">Or use single sign-on</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void signIn("authentik", { callbackUrl: "/" })}
|
||||
className={cn(
|
||||
"flex w-full items-center justify-center gap-2 rounded-lg border border-border bg-background py-2.5 text-sm font-medium transition",
|
||||
"hover:border-[hsl(var(--primary)/0.4)] hover:bg-muted/50",
|
||||
)}
|
||||
>
|
||||
<ShieldCheck className="h-4 w-4 text-[hsl(var(--primary))]" aria-hidden />
|
||||
Continue with SSO
|
||||
</button>
|
||||
|
||||
<p className="mt-8 text-center text-sm text-muted-foreground">
|
||||
Already have an account?{" "}
|
||||
<Link
|
||||
|
|
|
|||
|
|
@ -6,11 +6,117 @@ import GitHub from "next-auth/providers/github";
|
|||
import Google from "next-auth/providers/google";
|
||||
|
||||
/**
|
||||
* Optional: `pnpm add @auth/drizzle-adapter` then wire DrizzleAdapter + session strategy "database".
|
||||
* Using JWT + Credentials/OAuth; `db` is loaded dynamically inside `authorize` (Node route handler only).
|
||||
* User lookup uses the postgres.js client from Drizzle (`db.$client`) so we avoid a direct `drizzle-orm` import in this app.
|
||||
* Session strategy is JWT (no `@auth/drizzle-adapter`). We still want every
|
||||
* authenticated request to carry a real `users.id` so workspace-scoped tRPC
|
||||
* procedures can resolve membership, so OAuth sign-ins go through
|
||||
* `ensureUserIdByEmail` to upsert a row in `users` (matched case-insensitively
|
||||
* on email) and stamp `token.id` with the DB UUID. Credentials sign-in already
|
||||
* returns the DB id from `authorize`.
|
||||
*
|
||||
* `db` is loaded dynamically inside callbacks so this module stays importable
|
||||
* from edge contexts (middleware, etc.); the actual SQL only runs on the
|
||||
* Node route handler.
|
||||
*/
|
||||
|
||||
type Sql = (t: TemplateStringsArray, ...v: unknown[]) => Promise<unknown[]>;
|
||||
|
||||
async function getSql(): Promise<Sql> {
|
||||
const { db } = await import("@tasks/database/client");
|
||||
return (db as { $client: Sql }).$client;
|
||||
}
|
||||
|
||||
async function ensureUserIdByEmail(args: {
|
||||
email: string;
|
||||
name?: string | null;
|
||||
image?: string | null;
|
||||
}): Promise<string | null> {
|
||||
const email = args.email.trim();
|
||||
if (!email) return null;
|
||||
const sql = await getSql();
|
||||
|
||||
const existing = (await sql`
|
||||
SELECT id FROM users WHERE lower(email) = lower(${email}) LIMIT 1
|
||||
`) as { id: string }[];
|
||||
if (existing[0]) return existing[0].id;
|
||||
|
||||
await sql`
|
||||
INSERT INTO users (email, name, avatar_url)
|
||||
VALUES (${email.toLowerCase()}, ${args.name ?? null}, ${args.image ?? null})
|
||||
ON CONFLICT (email) DO NOTHING
|
||||
`;
|
||||
const after = (await sql`
|
||||
SELECT id FROM users WHERE lower(email) = lower(${email}) LIMIT 1
|
||||
`) as { id: string }[];
|
||||
return after[0]?.id ?? null;
|
||||
}
|
||||
|
||||
function slugifyForWorkspace(seed: string): string {
|
||||
const cleaned = seed
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "")
|
||||
.slice(0, 50);
|
||||
return cleaned || "workspace";
|
||||
}
|
||||
|
||||
/**
|
||||
* Idempotent: if the user already owns or is a member of any workspace, no-op.
|
||||
* Otherwise mint a personal workspace and add them as `owner`. Runs on every
|
||||
* first sign-in (credentials and OAuth alike) so freshly-created OAuth users
|
||||
* don't land in the app with no tenant scope and an unusable session.
|
||||
*
|
||||
* Slug collisions are handled by retrying with a random 6-char suffix; we cap
|
||||
* attempts so a misbehaving DB can't lock the sign-in flow.
|
||||
*/
|
||||
async function ensureUserHasWorkspace(args: {
|
||||
userId: string;
|
||||
displayName: string | null;
|
||||
email: string;
|
||||
}): Promise<void> {
|
||||
const sql = await getSql();
|
||||
|
||||
const existing = (await sql`
|
||||
SELECT 1
|
||||
FROM workspaces w
|
||||
LEFT JOIN workspace_members m
|
||||
ON m.workspace_id = w.id AND m.user_id = ${args.userId}
|
||||
WHERE w.owner_user_id = ${args.userId} OR m.user_id = ${args.userId}
|
||||
LIMIT 1
|
||||
`) as unknown[];
|
||||
if (existing.length > 0) return;
|
||||
|
||||
const trimmedName = args.displayName?.trim() ?? "";
|
||||
const seed = trimmedName || args.email.split("@")[0] || "workspace";
|
||||
const baseSlug = slugifyForWorkspace(seed);
|
||||
const workspaceName = trimmedName ? `${trimmedName}'s workspace` : "My workspace";
|
||||
|
||||
let workspaceId: string | null = null;
|
||||
let candidate = baseSlug;
|
||||
for (let attempt = 0; attempt < 5 && !workspaceId; attempt += 1) {
|
||||
const inserted = (await sql`
|
||||
INSERT INTO workspaces (slug, name, owner_user_id)
|
||||
VALUES (${candidate}, ${workspaceName}, ${args.userId})
|
||||
ON CONFLICT (slug) DO NOTHING
|
||||
RETURNING id
|
||||
`) as { id: string }[];
|
||||
if (inserted[0]) {
|
||||
workspaceId = inserted[0].id;
|
||||
break;
|
||||
}
|
||||
candidate = `${baseSlug}-${Math.random().toString(36).slice(2, 8)}`;
|
||||
}
|
||||
if (!workspaceId) {
|
||||
console.warn("[auth] Failed to provision workspace for user", args.userId);
|
||||
return;
|
||||
}
|
||||
|
||||
await sql`
|
||||
INSERT INTO workspace_members (workspace_id, user_id, role)
|
||||
VALUES (${workspaceId}, ${args.userId}, 'owner')
|
||||
ON CONFLICT (workspace_id, user_id) DO NOTHING
|
||||
`;
|
||||
}
|
||||
|
||||
declare module "next-auth" {
|
||||
interface Session {
|
||||
user: {
|
||||
|
|
@ -38,9 +144,7 @@ const providers: NextAuthConfig["providers"] = [
|
|||
}
|
||||
if (password !== devPassword) return null;
|
||||
|
||||
const { db } = await import("@tasks/database/client");
|
||||
const sql = (db as { $client: (t: TemplateStringsArray, ...v: unknown[]) => Promise<unknown[]> })
|
||||
.$client;
|
||||
const sql = await getSql();
|
||||
const rows = (await sql`
|
||||
SELECT id, email, name, avatar_url AS "avatarUrl"
|
||||
FROM users
|
||||
|
|
@ -99,9 +203,38 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
|
|||
},
|
||||
providers,
|
||||
callbacks: {
|
||||
async jwt({ token, user }) {
|
||||
if (user?.id) {
|
||||
token.id = user.id;
|
||||
async signIn({ user, account }) {
|
||||
// OAuth providers must give us an email so we can map to a `users` row.
|
||||
if (account && account.provider !== "credentials" && !user?.email) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
async jwt({ token, user, account }) {
|
||||
// First call (sign-in): `user` and `account` are present.
|
||||
if (account && user) {
|
||||
let dbId: string | null = null;
|
||||
if (account.provider === "credentials") {
|
||||
// `authorize` already returns a real DB UUID in `user.id`.
|
||||
dbId = user.id ?? null;
|
||||
} else if (user.email) {
|
||||
dbId = await ensureUserIdByEmail({
|
||||
email: user.email,
|
||||
name: user.name ?? null,
|
||||
image: user.image ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
if (dbId) {
|
||||
token.id = dbId;
|
||||
// Make sure every authenticated user has a tenant they can land in.
|
||||
// Cheap idempotent check; only mints a workspace on the first sign-in.
|
||||
await ensureUserHasWorkspace({
|
||||
userId: dbId,
|
||||
displayName: user.name ?? null,
|
||||
email: user.email ?? "",
|
||||
});
|
||||
}
|
||||
}
|
||||
return token;
|
||||
},
|
||||
|
|
|
|||
18
packages/database/migrations/0004_medical_blob.sql
Normal file
18
packages/database/migrations/0004_medical_blob.sql
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
-- ============================================================================
|
||||
-- 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"));
|
||||
2429
packages/database/migrations/meta/0004_snapshot.json
Normal file
2429
packages/database/migrations/meta/0004_snapshot.json
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -29,6 +29,13 @@
|
|||
"when": 1778124738113,
|
||||
"tag": "0003_damp_green_goblin",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 4,
|
||||
"version": "7",
|
||||
"when": 1779987416637,
|
||||
"tag": "0004_medical_blob",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
import { sql } from "drizzle-orm";
|
||||
import {
|
||||
pgTable,
|
||||
uuid,
|
||||
|
|
@ -22,6 +23,12 @@ export const users = pgTable(
|
|||
},
|
||||
(table) => ({
|
||||
emailIdx: index("users_email_idx").on(table.email),
|
||||
// Belt-and-braces: existing column-level UNIQUE on `email` plus a
|
||||
// case-insensitive UNIQUE on `lower(email)`. The latter prevents
|
||||
// accidentally storing `Alice@x.com` and `alice@x.com` as two users
|
||||
// and makes the case-insensitive lookups in `apps/web/lib/auth.ts`
|
||||
// safe even if upstream rows were created mixed-case.
|
||||
emailLowerUnique: uniqueIndex("users_email_lower_unique").on(sql`lower(${table.email})`),
|
||||
}),
|
||||
);
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue