Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ DATABASE_URL="postgresql://postgres:postgres@127.0.0.1:54322/postgres?pgbouncer=
# Used by Prisma for migrations
DIRECT_URL="postgresql://postgres:postgres@127.0.0.1:54322/postgres"

# App origin for default OTP magic-link redirect (emailRedirectTo = SITE_URL + /auth/callback)
NEXT_PUBLIC_SITE_URL="http://localhost:3000"

# Supabase project URL
NEXT_PUBLIC_SUPABASE_URL="http://127.0.0.1:54321"

Expand Down
22 changes: 17 additions & 5 deletions src/app/auth/callback/route.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,31 @@
import { NextRequest, NextResponse } from "next/server";
import { authErrorToQueryCode } from "@/lib/supabase/auth-errors";
import { getSafeNextPath } from "@/lib/supabase/next-redirect";
import { createServerSupabaseClient } from "@/lib/supabase/server";

/**
* Auth callback route for Supabase OTP/magic link verification.
* Supabase redirects here with a `code` param after the user
* clicks the magic link or enters an OTP
* Auth callback for Supabase email (PKCE). Supabase redirects here with `code`
* after the user follows the magic link.
*
* Optional query `next`: path-only post-login destination, set when building
* `emailRedirectTo` (e.g. `${origin}/auth/callback?next=/dashboard`).
*/
export async function GET(request: NextRequest) {
const { searchParams, origin } = new URL(request.url);
const code = searchParams.get("code");
const nextPath = getSafeNextPath(searchParams.get("next"));

if (!code) {
return NextResponse.redirect(`${origin}?error=missing_code`);
}

// TODO: Exchange code for a session via supabase
const supabase = await createServerSupabaseClient();
const { error } = await supabase.auth.exchangeCodeForSession(code);

return NextResponse.redirect(origin);
if (error) {
const codeParam = authErrorToQueryCode(error);
return NextResponse.redirect(`${origin}?error=${codeParam}`);
}

return NextResponse.redirect(`${origin}${nextPath}`);
}
35 changes: 35 additions & 0 deletions src/lib/supabase/admin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import "server-only";
import { createClient, type SupabaseClient } from "@supabase/supabase-js";
import { getSupabaseServiceRoleKey, getSupabaseUrl } from "./env";

const globalForAdmin = globalThis as unknown as {
supabaseAdmin?: SupabaseClient;
};

function createAdminClient(): SupabaseClient {
return createClient(getSupabaseUrl(), getSupabaseServiceRoleKey(), {
auth: {
autoRefreshToken: false,
persistSession: false,
},
});
}

/**
* Service-role client for trusted server-only operations (admin API).
* Reuses one instance per runtime (same pattern as Prisma in dev / long-lived Node).
* Never import this module from client components or public routes without authorization.
*/
export function createAdminSupabaseClient(): SupabaseClient {
if (!globalForAdmin.supabaseAdmin) {
globalForAdmin.supabaseAdmin = createAdminClient();
}
return globalForAdmin.supabaseAdmin;
}

/**
* Loads a single user from `auth.users` by id (admin privilege).
*/
export function getAuthUser(supabaseUserId: string) {
return createAdminSupabaseClient().auth.admin.getUserById(supabaseUserId);
}
7 changes: 7 additions & 0 deletions src/lib/supabase/auth-constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/**
* Defaults for org-wide OTP / magic-link behavior. Override per call via sendOtp options when needed.
*/
export const AUTH_CALLBACK_PATH = "/auth/callback";

/** Supabase default is true; we set explicitly so behavior stays obvious in code review. */
export const DEFAULT_OTP_SHOULD_CREATE_USER = true;
18 changes: 18 additions & 0 deletions src/lib/supabase/auth-errors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import type { AuthError } from "@supabase/supabase-js";

/**
* Maps Supabase Auth errors to stable query-param codes for the UI layer.
* Never expose raw provider messages in redirects.
*/
export function authErrorToQueryCode(error: AuthError): string {
const status = error.status;
const msg = error.message.toLowerCase();

if (status === 400 || msg.includes("expired") || msg.includes("invalid")) {
return "session_invalid";
}
if (msg.includes("rate limit") || status === 429) {
return "rate_limited";
}
return "auth_failed";
}
28 changes: 28 additions & 0 deletions src/lib/supabase/env.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/**
* URL and anon key use NEXT_PUBLIC_* so Edge middleware and the browser share one name.
*/
export function getSupabaseUrl(): string {
const url = process.env.NEXT_PUBLIC_SUPABASE_URL;
if (!url) {
throw new Error("Missing NEXT_PUBLIC_SUPABASE_URL environment variable");
}
return url;
}

export function getSupabaseAnonKey(): string {
const key = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;
if (!key) {
throw new Error(
"Missing NEXT_PUBLIC_SUPABASE_ANON_KEY environment variable",
);
}
return key;
}

