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:
2026-05-06 21:41:30 -04:00
parent 39e85c9770
commit 7d939a4acf
7 changed files with 673 additions and 60 deletions

View 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()
})
})

View File

@@ -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)
})
})
})