Add stage 7: email verification magic links and a profile page

Backend
- New Mail namespace: a Mailer interface with SMTP (phpmailer), PHP mail()
  (the default fallback), and log-to-file transports, selected by
  MAIL_TRANSPORT. EmailVerifier issues a hashed, 15-minute magic-link token
  and sends the link (APP_URL/verify-email?token=...).
- Migration 005: email_verifications table + users.verification_email_sent_at.
- Registration now emails a verification link (best effort — a send failure
  doesn't fail registration).
- POST /api/auth/verify-email consumes a token and returns a session, so
  opening the link verifies the address (or applies a pending email change)
  and logs the user in. Single-use; distinct 400s for invalid/used/expired.
- POST /api/email/verification resends; POST /api/email/change requests a
  deferred change (current password required; link goes to the new address;
  users.email only updates when that link is opened). Both throttled to once
  per 60s, returning 429 + retry_after.
- GET /api/me and every session payload now include pending_email. Shared
  SessionPayload builds the user/session JSON for all entry points.

Frontend
- /verify-email view: posts the token, adopts the returned session, redirects.
- /profile view: shows address + status, a resend button with a live cooldown
  (driven by retry_after / 429), and a change-email form (new address +
  current password) that surfaces the pending change.
- Header shows a "verify email" badge linking to the profile.

Tests: 9 new (EmailVerificationTest) covering the link lifecycle, throttle,
and deferred change; AuthTest folded into ApiTestCase, which now routes mail
to a per-test log. Suite: 32 passing.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-03 20:04:49 +01:00
co-authored by Claude Sonnet 5
parent c4c947896e
commit f9b65cc4a7
32 changed files with 1374 additions and 127 deletions
+5 -3
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { RouterView, useRouter } from 'vue-router'
import { RouterLink, RouterView, useRouter } from 'vue-router'
import { useAuthStore } from './stores/auth'
import { useItemsStore } from './stores/items'
import { useListsStore } from './stores/lists'
@@ -23,8 +23,10 @@ async function onLogout() {
<span class="app__brand">Todo List</span>
<div v-if="auth.isAuthenticated" class="app__account">
<span class="app__email">{{ auth.user?.email }}</span>
<span v-if="!auth.emailVerified" class="badge badge--warn">email unverified</span>
<RouterLink v-if="!auth.emailVerified" to="/profile" class="badge badge--warn">
verify email
</RouterLink>
<RouterLink to="/profile" class="app__email">{{ auth.user?.email }}</RouterLink>
<button type="button" class="link" @click="onLogout">Log out</button>
</div>
</header>
+6
View File
@@ -24,6 +24,12 @@ export class ApiError extends Error {
fieldError(field: string): string | undefined {
return this.details[field]?.[0]
}
/** Seconds to wait before retrying, when the server sends one (429 responses). */
get retryAfter(): number | undefined {
const value = (this.details as Record<string, unknown>).retry_after
return typeof value === 'number' ? value : undefined
}
}
interface RequestOptions {
+12
View File
@@ -16,6 +16,18 @@ const router = createRouter({
component: () => import('../views/ListView.vue'),
meta: { requiresAuth: true },
},
{
path: '/profile',
name: 'profile',
component: () => import('../views/ProfileView.vue'),
meta: { requiresAuth: true },
},
{
// Magic-link target. Works signed in or out — verifying returns a session.
path: '/verify-email',
name: 'verify-email',
component: () => import('../views/VerifyEmailView.vue'),
},
{
path: '/login',
name: 'login',
+36
View File
@@ -63,6 +63,39 @@ export const useAuthStore = defineStore('auth', () => {
user.value = null
}
/** Verify an email address from a magic-link token; the response logs the user in. */
async function verifyEmail(magicToken: string): Promise<void> {
adopt(
await apiRequest<AuthResponse>('/auth/verify-email', {
method: 'POST',
body: { token: magicToken },
}),
)
}
/** Resend the verification email. Returns the seconds to wait before the next request. */
async function resendVerification(): Promise<number> {
const { retry_after } = await apiRequest<{ retry_after: number }>('/email/verification', {
method: 'POST',
auth: true,
})
return retry_after
}
/** Request a deferred email change. Returns the pending address and cooldown. */
async function requestEmailChange(
email: string,
password: string,
): Promise<{ pending_email: string; retry_after: number }> {
const result = await apiRequest<{ pending_email: string; retry_after: number }>('/email/change', {
method: 'POST',
auth: true,
body: { email, password },
})
await fetchMe() // pick up user.pending_email
return result
}
/** Resolve the current user from a stored token; clears it if invalid. */
async function fetchMe(): Promise<void> {
if (!token.value) return
@@ -88,5 +121,8 @@ export const useAuthStore = defineStore('auth', () => {
login,
logout,
fetchMe,
verifyEmail,
resendVerification,
requestEmailChange,
}
})
+5
View File
@@ -62,6 +62,11 @@ body {
.app__email {
color: var(--muted);
text-decoration: none;
}
a.badge {
text-decoration: none;
}
.app__main {
+2
View File
@@ -3,6 +3,8 @@ export interface User {
email: string
email_verified: boolean
email_verified_at: string | null
/** A confirmed-but-not-yet-applied email change is waiting on this address. */
pending_email: string | null
created_at: string | null
}
+139
View File
@@ -0,0 +1,139 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, ref } from 'vue'
import { ApiError } from '../lib/api'
import { useAuthStore } from '../stores/auth'
const auth = useAuthStore()
const cooldown = ref(0)
let timer: ReturnType<typeof setInterval> | undefined
function startCooldown(seconds: number) {
cooldown.value = Math.max(0, Math.ceil(seconds))
clearInterval(timer)
timer = setInterval(() => {
cooldown.value -= 1
if (cooldown.value <= 0) clearInterval(timer)
}, 1000)
}
onBeforeUnmount(() => clearInterval(timer))
// --- resend verification -------------------------------------------------
const resending = ref(false)
const resendMessage = ref('')
const resendError = ref('')
async function onResend() {
resending.value = true
resendMessage.value = ''
resendError.value = ''
try {
const retryAfter = await auth.resendVerification()
resendMessage.value = `Sent. Check ${auth.user?.email}.`
startCooldown(retryAfter)
} catch (e) {
if (e instanceof ApiError) {
resendError.value = e.message
if (e.status === 429) startCooldown(e.retryAfter ?? 60)
} else {
resendError.value = 'Could not send the email.'
}
} finally {
resending.value = false
}
}
// --- change email ------------------------------------------------------
const newEmail = ref('')
const password = ref('')
const changing = ref(false)
const changeMessage = ref('')
const changeError = ref<ApiError | null>(null)
async function onChangeEmail() {
changing.value = true
changeMessage.value = ''
changeError.value = null
try {
const { pending_email, retry_after } = await auth.requestEmailChange(newEmail.value, password.value)
changeMessage.value = `Confirmation link sent to ${pending_email}. Your address changes once you open it.`
newEmail.value = ''
password.value = ''
startCooldown(retry_after)
} catch (e) {
changeError.value = e instanceof ApiError ? e : new ApiError('Could not request the change.', 0)
if (e instanceof ApiError && e.status === 429) startCooldown(e.retryAfter ?? 60)
} finally {
changing.value = false
}
}
const resendLabel = computed(() => {
if (resending.value) return 'Sending…'
if (cooldown.value > 0) return `Resend in ${cooldown.value}s`
return 'Resend verification email'
})
</script>
<template>
<section class="card">
<p><RouterLink to="/">&larr; Back to lists</RouterLink></p>
<h1>Your profile</h1>
<p><strong>Email:</strong> {{ auth.user?.email }}</p>
<p>
<strong>Status:</strong>
<span v-if="auth.emailVerified">verified</span>
<span v-else class="badge badge--warn">not verified</span>
</p>
<div v-if="auth.user?.pending_email" class="notice">
A change to <strong>{{ auth.user.pending_email }}</strong> is pending. Open the
link we sent to that address to complete it. The link expires 15 minutes
after it was sent.
</div>
<section v-if="!auth.emailVerified">
<h2>Verify your email</h2>
<p class="muted">
We sent a link to {{ auth.user?.email }}. It expires 15 minutes after
it's sent. You can resend it once a minute.
</p>
<button type="button" :disabled="resending || cooldown > 0" @click="onResend">
{{ resendLabel }}
</button>
<p v-if="resendMessage" class="muted">{{ resendMessage }}</p>
<p v-if="resendError" class="form-error">{{ resendError }}</p>
</section>
<section>
<h2>Change email address</h2>
<form class="form" @submit.prevent="onChangeEmail">
<label>
<span>New email</span>
<input v-model="newEmail" type="email" maxlength="255" required />
<small v-if="changeError?.fieldError('email')" class="field-error">
{{ changeError.fieldError('email') }}
</small>
</label>
<label>
<span>Current password</span>
<input v-model="password" type="password" autocomplete="current-password" required />
<small v-if="changeError?.fieldError('password')" class="field-error">
{{ changeError.fieldError('password') }}
</small>
</label>
<p v-if="changeError && Object.keys(changeError.details).length === 0" class="form-error">
{{ changeError.message }}
</p>
<p v-if="changeMessage" class="muted">{{ changeMessage }}</p>
<button type="submit" :disabled="changing || cooldown > 0">
{{ changing ? 'Sending' : cooldown > 0 ? `Wait ${cooldown}s` : 'Send confirmation link' }}
</button>
</form>
</section>
</section>
</template>
+54
View File
@@ -0,0 +1,54 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ApiError } from '../lib/api'
import { useAuthStore } from '../stores/auth'
const route = useRoute()
const router = useRouter()
const auth = useAuthStore()
const state = ref<'working' | 'done' | 'error'>('working')
const message = ref('')
onMounted(async () => {
const token = typeof route.query.token === 'string' ? route.query.token : ''
if (!token) {
state.value = 'error'
message.value = 'This link is missing its token.'
return
}
try {
await auth.verifyEmail(token)
state.value = 'done'
setTimeout(() => router.push('/'), 1500)
} catch (e) {
state.value = 'error'
message.value = e instanceof ApiError ? e.message : 'Could not verify this link.'
}
})
</script>
<template>
<section class="card">
<h1>Email verification</h1>
<p v-if="state === 'working'" class="muted">Verifying</p>
<template v-else-if="state === 'done'">
<p>Your email address is verified and you're signed in.</p>
<p class="muted">Taking you to your lists</p>
<RouterLink to="/">Go now</RouterLink>
</template>
<template v-else>
<p class="form-error">{{ message }}</p>
<p class="muted">
Request a fresh link from your
<RouterLink to="/profile">profile</RouterLink>, or
<RouterLink to="/login">log in</RouterLink>.
</p>
</template>
</section>
</template>