export function getSupabaseServiceRoleKey(): string {
const key = process.env.SUPABASE_SERVICE_ROLE_KEY;
if (!key) {
throw new Error("Missing SUPABASE_SERVICE_ROLE_KEY environment variable");
}
return key;
}
19 changes: 19 additions & 0 deletions src/lib/supabase/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* Server-oriented exports; individual modules use `server-only` where needed.
* Root middleware imports `updateSession` from here — do not add `import "server-only"` to this file.
*/
export { createAdminSupabaseClient, getAuthUser } from "./admin";
export {
AUTH_CALLBACK_PATH,
DEFAULT_OTP_SHOULD_CREATE_USER,
} from "./auth-constants";
export { authErrorToQueryCode } from "./auth-errors";
export {
getSupabaseAnonKey,
getSupabaseServiceRoleKey,
getSupabaseUrl,
} from "./env";
export { getSafeNextPath } from "./next-redirect";
export { sendOtp, verifyOtp, type SendOtpOptions } from "./otp";
export { createServerSupabaseClient } from "./server";
export { updateSession } from "./middleware";
35 changes: 35 additions & 0 deletions src/lib/supabase/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { createServerClient } from "@supabase/ssr";
import { type NextRequest, NextResponse } from "next/server";
import { getSupabaseAnonKey, getSupabaseUrl } from "./env";

/**
* Refreshes the Auth session and forwards updated cookies on the response.
* Call this from the root `middleware.ts` matcher so sessions stay valid.
*/
export async function updateSession(request: NextRequest) {
let supabaseResponse = NextResponse.next({
request,
});

const supabase = createServerClient(getSupabaseUrl(), getSupabaseAnonKey(), {
cookies: {
getAll: () => request.cookies.getAll(),
setAll(cookiesToSet) {
cookiesToSet.forEach(({ name, value }) =>
request.cookies.set(name, value),
);
supabaseResponse = NextResponse.next({
request,
});
cookiesToSet.forEach(({ name, value, options }) =>
supabaseResponse.cookies.set(name, value, options),
);
},
},
});

// Do not run logic between createServerClient and getUser()
await supabase.auth.getUser();

return supabaseResponse;
}
19 changes: 19 additions & 0 deletions src/lib/supabase/next-redirect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* `next` is supplied by our app when building magic-link URLs, e.g.
* `emailRedirectTo: `${origin}/auth/callback?next=${encodeURIComponent(returnPath)}``.
* Only same-origin path redirects are allowed (blocks open redirects).
*/
export function getSafeNextPath(raw: string | null): string {
const fallback = "/";
if (raw == null || raw === "") {
return fallback;
}
const trimmed = raw.trim();
if (trimmed === "") {
return fallback;
}
if (trimmed.includes("://") || trimmed.startsWith("//")) {
return fallback;
}
return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
}
53 changes: 53 additions & 0 deletions src/lib/supabase/otp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import "server-only";
import type { AuthOtpResponse } from "@supabase/supabase-js";
import {
AUTH_CALLBACK_PATH,
DEFAULT_OTP_SHOULD_CREATE_USER,
} from "./auth-constants";
import { createServerSupabaseClient } from "./server";

export type SendOtpOptions = {
/** Overrides default magic-link callback URL when set. */
emailRedirectTo?: string;
shouldCreateUser?: boolean;
data?: Record<string, unknown>;
};

function getDefaultEmailRedirectTo(): string | undefined {
const base = process.env.NEXT_PUBLIC_SITE_URL?.replace(/\/$/, "");
if (!base) {
return undefined;
}
return `${base}${AUTH_CALLBACK_PATH}`;
}

/**
* Sends a one-time code / magic link via Supabase Auth (configured email provider).
*/
export async function sendOtp(
email: string,
options?: SendOtpOptions,
): Promise<AuthOtpResponse> {
const supabase = await createServerSupabaseClient();
return supabase.auth.signInWithOtp({
email,
options: {
emailRedirectTo: options?.emailRedirectTo ?? getDefaultEmailRedirectTo(),
shouldCreateUser:
options?.shouldCreateUser ?? DEFAULT_OTP_SHOULD_CREATE_USER,
data: options?.data,
},
});
}

/**
* Verifies an email OTP and establishes a session (cookies via server client).
*/
export async function verifyOtp(email: string, token: string) {
const supabase = await createServerSupabaseClient();
return supabase.auth.verifyOtp({
email,
token,
type: "email",
});
}
30 changes: 30 additions & 0 deletions src/lib/supabase/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import "server-only";
import { createServerClient } from "@supabase/ssr";
import { cookies } from "next/headers";
import { getSupabaseAnonKey, getSupabaseUrl } from "./env";

/**
* Supabase client for Server Components, Server Actions, and Route Handlers.
* Persists session via HTTP-only cookies set by Auth responses.
*/
export async function createServerSupabaseClient() {
const cookieStore = await cookies();

return createServerClient(getSupabaseUrl(), getSupabaseAnonKey(), {
cookies: {
getAll() {
return cookieStore.getAll();
},
setAll(cookiesToSet) {
try {
cookiesToSet.forEach(({ name, value, options }) =>
cookieStore.set(name, value, options),
);
} catch {
// Called from a Server Component where cookies are read-only;
// session refresh is handled by middleware.
}
},
},
});
}
15 changes: 15 additions & 0 deletions src/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { type NextRequest } from "next/server";
import { updateSession } from "@/lib/supabase";

export async function middleware(request: NextRequest) {
return updateSession(request);
}

export const config = {
matcher: [
/*
* Match all request paths except static assets and image optimization files.
*/
"/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
],
};
Loading