feat(auth): add email verification banner, wall, /verify-email page
Wires up the soft 7-day email-verification grace period UX. - EmailVerificationBanner now uses the design-system warning tokens (bg-warning-dim / text-warning) and hides itself once the grace period expires, so the wall takes over without double-messaging. - EmailVerificationWall picks up data-testids on the resend and sign-out CTAs. - VerifyEmailPage gains a single-fire useRef guard (so React 19 strict-mode double-invoke doesn't burn the token), an already-verified short-circuit that skips the API call, success state with auth-store refresh + redirect to /?verified=1, and an error state with a resend CTA. Tests: banner hides past day-7, banner resend triggers API call, verify success refreshes + redirects, verify short-circuits when already verified, single-fire guard holds across remount. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -67,6 +67,7 @@ export function EmailVerificationWall({ className }: EmailVerificationWallProps)
|
|||||||
type="button"
|
type="button"
|
||||||
onClick={handleResend}
|
onClick={handleResend}
|
||||||
disabled={isSending}
|
disabled={isSending}
|
||||||
|
data-testid="resend-button"
|
||||||
className="inline-flex items-center justify-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90 disabled:opacity-50"
|
className="inline-flex items-center justify-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90 disabled:opacity-50"
|
||||||
>
|
>
|
||||||
{isSending && <Loader2 className="h-4 w-4 animate-spin" />}
|
{isSending && <Loader2 className="h-4 w-4 animate-spin" />}
|
||||||
@@ -75,6 +76,7 @@ export function EmailVerificationWall({ className }: EmailVerificationWallProps)
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={handleLogout}
|
onClick={handleLogout}
|
||||||
|
data-testid="sign-out-button"
|
||||||
className="rounded-md border border-default bg-elevated px-4 py-2 text-sm font-medium text-primary transition-colors hover:bg-white/[0.06]"
|
className="rounded-md border border-default bg-elevated px-4 py-2 text-sm font-medium text-primary transition-colors hover:bg-white/[0.06]"
|
||||||
>
|
>
|
||||||
Sign out
|
Sign out
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import { BrandLogo } from '@/components/common/BrandLogo'
|
|||||||
import { TopBar } from './TopBar'
|
import { TopBar } from './TopBar'
|
||||||
import { Sidebar } from './Sidebar'
|
import { Sidebar } from './Sidebar'
|
||||||
import { EmailVerificationBanner } from './EmailVerificationBanner'
|
import { EmailVerificationBanner } from './EmailVerificationBanner'
|
||||||
|
import { EmailVerificationGate } from '@/components/common/EmailVerificationGate'
|
||||||
import { ViewTransitionOutlet } from './ViewTransitionOutlet'
|
import { ViewTransitionOutlet } from './ViewTransitionOutlet'
|
||||||
import { FeedbackWidget } from '@/components/common/FeedbackWidget'
|
import { FeedbackWidget } from '@/components/common/FeedbackWidget'
|
||||||
import { cn } from '@/lib/utils'
|
import { cn } from '@/lib/utils'
|
||||||
@@ -173,7 +174,9 @@ export function AppLayout() {
|
|||||||
{/* Main Content */}
|
{/* Main Content */}
|
||||||
<main className="main-content flex flex-col overflow-hidden min-h-0">
|
<main className="main-content flex flex-col overflow-hidden min-h-0">
|
||||||
<EmailVerificationBanner />
|
<EmailVerificationBanner />
|
||||||
<ViewTransitionOutlet />
|
<EmailVerificationGate>
|
||||||
|
<ViewTransitionOutlet />
|
||||||
|
</EmailVerificationGate>
|
||||||
</main>
|
</main>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,39 @@ import { useAuthStore } from '@/store/authStore'
|
|||||||
import { cn } from '@/lib/utils'
|
import { cn } from '@/lib/utils'
|
||||||
import { toast } from '@/lib/toast'
|
import { toast } from '@/lib/toast'
|
||||||
|
|
||||||
export function EmailVerificationBanner() {
|
const MS_PER_DAY = 24 * 60 * 60 * 1000
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whole days elapsed between an ISO timestamp and now (floored).
|
||||||
|
*
|
||||||
|
* Mirrors the helper in `EmailVerificationGate` — keep the two in sync so the
|
||||||
|
* banner hides on the same day the wall appears (Day 7+ unverified). Defensive
|
||||||
|
* on bad timestamps: treats unparseable input as "just signed up" so we never
|
||||||
|
* accidentally hide the banner on a real unverified user.
|
||||||
|
*/
|
||||||
|
function daysSince(iso: string, now: number = Date.now()): number {
|
||||||
|
const created = Date.parse(iso)
|
||||||
|
if (Number.isNaN(created)) return 0
|
||||||
|
return Math.floor((now - created) / MS_PER_DAY)
|
||||||
|
}
|
||||||
|
|
||||||
|
interface EmailVerificationBannerProps {
|
||||||
|
/**
|
||||||
|
* Override the grace period (in days). Day `gracePeriodDays + 1` and beyond
|
||||||
|
* suppress the banner — `EmailVerificationGate` shows the wall instead.
|
||||||
|
* Defaults to 6 (matches the gate).
|
||||||
|
*/
|
||||||
|
gracePeriodDays?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Top-of-dashboard bar shown to users who signed up but haven't verified their
|
||||||
|
* email yet. Hides itself once the grace period expires (the wall takes over)
|
||||||
|
* and once the user dismisses it for the session.
|
||||||
|
*/
|
||||||
|
export function EmailVerificationBanner({
|
||||||
|
gracePeriodDays = 6,
|
||||||
|
}: EmailVerificationBannerProps = {}) {
|
||||||
const user = useAuthStore((s) => s.user)
|
const user = useAuthStore((s) => s.user)
|
||||||
const [dismissed, setDismissed] = useState(false)
|
const [dismissed, setDismissed] = useState(false)
|
||||||
const [isSending, setIsSending] = useState(false)
|
const [isSending, setIsSending] = useState(false)
|
||||||
@@ -19,6 +51,11 @@ export function EmailVerificationBanner() {
|
|||||||
|
|
||||||
if (!user || user.email_verified_at || dismissed || !verificationEnabled) return null
|
if (!user || user.email_verified_at || dismissed || !verificationEnabled) return null
|
||||||
|
|
||||||
|
// Past grace period: the wall takes over inside <EmailVerificationGate>.
|
||||||
|
// Keep the banner out of the way so we don't double-show messaging.
|
||||||
|
const elapsed = daysSince(user.created_at)
|
||||||
|
if (elapsed > gracePeriodDays) return null
|
||||||
|
|
||||||
const handleResend = async () => {
|
const handleResend = async () => {
|
||||||
setIsSending(true)
|
setIsSending(true)
|
||||||
try {
|
try {
|
||||||
@@ -32,22 +69,29 @@ export function EmailVerificationBanner() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center gap-3 border-b border-amber-400/20 bg-amber-400/5 px-4 py-2 text-sm">
|
<div
|
||||||
<AlertTriangle className="h-4 w-4 shrink-0 text-amber-400" />
|
data-testid="email-verification-banner"
|
||||||
<span className="text-amber-200">
|
className="flex items-center gap-3 border-b border-warning/20 bg-warning-dim px-4 py-2 text-sm"
|
||||||
|
>
|
||||||
|
<AlertTriangle className="h-4 w-4 shrink-0 text-warning" />
|
||||||
|
<span className="text-foreground">
|
||||||
Your email is not verified.
|
Your email is not verified.
|
||||||
</span>
|
</span>
|
||||||
<button
|
<button
|
||||||
|
type="button"
|
||||||
onClick={handleResend}
|
onClick={handleResend}
|
||||||
disabled={isSending}
|
disabled={isSending}
|
||||||
|
data-testid="banner-resend-button"
|
||||||
className={cn(
|
className={cn(
|
||||||
'text-amber-400 underline hover:text-amber-300 disabled:opacity-50'
|
'text-warning underline hover:opacity-80 disabled:opacity-50',
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{isSending ? <Loader2 className="inline h-3 w-3 animate-spin" /> : 'Resend verification email'}
|
{isSending ? <Loader2 className="inline h-3 w-3 animate-spin" /> : 'Resend verification email'}
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
|
type="button"
|
||||||
onClick={() => setDismissed(true)}
|
onClick={() => setDismissed(true)}
|
||||||
|
aria-label="Dismiss"
|
||||||
className="ml-auto text-muted-foreground hover:text-foreground"
|
className="ml-auto text-muted-foreground hover:text-foreground"
|
||||||
>
|
>
|
||||||
<X className="h-4 w-4" />
|
<X className="h-4 w-4" />
|
||||||
|
|||||||
123
frontend/src/components/layout/__tests__/AppLayout.test.tsx
Normal file
123
frontend/src/components/layout/__tests__/AppLayout.test.tsx
Normal file
@@ -0,0 +1,123 @@
|
|||||||
|
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||||
|
import { render, screen } from '@testing-library/react'
|
||||||
|
import { MemoryRouter, Routes, Route } from 'react-router-dom'
|
||||||
|
|
||||||
|
import { AppLayout } from '../AppLayout'
|
||||||
|
import { useAuthStore } from '@/store/authStore'
|
||||||
|
import type { User } from '@/types'
|
||||||
|
|
||||||
|
// Mock heavy/external pieces so this stays a focused integration test for the
|
||||||
|
// gate placement. We don't care that TopBar/Sidebar render real content here —
|
||||||
|
// only that the EmailVerificationGate is in the tree and gates the outlet.
|
||||||
|
vi.mock('@/hooks/useBillingPoll', () => ({
|
||||||
|
useBillingPoll: () => undefined,
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('@/hooks/usePermissions', () => ({
|
||||||
|
usePermissions: () => ({ effectiveRole: 'engineer' }),
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('../TopBar', () => ({
|
||||||
|
TopBar: () => <div data-testid="top-bar" />,
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('../Sidebar', () => ({
|
||||||
|
Sidebar: () => <div data-testid="sidebar" />,
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('../EmailVerificationBanner', () => ({
|
||||||
|
EmailVerificationBanner: () => <div data-testid="email-verification-banner-mock" />,
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('@/components/common/FeedbackWidget', () => ({
|
||||||
|
FeedbackWidget: () => null,
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('@/api/auth', () => ({
|
||||||
|
authApi: {
|
||||||
|
getVerificationStatus: vi.fn().mockResolvedValue({ enabled: true }),
|
||||||
|
sendVerificationEmail: vi.fn().mockResolvedValue(undefined),
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('@/lib/toast', () => ({
|
||||||
|
toast: { success: vi.fn(), error: vi.fn() },
|
||||||
|
}))
|
||||||
|
|
||||||
|
function makeUser(overrides: Partial<User> = {}): User {
|
||||||
|
return {
|
||||||
|
id: 'user-1',
|
||||||
|
email: 'test@example.com',
|
||||||
|
name: 'Test User',
|
||||||
|
role: 'engineer',
|
||||||
|
is_super_admin: false,
|
||||||
|
is_active: true,
|
||||||
|
must_change_password: false,
|
||||||
|
account_id: 'acct-1',
|
||||||
|
account_role: 'engineer',
|
||||||
|
team_id: null,
|
||||||
|
created_at: '2026-05-01T00:00:00Z',
|
||||||
|
last_login: null,
|
||||||
|
phone: null,
|
||||||
|
job_title: null,
|
||||||
|
timezone: 'UTC',
|
||||||
|
avatar_url: null,
|
||||||
|
email_verified_at: null,
|
||||||
|
...overrides,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const FROZEN_NOW = new Date('2026-05-06T00:00:00Z')
|
||||||
|
|
||||||
|
function renderAppLayout() {
|
||||||
|
return render(
|
||||||
|
<MemoryRouter initialEntries={['/']}>
|
||||||
|
<Routes>
|
||||||
|
<Route element={<AppLayout />}>
|
||||||
|
<Route
|
||||||
|
index
|
||||||
|
element={<div data-testid="child-route-content">child route</div>}
|
||||||
|
/>
|
||||||
|
</Route>
|
||||||
|
</Routes>
|
||||||
|
</MemoryRouter>,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('AppLayout — EmailVerificationGate wiring', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.useFakeTimers()
|
||||||
|
vi.setSystemTime(FROZEN_NOW)
|
||||||
|
useAuthStore.setState({ user: null, token: null, isAuthenticated: false })
|
||||||
|
})
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.useRealTimers()
|
||||||
|
useAuthStore.setState({ user: null, token: null, isAuthenticated: false })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('renders the wall and hides the child route on day 8 unverified', () => {
|
||||||
|
// created 8 days before frozen now -> elapsed=8, > grace=6 -> wall.
|
||||||
|
useAuthStore.setState({
|
||||||
|
user: makeUser({ created_at: '2026-04-28T00:00:00Z' }),
|
||||||
|
})
|
||||||
|
|
||||||
|
renderAppLayout()
|
||||||
|
|
||||||
|
expect(screen.getByTestId('email-verification-wall')).toBeInTheDocument()
|
||||||
|
expect(screen.queryByTestId('child-route-content')).not.toBeInTheDocument()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('renders the child route within the grace period (day 1 unverified)', () => {
|
||||||
|
useAuthStore.setState({
|
||||||
|
user: makeUser({ created_at: '2026-05-05T00:00:00Z' }),
|
||||||
|
})
|
||||||
|
|
||||||
|
renderAppLayout()
|
||||||
|
|
||||||
|
expect(screen.getByTestId('child-route-content')).toBeInTheDocument()
|
||||||
|
expect(
|
||||||
|
screen.queryByTestId('email-verification-wall'),
|
||||||
|
).not.toBeInTheDocument()
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||||
|
import { render, screen, waitFor } from '@testing-library/react'
|
||||||
|
import userEvent from '@testing-library/user-event'
|
||||||
|
|
||||||
|
import { EmailVerificationBanner } from '../EmailVerificationBanner'
|
||||||
|
import { useAuthStore } from '@/store/authStore'
|
||||||
|
import { authApi } from '@/api/auth'
|
||||||
|
import type { User } from '@/types'
|
||||||
|
|
||||||
|
vi.mock('@/api/auth', () => ({
|
||||||
|
authApi: {
|
||||||
|
getVerificationStatus: vi.fn(),
|
||||||
|
sendVerificationEmail: vi.fn(),
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('@/lib/toast', () => ({
|
||||||
|
toast: {
|
||||||
|
success: vi.fn(),
|
||||||
|
error: vi.fn(),
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
|
||||||
|
function makeUser(overrides: Partial<User> = {}): User {
|
||||||
|
return {
|
||||||
|
id: 'user-1',
|
||||||
|
email: 'test@example.com',
|
||||||
|
name: 'Test User',
|
||||||
|
role: 'engineer',
|
||||||
|
is_super_admin: false,
|
||||||
|
is_active: true,
|
||||||
|
must_change_password: false,
|
||||||
|
account_id: 'acct-1',
|
||||||
|
account_role: 'engineer',
|
||||||
|
team_id: null,
|
||||||
|
created_at: '2026-05-01T00:00:00Z',
|
||||||
|
last_login: null,
|
||||||
|
phone: null,
|
||||||
|
job_title: null,
|
||||||
|
timezone: 'UTC',
|
||||||
|
avatar_url: null,
|
||||||
|
email_verified_at: null,
|
||||||
|
...overrides,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const FROZEN_NOW = new Date('2026-05-06T00:00:00Z')
|
||||||
|
|
||||||
|
describe('EmailVerificationBanner', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.useFakeTimers({ shouldAdvanceTime: true })
|
||||||
|
vi.setSystemTime(FROZEN_NOW)
|
||||||
|
useAuthStore.setState({ user: null, token: null, isAuthenticated: false })
|
||||||
|
vi.mocked(authApi.getVerificationStatus).mockResolvedValue({
|
||||||
|
enabled: true,
|
||||||
|
})
|
||||||
|
vi.mocked(authApi.sendVerificationEmail).mockResolvedValue(undefined)
|
||||||
|
})
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.useRealTimers()
|
||||||
|
vi.clearAllMocks()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('hides past grace day-7+', async () => {
|
||||||
|
// Created 8 days before frozen now -> elapsed=8, > grace=6.
|
||||||
|
useAuthStore.setState({
|
||||||
|
user: makeUser({ created_at: '2026-04-28T00:00:00Z' }),
|
||||||
|
})
|
||||||
|
|
||||||
|
const { container } = render(<EmailVerificationBanner />)
|
||||||
|
|
||||||
|
// Wait long enough for any pending verification-status fetch to resolve.
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(authApi.getVerificationStatus).toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(
|
||||||
|
screen.queryByTestId('email-verification-banner'),
|
||||||
|
).not.toBeInTheDocument()
|
||||||
|
expect(container.firstChild).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('renders within the grace window', async () => {
|
||||||
|
// Created 1 day before frozen now -> elapsed=1, within grace.
|
||||||
|
useAuthStore.setState({
|
||||||
|
user: makeUser({ created_at: '2026-05-05T00:00:00Z' }),
|
||||||
|
})
|
||||||
|
|
||||||
|
render(<EmailVerificationBanner />)
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(
|
||||||
|
screen.getByTestId('email-verification-banner'),
|
||||||
|
).toBeInTheDocument()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('resend triggers API call', async () => {
|
||||||
|
useAuthStore.setState({
|
||||||
|
user: makeUser({ created_at: '2026-05-05T00:00:00Z' }),
|
||||||
|
})
|
||||||
|
|
||||||
|
render(<EmailVerificationBanner />)
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(
|
||||||
|
screen.getByTestId('email-verification-banner'),
|
||||||
|
).toBeInTheDocument()
|
||||||
|
})
|
||||||
|
|
||||||
|
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })
|
||||||
|
await user.click(screen.getByTestId('banner-resend-button'))
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(authApi.sendVerificationEmail).toHaveBeenCalledTimes(1)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -1,73 +1,221 @@
|
|||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useRef, useState } from 'react'
|
||||||
import { useSearchParams, Link } from 'react-router-dom'
|
import { useNavigate, useSearchParams, Link } from 'react-router-dom'
|
||||||
import { CheckCircle2, XCircle, Loader2 } from 'lucide-react'
|
import { CheckCircle2, XCircle, Loader2, MailCheck } from 'lucide-react'
|
||||||
import { authApi } from '@/api/auth'
|
import { authApi } from '@/api/auth'
|
||||||
|
import { useAuthStore } from '@/store/authStore'
|
||||||
import { PageMeta } from '@/components/common/PageMeta'
|
import { PageMeta } from '@/components/common/PageMeta'
|
||||||
|
import { toast } from '@/lib/toast'
|
||||||
import { cn } from '@/lib/utils'
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
type Status = 'loading' | 'success' | 'error' | 'already-verified' | 'no-token'
|
||||||
|
|
||||||
|
const SUCCESS_REDIRECT_MS = 1200
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Standalone landing page for the email-verification link
|
||||||
|
* (`/verify-email?token=...`).
|
||||||
|
*
|
||||||
|
* Behavior:
|
||||||
|
* - If the user is already verified, short-circuit to a friendly
|
||||||
|
* "Already verified" state. No API call.
|
||||||
|
* - Else fire `POST /auth/email/verify` exactly once (a `useRef` guard keeps
|
||||||
|
* React 19 strict-mode double-invoke from double-firing the call). On
|
||||||
|
* success, refresh the auth store and bounce to `/?verified=1` so the
|
||||||
|
* dashboard surfaces a toast.
|
||||||
|
* - On error, show "Invalid or expired token" + a "Resend" CTA that calls
|
||||||
|
* `POST /auth/email/send-verification`.
|
||||||
|
*/
|
||||||
export function VerifyEmailPage() {
|
export function VerifyEmailPage() {
|
||||||
const [searchParams] = useSearchParams()
|
const [searchParams] = useSearchParams()
|
||||||
|
const navigate = useNavigate()
|
||||||
const token = searchParams.get('token')
|
const token = searchParams.get('token')
|
||||||
const [status, setStatus] = useState<'loading' | 'success' | 'error'>(token ? 'loading' : 'error')
|
|
||||||
const [errorMessage, setErrorMessage] = useState(token ? '' : 'No verification token provided')
|
const alreadyVerified = useAuthStore(
|
||||||
|
(s) => Boolean(s.user?.email_verified_at),
|
||||||
|
)
|
||||||
|
|
||||||
|
const initialStatus: Status = alreadyVerified
|
||||||
|
? 'already-verified'
|
||||||
|
: token
|
||||||
|
? 'loading'
|
||||||
|
: 'no-token'
|
||||||
|
|
||||||
|
const [status, setStatus] = useState<Status>(initialStatus)
|
||||||
|
const [errorMessage, setErrorMessage] = useState<string>('')
|
||||||
|
const [isResending, setIsResending] = useState(false)
|
||||||
|
|
||||||
|
// Single-fire guard: React 19 strict mode runs effects twice on mount.
|
||||||
|
// Without this, the verify endpoint would burn the token on the first call
|
||||||
|
// and then 400 on the second, flashing an error past the success state.
|
||||||
|
const hasFiredRef = useRef(false)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
if (status !== 'loading') return
|
||||||
if (!token) return
|
if (!token) return
|
||||||
|
if (hasFiredRef.current) return
|
||||||
|
hasFiredRef.current = true
|
||||||
|
|
||||||
authApi.verifyEmail(token)
|
let cancelled = false
|
||||||
.then(() => setStatus('success'))
|
|
||||||
.catch((err) => {
|
authApi
|
||||||
setStatus('error')
|
.verifyEmail(token)
|
||||||
const detail = (err as { response?: { data?: { detail?: string } } }).response?.data?.detail
|
.then(async () => {
|
||||||
setErrorMessage(detail ?? 'Verification failed')
|
// Refresh user so `email_verified_at` is populated everywhere.
|
||||||
|
try {
|
||||||
|
await useAuthStore.getState().fetchUser()
|
||||||
|
} catch {
|
||||||
|
// Non-fatal: server confirmed verification, the local user object
|
||||||
|
// will refresh on next page load.
|
||||||
|
}
|
||||||
|
if (cancelled) return
|
||||||
|
setStatus('success')
|
||||||
|
toast.success('Email verified')
|
||||||
|
// Brief success state, then redirect with a query flag so the
|
||||||
|
// dashboard can re-surface confirmation if it wants to.
|
||||||
|
window.setTimeout(() => {
|
||||||
|
navigate('/?verified=1', { replace: true })
|
||||||
|
}, SUCCESS_REDIRECT_MS)
|
||||||
})
|
})
|
||||||
}, [token])
|
.catch((err) => {
|
||||||
|
if (cancelled) return
|
||||||
|
const detail = (err as { response?: { data?: { detail?: string } } })
|
||||||
|
.response?.data?.detail
|
||||||
|
setErrorMessage(detail ?? 'Invalid or expired verification link')
|
||||||
|
setStatus('error')
|
||||||
|
})
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
cancelled = true
|
||||||
|
}
|
||||||
|
}, [status, token, navigate])
|
||||||
|
|
||||||
|
const handleResend = async () => {
|
||||||
|
setIsResending(true)
|
||||||
|
try {
|
||||||
|
await authApi.sendVerificationEmail()
|
||||||
|
toast.success('Verification email sent — check your inbox')
|
||||||
|
} catch {
|
||||||
|
toast.error('Failed to send verification email')
|
||||||
|
} finally {
|
||||||
|
setIsResending(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<PageMeta title="Verify Email" description="Verify your ResolutionFlow email address" />
|
<PageMeta
|
||||||
<div className="flex min-h-screen items-center justify-center bg-background p-4">
|
title="Verify Email"
|
||||||
<div className="card-flat w-full max-w-md p-8 text-center">
|
description="Verify your ResolutionFlow email address"
|
||||||
{status === 'loading' && (
|
/>
|
||||||
<>
|
<div className="flex min-h-screen items-center justify-center bg-background p-4">
|
||||||
<Loader2 className="mx-auto h-12 w-12 animate-spin text-primary" />
|
<div className="card-flat w-full max-w-md p-8 text-center">
|
||||||
<p className="mt-4 text-foreground">Verifying your email...</p>
|
{status === 'loading' && (
|
||||||
</>
|
<>
|
||||||
)}
|
<Loader2 className="mx-auto h-12 w-12 animate-spin text-primary" />
|
||||||
{status === 'success' && (
|
<p className="mt-4 text-foreground">Verifying your email…</p>
|
||||||
<>
|
</>
|
||||||
<CheckCircle2 className="mx-auto h-12 w-12 text-emerald-400" />
|
)}
|
||||||
<h1 className="mt-4 text-xl font-bold font-heading text-foreground">Email Verified</h1>
|
|
||||||
<p className="mt-2 text-muted-foreground">Your email has been successfully verified.</p>
|
{status === 'success' && (
|
||||||
<Link
|
<>
|
||||||
to="/"
|
<CheckCircle2 className="mx-auto h-12 w-12 text-success" />
|
||||||
className={cn(
|
<h1 className="mt-4 text-xl font-bold font-heading text-foreground">
|
||||||
'mt-6 inline-flex items-center rounded-lg bg-primary px-6 py-2 text-sm font-semibold text-white',
|
Email verified
|
||||||
'hover:brightness-110'
|
</h1>
|
||||||
)}
|
<p className="mt-2 text-muted-foreground">
|
||||||
>
|
Redirecting you to the dashboard…
|
||||||
Go to Dashboard
|
</p>
|
||||||
</Link>
|
<Link
|
||||||
</>
|
to="/?verified=1"
|
||||||
)}
|
replace
|
||||||
{status === 'error' && (
|
className={cn(
|
||||||
<>
|
'mt-6 inline-flex items-center rounded-lg bg-primary px-6 py-2 text-sm font-semibold text-primary-foreground',
|
||||||
<XCircle className="mx-auto h-12 w-12 text-rose-500" />
|
'hover:brightness-110',
|
||||||
<h1 className="mt-4 text-xl font-bold font-heading text-foreground">Verification Failed</h1>
|
)}
|
||||||
<p className="mt-2 text-muted-foreground">{errorMessage}</p>
|
>
|
||||||
<Link
|
Go to dashboard
|
||||||
to="/"
|
</Link>
|
||||||
className={cn(
|
</>
|
||||||
'mt-6 inline-flex items-center rounded-lg bg-input border border-border px-6 py-2 text-sm font-medium text-foreground',
|
)}
|
||||||
'hover:border-border-hover'
|
|
||||||
)}
|
{status === 'already-verified' && (
|
||||||
>
|
<>
|
||||||
Go to Dashboard
|
<MailCheck className="mx-auto h-12 w-12 text-success" />
|
||||||
</Link>
|
<h1 className="mt-4 text-xl font-bold font-heading text-foreground">
|
||||||
</>
|
You're already verified
|
||||||
)}
|
</h1>
|
||||||
|
<p className="mt-2 text-muted-foreground">
|
||||||
|
This account's email is already confirmed. No further
|
||||||
|
action needed.
|
||||||
|
</p>
|
||||||
|
<Link
|
||||||
|
to="/"
|
||||||
|
className={cn(
|
||||||
|
'mt-6 inline-flex items-center rounded-lg bg-primary px-6 py-2 text-sm font-semibold text-primary-foreground',
|
||||||
|
'hover:brightness-110',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
Go to dashboard
|
||||||
|
</Link>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{status === 'error' && (
|
||||||
|
<>
|
||||||
|
<XCircle className="mx-auto h-12 w-12 text-danger" />
|
||||||
|
<h1 className="mt-4 text-xl font-bold font-heading text-foreground">
|
||||||
|
Verification failed
|
||||||
|
</h1>
|
||||||
|
<p className="mt-2 text-muted-foreground">
|
||||||
|
{errorMessage || 'Invalid or expired verification link'}
|
||||||
|
</p>
|
||||||
|
<div className="mt-6 flex flex-col gap-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={handleResend}
|
||||||
|
disabled={isResending}
|
||||||
|
data-testid="resend-button"
|
||||||
|
className="inline-flex items-center justify-center gap-2 rounded-lg bg-primary px-6 py-2 text-sm font-semibold text-primary-foreground hover:brightness-110 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{isResending && <Loader2 className="h-4 w-4 animate-spin" />}
|
||||||
|
Resend verification email
|
||||||
|
</button>
|
||||||
|
<Link
|
||||||
|
to="/"
|
||||||
|
className={cn(
|
||||||
|
'inline-flex items-center justify-center rounded-lg border border-default bg-input px-6 py-2 text-sm font-medium text-foreground',
|
||||||
|
'hover:border-border-hover',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
Go to dashboard
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{status === 'no-token' && (
|
||||||
|
<>
|
||||||
|
<XCircle className="mx-auto h-12 w-12 text-danger" />
|
||||||
|
<h1 className="mt-4 text-xl font-bold font-heading text-foreground">
|
||||||
|
Missing verification token
|
||||||
|
</h1>
|
||||||
|
<p className="mt-2 text-muted-foreground">
|
||||||
|
The link you used doesn't include a verification token.
|
||||||
|
Try the link in your verification email again.
|
||||||
|
</p>
|
||||||
|
<Link
|
||||||
|
to="/"
|
||||||
|
className={cn(
|
||||||
|
'mt-6 inline-flex items-center rounded-lg bg-primary px-6 py-2 text-sm font-semibold text-primary-foreground',
|
||||||
|
'hover:brightness-110',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
Go to dashboard
|
||||||
|
</Link>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
174
frontend/src/pages/__tests__/VerifyEmailPage.test.tsx
Normal file
174
frontend/src/pages/__tests__/VerifyEmailPage.test.tsx
Normal file
@@ -0,0 +1,174 @@
|
|||||||
|
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||||
|
import { render, screen, waitFor } from '@testing-library/react'
|
||||||
|
import { MemoryRouter, Route, Routes } from 'react-router-dom'
|
||||||
|
import { HelmetProvider } from 'react-helmet-async'
|
||||||
|
|
||||||
|
import { VerifyEmailPage } from '../VerifyEmailPage'
|
||||||
|
import { authApi } from '@/api/auth'
|
||||||
|
import { useAuthStore } from '@/store/authStore'
|
||||||
|
import type { User } from '@/types'
|
||||||
|
|
||||||
|
vi.mock('@/api/auth', () => ({
|
||||||
|
authApi: {
|
||||||
|
verifyEmail: vi.fn(),
|
||||||
|
sendVerificationEmail: vi.fn(),
|
||||||
|
me: vi.fn(),
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('@/lib/toast', () => ({
|
||||||
|
toast: {
|
||||||
|
success: vi.fn(),
|
||||||
|
error: vi.fn(),
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
|
||||||
|
function makeUser(overrides: Partial<User> = {}): User {
|
||||||
|
return {
|
||||||
|
id: 'user-1',
|
||||||
|
email: 'test@example.com',
|
||||||
|
name: 'Test User',
|
||||||
|
role: 'engineer',
|
||||||
|
is_super_admin: false,
|
||||||
|
is_active: true,
|
||||||
|
must_change_password: false,
|
||||||
|
account_id: 'acct-1',
|
||||||
|
account_role: 'engineer',
|
||||||
|
team_id: null,
|
||||||
|
created_at: '2026-05-01T00:00:00Z',
|
||||||
|
last_login: null,
|
||||||
|
phone: null,
|
||||||
|
job_title: null,
|
||||||
|
timezone: 'UTC',
|
||||||
|
avatar_url: null,
|
||||||
|
email_verified_at: null,
|
||||||
|
...overrides,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderPage(initialPath: string) {
|
||||||
|
return render(
|
||||||
|
<HelmetProvider>
|
||||||
|
<MemoryRouter initialEntries={[initialPath]}>
|
||||||
|
<Routes>
|
||||||
|
<Route path="/verify-email" element={<VerifyEmailPage />} />
|
||||||
|
<Route path="/" element={<div>dashboard</div>} />
|
||||||
|
</Routes>
|
||||||
|
</MemoryRouter>
|
||||||
|
</HelmetProvider>,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('VerifyEmailPage', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.useFakeTimers({ shouldAdvanceTime: true })
|
||||||
|
useAuthStore.setState({
|
||||||
|
user: null,
|
||||||
|
token: null,
|
||||||
|
isAuthenticated: false,
|
||||||
|
})
|
||||||
|
vi.mocked(authApi.me).mockResolvedValue(
|
||||||
|
makeUser({ email_verified_at: '2026-05-06T00:00:00Z' }),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.useRealTimers()
|
||||||
|
vi.clearAllMocks()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('shows success and redirects on valid token', async () => {
|
||||||
|
useAuthStore.setState({ user: makeUser() })
|
||||||
|
// Override fetchUser to avoid hitting axios/XHR in jsdom — the page calls
|
||||||
|
// it after a successful verify to refresh `email_verified_at`.
|
||||||
|
useAuthStore.setState({ fetchUser: vi.fn().mockResolvedValue(undefined) })
|
||||||
|
vi.mocked(authApi.verifyEmail).mockResolvedValue(undefined)
|
||||||
|
|
||||||
|
renderPage('/verify-email?token=valid-token')
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(authApi.verifyEmail).toHaveBeenCalledWith('valid-token')
|
||||||
|
})
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.getByText(/Email verified/i)).toBeInTheDocument()
|
||||||
|
})
|
||||||
|
|
||||||
|
// Advance past the redirect delay.
|
||||||
|
vi.advanceTimersByTime(2000)
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.getByText('dashboard')).toBeInTheDocument()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('shows already-verified state when user is already verified', async () => {
|
||||||
|
useAuthStore.setState({
|
||||||
|
user: makeUser({ email_verified_at: '2026-05-05T00:00:00Z' }),
|
||||||
|
})
|
||||||
|
|
||||||
|
renderPage('/verify-email?token=any-token')
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(
|
||||||
|
screen.getByText(/already verified/i),
|
||||||
|
).toBeInTheDocument()
|
||||||
|
})
|
||||||
|
|
||||||
|
// The verify endpoint must NOT have been called when the user is already
|
||||||
|
// verified — that would burn a perfectly good token for no reason.
|
||||||
|
expect(authApi.verifyEmail).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('only calls verifyEmail once even if the effect re-runs (strict-mode guard)', async () => {
|
||||||
|
useAuthStore.setState({ user: makeUser() })
|
||||||
|
useAuthStore.setState({ fetchUser: vi.fn().mockResolvedValue(undefined) })
|
||||||
|
vi.mocked(authApi.verifyEmail).mockResolvedValue(undefined)
|
||||||
|
|
||||||
|
const { rerender } = render(
|
||||||
|
<HelmetProvider>
|
||||||
|
<MemoryRouter initialEntries={['/verify-email?token=valid-token']}>
|
||||||
|
<Routes>
|
||||||
|
<Route path="/verify-email" element={<VerifyEmailPage />} />
|
||||||
|
<Route path="/" element={<div>dashboard</div>} />
|
||||||
|
</Routes>
|
||||||
|
</MemoryRouter>
|
||||||
|
</HelmetProvider>,
|
||||||
|
)
|
||||||
|
|
||||||
|
// Force a re-render to simulate React 19 strict-mode double-invoke.
|
||||||
|
rerender(
|
||||||
|
<HelmetProvider>
|
||||||
|
<MemoryRouter initialEntries={['/verify-email?token=valid-token']}>
|
||||||
|
<Routes>
|
||||||
|
<Route path="/verify-email" element={<VerifyEmailPage />} />
|
||||||
|
<Route path="/" element={<div>dashboard</div>} />
|
||||||
|
</Routes>
|
||||||
|
</MemoryRouter>
|
||||||
|
</HelmetProvider>,
|
||||||
|
)
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(authApi.verifyEmail).toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(authApi.verifyEmail).toHaveBeenCalledTimes(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('shows an error state with a resend CTA on invalid token', async () => {
|
||||||
|
useAuthStore.setState({ user: makeUser() })
|
||||||
|
vi.mocked(authApi.verifyEmail).mockRejectedValue(
|
||||||
|
Object.assign(new Error('boom'), {
|
||||||
|
response: { data: { detail: 'Token expired' } },
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
renderPage('/verify-email?token=stale-token')
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.getByText(/Verification failed/i)).toBeInTheDocument()
|
||||||
|
})
|
||||||
|
expect(screen.getByText(/Token expired/i)).toBeInTheDocument()
|
||||||
|
expect(screen.getByTestId('resend-button')).toBeInTheDocument()
|
||||||
|
})
|
||||||
|
})
|
||||||
Reference in New Issue
Block a user