-
Notifications
You must be signed in to change notification settings - Fork 0
AUTH-11 Implement Supabase SSR clients, OTP helpers, and auth callback #3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
loganravin4
wants to merge
4
commits into
main
Choose a base branch
from
auth-11
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
7b6b499
implement Supabase SSR clients, OTP helpers, and auth callback. block…
loganravin4 0055bc6
AUTH-11 addressed PR comments: safe auth error codes, getSafeNextPath…
loganravin4 6f22971
Merge remote-tracking branch 'origin/main' into auth-11
loganravin4 17e3f84
AUTH-11 ran prettier
loganravin4 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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}`); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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}`; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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, | ||
loganravin4 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| ): 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", | ||
| }); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. | ||
| } | ||
| }, | ||
| }, | ||
| }); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)$).*)", | ||
| ], | ||
| }; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.