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,6 +130,7 @@ function SignInForm() {
|
|||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<button
|
||||
type="button"
|
||||
|
|
@ -173,6 +174,18 @@ function SignInForm() {
|
|||
Google
|
||||
</button>
|
||||
</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 />
|
||||
Authentik SSO
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p className="mt-8 text-center text-sm text-muted-foreground">
|
||||
New to Tasks?{" "}
|
||||
|
|
|
|||
|
|
@ -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