An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
fix(auth): sign users in when they confirm their sign-up email (#1074)
Yoshiki Miura87b4644d88e3
diff --git a/app/auth/login/page.tsx b/app/auth/login/page.tsxindex e9c5774c..31b499c9 100644--- a/app/auth/login/page.tsx+++ b/app/auth/login/page.tsx@@ -5,14 +5,14 @@ import { LoginForm } from '@/components/login-form'export const dynamic = 'force-dynamic'export default async function Page(props: {- searchParams: Promise<{ next?: string }>+ searchParams: Promise<{ next?: string; confirmed?: string }>}) {- const { next } = await props.searchParams+ const { next, confirmed } = await props.searchParamsreturn (<div className="flex min-h-svh w-full items-center justify-center p-6 md:p-10"><div className="w-full max-w-sm">- <LoginForm next={next} />+ <LoginForm next={next} confirmed={confirmed === '1'} /></div></div>)diff --git a/components/__tests__/login-form.test.tsx b/components/__tests__/login-form.test.tsxindex 2ed0cc21..a6646b3e 100644--- a/components/__tests__/login-form.test.tsx+++ b/components/__tests__/login-form.test.tsx@@ -32,14 +32,15 @@ const capabilities = {function renderForm(override: Partial<typeof capabilities> = {},user = null,- next?: string+ next?: string,+ confirmed?: boolean) {return render(<AppUserProvideruser={user}capabilities={{ ...capabilities, ...override }}>- <LoginForm next={next} />+ <LoginForm next={next} confirmed={confirmed} /></AppUserProvider>)}@@ -49,6 +50,14 @@ describe('LoginForm', () => {vi.clearAllMocks()})+ it('prompts users arriving from a confirmation link to sign in', () => {+ renderForm({}, null, undefined, true)++ expect(+ screen.getByText('If you just confirmed your email, sign in to continue.')+ ).toBeInTheDocument()+ })+it('signs in through the auth server action and refreshes the router', async () => {vi.mocked(signIn).mockResolvedValue({ success: true })renderForm()diff --git a/components/login-form.tsx b/components/login-form.tsxindex a4d4e489..9feee9cd 100644--- a/components/login-form.tsx+++ b/components/login-form.tsx@@ -26,8 +26,12 @@ import { PasswordInput } from './ui/password-input'export function LoginForm({className,next,+ confirmed = false,...props-}: React.ComponentPropsWithoutRef<'div'> & { next?: string }) {+}: React.ComponentPropsWithoutRef<'div'> & {+ next?: string+ confirmed?: boolean+}) {const [email, setEmail] = useState('')const [password, setPassword] = useState('')const [error, setError] = useState<string | null>(null)@@ -96,7 +100,11 @@ export function LoginForm({<IconLogo className="size-12" />Welcome back</CardTitle>- <CardDescription>Sign in to your account</CardDescription>+ <CardDescription>+ {confirmed+ ? 'If you just confirmed your email, sign in to continue.'+ : 'Sign in to your account'}+ </CardDescription></CardHeader><CardContent><div className="flex flex-col gap-4">diff --git a/lib/auth/__tests__/supabase-provider.test.ts b/lib/auth/__tests__/supabase-provider.test.tsindex 6bce5b74..0bdea6d0 100644--- a/lib/auth/__tests__/supabase-provider.test.ts+++ b/lib/auth/__tests__/supabase-provider.test.ts@@ -11,7 +11,7 @@ vi.mock('@/lib/supabase/server', () => ({}))vi.mock('@/lib/supabase/middleware', () => ({updateSession: vi.fn(),- exchangeRecoveryCode: vi.fn()+ exchangeAuthCode: vi.fn()}))vi.mock('@/lib/supabase/keys', () => ({hasSupabasePublicConfig: vi.fn(() => true)@@ -20,7 +20,7 @@ vi.mock('next/headers', () => ({ headers: vi.fn() }))import { headers } from 'next/headers'-import { exchangeRecoveryCode, updateSession } from '@/lib/supabase/middleware'+import { exchangeAuthCode, updateSession } from '@/lib/supabase/middleware'function request(url: string) {return new NextRequest(url)@@ -58,14 +58,14 @@ describe('supabase provider', () => {const exchanged = NextResponse.redirect('http://localhost:3000/auth/update-password')- vi.mocked(exchangeRecoveryCode).mockResolvedValue(exchanged)+ vi.mocked(exchangeAuthCode).mockResolvedValue(exchanged)const req = request('http://localhost:3000/auth/update-password?code=abc&state=xyz')const response = await supabaseAuthProvider.handleSession!(req)- expect(exchangeRecoveryCode).toHaveBeenCalledWith(req, 'abc')+ expect(exchangeAuthCode).toHaveBeenCalledWith(req, 'abc')expect(updateSession).not.toHaveBeenCalled()expect(response).toBe(exchanged)})@@ -79,10 +79,22 @@ describe('supabase provider', () => {)expect(updateSession).toHaveBeenCalledOnce()- expect(exchangeRecoveryCode).not.toHaveBeenCalled()+ expect(exchangeAuthCode).not.toHaveBeenCalled()expect(response).toBe(next)})+ it('exchanges a sign-up confirmation code arriving at the root', async () => {+ const exchanged = NextResponse.redirect('http://localhost:3000/')+ vi.mocked(exchangeAuthCode).mockResolvedValue(exchanged)+ const req = request('http://localhost:3000/?code=abc')++ const response = await supabaseAuthProvider.handleSession!(req)++ expect(exchangeAuthCode).toHaveBeenCalledWith(req, 'abc', '?confirmed=1')+ expect(updateSession).not.toHaveBeenCalled()+ expect(response).toBe(exchanged)+ })+it('ignores code params on other paths', async () => {const next = NextResponse.next()vi.mocked(updateSession).mockResolvedValue(next)@@ -92,7 +104,7 @@ describe('supabase provider', () => {)expect(updateSession).toHaveBeenCalledOnce()- expect(exchangeRecoveryCode).not.toHaveBeenCalled()+ expect(exchangeAuthCode).not.toHaveBeenCalled()})})})diff --git a/lib/auth/providers/supabase.ts b/lib/auth/providers/supabase.tsindex 7ac7dfcd..54c67f85 100644--- a/lib/auth/providers/supabase.ts+++ b/lib/auth/providers/supabase.ts@@ -6,7 +6,7 @@ import { getRequestOrigin } from '@/lib/auth/request'import type { AppUser, AuthActionResult, AuthProvider } from '@/lib/auth/types'import { createAdminClient } from '@/lib/supabase/admin'import { hasSupabasePublicConfig } from '@/lib/supabase/keys'-import { exchangeRecoveryCode, updateSession } from '@/lib/supabase/middleware'+import { exchangeAuthCode, updateSession } from '@/lib/supabase/middleware'import { createAuthActionClient, createClient } from '@/lib/supabase/server'function metaString(@@ -60,8 +60,14 @@ export const supabaseAuthProvider: AuthProvider = {return NextResponse.next({ request })}const code = request.nextUrl.searchParams.get('code')- if (request.nextUrl.pathname === '/auth/update-password' && code) {- return exchangeRecoveryCode(request, code)+ if (code) {+ const { pathname } = request.nextUrl+ if (pathname === '/auth/update-password') {+ return exchangeAuthCode(request, code)+ }+ if (pathname === '/') {+ return exchangeAuthCode(request, code, '?confirmed=1')+ }}return updateSession(request)},diff --git a/lib/supabase/__tests__/middleware.test.ts b/lib/supabase/__tests__/middleware.test.tsindex 48d50fb6..367cd95e 100644--- a/lib/supabase/__tests__/middleware.test.ts+++ b/lib/supabase/__tests__/middleware.test.ts@@ -2,7 +2,7 @@ import { NextRequest } from 'next/server'import { beforeEach, describe, expect, it, vi } from 'vitest'-import { exchangeRecoveryCode } from '../middleware'+import { exchangeAuthCode } from '../middleware'vi.mock('@supabase/ssr', () => ({ createServerClient: vi.fn() }))vi.mock('@/lib/supabase/keys', () => ({@@ -11,7 +11,7 @@ vi.mock('@/lib/supabase/keys', () => ({import { createServerClient } from '@supabase/ssr'-describe('exchangeRecoveryCode', () => {+describe('exchangeAuthCode', () => {const exchangeCodeForSession = vi.fn()let cookieOptions: {cookies: {@@ -44,7 +44,7 @@ describe('exchangeRecoveryCode', () => {return { error: null }})- const response = await exchangeRecoveryCode(requestWithCode(), 'abc')+ const response = await exchangeAuthCode(requestWithCode(), 'abc')expect(exchangeCodeForSession).toHaveBeenCalledWith('abc')expect(response.status).toBe(307)@@ -59,11 +59,27 @@ describe('exchangeRecoveryCode', () => {error: { message: 'invalid code' }})- const response = await exchangeRecoveryCode(requestWithCode(), 'abc')+ const response = await exchangeAuthCode(requestWithCode(), 'abc')expect(response.status).toBe(307)expect(response.headers.get('location')).toBe('http://localhost:3000/auth/login')})++ it('carries the failure query to login', async () => {+ exchangeCodeForSession.mockResolvedValue({+ error: { message: 'code verifier not found' }+ })++ const response = await exchangeAuthCode(+ new NextRequest('http://localhost:3000/?code=abc'),+ 'abc',+ '?confirmed=1'+ )++ expect(response.headers.get('location')).toBe(+ 'http://localhost:3000/auth/login?confirmed=1'+ )+ })})diff --git a/lib/supabase/middleware.ts b/lib/supabase/middleware.tsindex 360c2703..76b2b969 100644--- a/lib/supabase/middleware.ts+++ b/lib/supabase/middleware.ts@@ -78,16 +78,11 @@ export async function updateSession(request: NextRequest) {return supabaseResponse}-/**- * Exchange the one-time PKCE code of a password-recovery link for a session,- * persisting it as cookies, then redirect to the clean destination URL. The- * recovery link keeps pointing at `/auth/update-password` (the destination- * existing deployments already allowlist in Supabase), so the exchange runs- * here in middleware where response cookies can be written.- */-export async function exchangeRecoveryCode(+// Exchanges the PKCE code from an emailed link for session cookies.+export async function exchangeAuthCode(request: NextRequest,- code: string+ code: string,+ failureSearch = ''): Promise<NextResponse> {const url = request.nextUrl.clone()url.search = ''@@ -115,7 +110,7 @@ export async function exchangeRecoveryCode(if (error) {const loginUrl = request.nextUrl.clone()loginUrl.pathname = '/auth/login'- loginUrl.search = ''+ loginUrl.search = failureSearchreturn NextResponse.redirect(loginUrl)}