feat: register T0

This commit is contained in:
fsylvain committed 2026-09-26 02:48:16 +02:00
1 parent a5873f8886
commit 3c3f7c6194
9 files changed
+920 -4

No files matched your search

+239 -2
View File
@@ -1,9 +1,246 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { useRouter } from 'vue-router'
import AuthShell from '@/components/AuthShell.vue'
import PasswordStrengthHint from '@/components/PasswordStrengthHint.vue'
import ResultPanel from '@/components/ResultPanel.vue'
import { ApiError, useApi } from '@/composables/useApi'
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
const router = useRouter()
const api = useApi()
const username = ref('')
const email = ref('')
const password = ref('')
const usernameTouched = ref(false)
const emailTouched = ref(false)
const passwordTouched = ref(false)
const submitting = ref(false)
const passwordShown = ref(false)
const registrationClosed = ref(false)
const serverErrorAlert = ref(false)
const usernameValid = computed(() => username.value.length >= 3 && username.value.length <= 20)
const emailValid = computed(() => EMAIL_PATTERN.test(email.value))
const passwordValid = computed(() => password.value.length >= 8)
const usernameError = computed(() =>
usernameTouched.value && !usernameValid.value ? 'Use 3 to 20 characters.' : '',
)
const emailError = computed(() =>
emailTouched.value && !emailValid.value
? 'Enter a full email address, like name@example.com.'
: '',
)
const passwordRules = computed(() => [{ label: 'At least 8 characters', met: passwordValid.value }])
const formValid = computed(() => usernameValid.value && emailValid.value && passwordValid.value)
function touchAll() {
usernameTouched.value = true
emailTouched.value = true
passwordTouched.value = true
}
function goToLogin() {
router.push('/login')
}
async function onSubmit() {
touchAll()
if (!formValid.value) {
return
}
serverErrorAlert.value = false
submitting.value = true
try {
await api.request('/v1/auth/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
username: username.value,
email: email.value,
password: password.value,
}),
})
await router.push('/register/pending')
} catch (error) {
if (error instanceof ApiError && error.status === 403) {
registrationClosed.value = true
document.title = 'This site already has an owner · RenewCMS'
return
}
serverErrorAlert.value = true
} finally {
submitting.value = false
}
}
const pageTitle = computed(() => (registrationClosed.value ? '' : 'Create the owner account'))
const pageDescription = computed(() =>
registrationClosed.value
? undefined
: "This creates the single admin account for this site. Once it's verified, registration closes.",
)
const closedPanelActions = [{ label: 'Go to log in', onClick: goToLogin }]
</script>
<template>
<AuthShell title="Create your account">
<p>Register placeholder.</p>
<AuthShell :title="pageTitle" :description="pageDescription">
<template v-if="serverErrorAlert" #notice>
<UAlert
color="error"
icon="i-lucide-circle-x"
title="Couldn't create the account"
description="Something went wrong on the server. Try again in a moment."
variant="soft"
:close="false"
role="alert"
/>
</template>
<template v-if="registrationClosed" #default>
<ResultPanel
tone="info"
icon="i-lucide-user-x"
title="This site already has an owner"
description="Log in instead."
:actions="closedPanelActions"
/>
</template>
<template v-else #default="{ controlSize, controlClass }">
<UForm
:state="{ username, email, password }"
class="flex flex-col gap-4"
@submit="onSubmit"
>
<UFormField
label="Username"
name="username"
:error="usernameError || undefined"
:size="controlSize"
>
<template v-if="usernameError" #error="{ error }">
<span class="flex items-center gap-1.5">
<UIcon name="i-lucide-circle-alert" class="text-error shrink-0" />
{{ error }}
</span>
</template>
<template v-else #help>
Letters and numbers, 3 to 20 characters. You'll use it to log in.
</template>
<template #hint>
<span :class="usernameError ? 'text-error' : 'text-toned'">
{{ username.length }} / 20
</span>
</template>
<UInput
v-model="username"
placeholder="e.g. marta"
autocomplete="username"
:disabled="submitting"
variant="outline"
color="primary"
:highlight="!!usernameError"
:size="controlSize"
:ui="{ base: controlClass }"
class="w-full"
@blur="usernameTouched = true"
/>
</UFormField>
<UFormField
label="Email"
name="email"
:error="emailError || undefined"
:size="controlSize"
>
<template v-if="emailError" #error="{ error }">
<span class="flex items-center gap-1.5">
<UIcon name="i-lucide-circle-alert" class="text-error shrink-0" />
{{ error }}
</span>
</template>
<template v-else #help> We'll send a verification link here. </template>
<UInput
v-model="email"
type="email"
placeholder="you@example.com"
autocomplete="email"
:disabled="submitting"
variant="outline"
color="primary"
:highlight="!!emailError"
:size="controlSize"
:ui="{ base: controlClass }"
class="w-full"
@blur="emailTouched = true"
/>
</UFormField>
<UFormField label="Password" name="password" :size="controlSize">
<template #help>
<PasswordStrengthHint
:rules="passwordRules"
:show-errors="passwordTouched"
/>
</template>
<UInput
v-model="password"
:type="passwordShown ? 'text' : 'password'"
autocomplete="new-password"
:disabled="submitting"
variant="outline"
color="primary"
:size="controlSize"
:ui="{ base: controlClass }"
class="w-full"
@blur="passwordTouched = true"
>
<template #trailing>
<UButton
:icon="passwordShown ? 'i-lucide-eye-off' : 'i-lucide-eye'"
variant="ghost"
color="neutral"
size="sm"
square
:aria-label="passwordShown ? 'Hide password' : 'Show password'"
:aria-pressed="passwordShown"
@click="passwordShown = !passwordShown"
/>
</template>
</UInput>
</UFormField>
<UButton
type="submit"
block
:size="controlSize"
:ui="{ base: controlClass }"
:loading="submitting"
:disabled="submitting"
>
{{ submitting ? 'Creating account…' : 'Create account' }}
</UButton>
</UForm>
</template>
<template v-if="!registrationClosed" #footer>
<p>
Already set up?
<RouterLink to="/login" class="text-primary">Log in</RouterLink>
</p>
</template>
</AuthShell>
</template>
@@ -0,0 +1,299 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { mount, flushPromises } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import uiPlugin from '@nuxt/ui/vue-plugin'
import router from '@/router'
import ResultPanel from '@/components/ResultPanel.vue'
import RegisterView from '../RegisterView.vue'
function mockResponse(status: number, body: unknown = null, headers: Record<string, string> = {}) {
return {
ok: status >= 200 && status < 300,
status,
headers: { get: (name: string) => headers[name] ?? null },
json: async () => body,
} as unknown as Response
}
function routeFor(url: string, init?: RequestInit) {
const method = init?.method ?? 'GET'
return `${method} ${url}`
}
function fetchRouter(handlers: Record<string, () => Response | Promise<Response>>) {
return vi.fn((url: string, init?: RequestInit) => {
const key = routeFor(url, init)
const handler = handlers[key]
if (!handler) {
throw new Error(`Unexpected fetch call: ${key}`)
}
return handler()
})
}
let currentWrapper: Awaited<ReturnType<typeof mount>> | null = null
async function mountRegister(handlers: Record<string, () => Response | Promise<Response>> = {}) {
setActivePinia(createPinia())
const fetchMock = fetchRouter(handlers)
global.fetch = fetchMock as unknown as typeof fetch
await router.push('/register')
const wrapper = mount(RegisterView, {
attachTo: document.body,
global: {
plugins: [router, uiPlugin],
},
})
currentWrapper = wrapper
await flushPromises()
return { wrapper, fetchMock }
}
function usernameInput(wrapper: Awaited<ReturnType<typeof mountRegister>>) {
return wrapper.find('input[placeholder="e.g. marta"]')
}
function emailInput(wrapper: Awaited<ReturnType<typeof mountRegister>>) {
return wrapper.find('input[placeholder="you@example.com"]')
}
function passwordInput(wrapper: Awaited<ReturnType<typeof mountRegister>>) {
return wrapper.find('input[autocomplete="new-password"]')
}
async function fillValidForm(wrapper: Awaited<ReturnType<typeof mountRegister>>) {
await usernameInput(wrapper).setValue('marta')
await emailInput(wrapper).setValue('marta@renew.example')
await passwordInput(wrapper).setValue('limewash2026')
}
afterEach(async () => {
currentWrapper?.unmount()
currentWrapper = null
await router.push('/login')
})
describe('Default — a fresh, empty form', () => {
it('renders the empty state', async () => {
const { wrapper } = await mountRegister()
expect(wrapper.find('h1').text()).toBe('Create the owner account')
expect(wrapper.text()).toContain(
"This creates the single admin account for this site. Once it's verified, registration closes.",
)
expect((usernameInput(wrapper).element as HTMLInputElement).value).toBe('')
expect(wrapper.text()).toContain('0 / 20')
expect((emailInput(wrapper).element as HTMLInputElement).value).toBe('')
expect((passwordInput(wrapper).element as HTMLInputElement).value).toBe('')
expect(wrapper.text()).toContain('At least 8 characters')
expect(wrapper.find('button[type="submit"]').text()).toBe('Create account')
expect(wrapper.text()).toContain('Already set up?')
const footerLink = wrapper.find('a[href="/login"]')
expect(footerLink.exists()).toBe(true)
expect(footerLink.text()).toBe('Log in')
})
})
describe('Validation errors — checked on blur and on submit', () => {
it('shows the three errors and never calls the register endpoint', async () => {
const register = vi.fn(() => mockResponse(200))
const { wrapper } = await mountRegister({
'POST /v1/auth/register': register,
})
await usernameInput(wrapper).setValue('ma')
await usernameInput(wrapper).trigger('blur')
await emailInput(wrapper).setValue('marta@renew')
await emailInput(wrapper).trigger('blur')
await passwordInput(wrapper).setValue('lime')
await passwordInput(wrapper).trigger('blur')
expect(wrapper.text()).toContain('2 / 20')
expect(wrapper.text()).toContain('Use 3 to 20 characters.')
expect(wrapper.text()).toContain('Enter a full email address, like name@example.com.')
await wrapper.find('form').trigger('submit')
await flushPromises()
expect(register).not.toHaveBeenCalled()
expect(wrapper.text()).toContain('Use 3 to 20 characters.')
expect(wrapper.text()).toContain('Enter a full email address, like name@example.com.')
})
})
describe('Filled, valid — every rule is met', () => {
it('shows no errors and a green checklist item', async () => {
const { wrapper } = await mountRegister()
await fillValidForm(wrapper)
const toggle = wrapper.find('button[aria-label="Show password"]')
await toggle.trigger('click')
expect(wrapper.find('button[aria-label="Hide password"]').attributes('aria-pressed')).toBe(
'true',
)
expect(wrapper.text()).toContain('5 / 20')
expect(wrapper.text()).not.toContain('Use 3 to 20 characters.')
expect(wrapper.text()).toContain(
"Letters and numbers, 3 to 20 characters. You'll use it to log in.",
)
expect(wrapper.text()).not.toContain('Enter a full email address, like name@example.com.')
expect(wrapper.text()).toContain("We'll send a verification link here.")
expect((passwordInput(wrapper).element as HTMLInputElement).type).toBe('text')
expect((passwordInput(wrapper).element as HTMLInputElement).value).toBe('limewash2026')
const submitButton = wrapper.find('button[type="submit"]')
expect(submitButton.text()).toBe('Create account')
expect((submitButton.element as HTMLButtonElement).disabled).toBe(false)
})
})
describe('Submitting — fields and button are disabled while the request is in flight', () => {
it('disables the fields and shows the loading label', async () => {
let resolveRegister: (() => void) | null = null
const { wrapper } = await mountRegister({
'POST /v1/auth/register': () =>
new Promise((resolve) => {
resolveRegister = () => resolve(mockResponse(200))
}),
})
await fillValidForm(wrapper)
await wrapper.find('form').trigger('submit')
await flushPromises()
expect((usernameInput(wrapper).element as HTMLInputElement).disabled).toBe(true)
expect((emailInput(wrapper).element as HTMLInputElement).disabled).toBe(true)
expect((passwordInput(wrapper).element as HTMLInputElement).disabled).toBe(true)
const submitButton = wrapper.find('button[type="submit"]')
expect(submitButton.text()).toBe('Creating account…')
expect((submitButton.element as HTMLButtonElement).disabled).toBe(true)
resolveRegister?.()
await flushPromises()
})
})
describe('Registration closed — the form is replaced by a ResultPanel', () => {
it('shows the panel and navigates to /login when activated', async () => {
const { wrapper, fetchMock } = await mountRegister({
'POST /v1/auth/register': () => mockResponse(403),
})
await fillValidForm(wrapper)
await wrapper.find('form').trigger('submit')
await flushPromises()
expect(fetchMock).toHaveBeenCalledWith(
'/v1/auth/register',
expect.objectContaining({
method: 'POST',
body: JSON.stringify({
username: 'marta',
email: 'marta@renew.example',
password: 'limewash2026',
}),
}),
)
expect(wrapper.find('form').exists()).toBe(false)
expect(wrapper.text()).toContain('This site already has an owner')
expect(wrapper.text()).toContain('Log in instead.')
expect(wrapper.text()).not.toContain('Already set up?')
expect(document.title).toBe('This site already has an owner · RenewCMS')
const resultPanel = wrapper.findComponent(ResultPanel)
expect(resultPanel.props('tone')).toBe('info')
expect(resultPanel.props('icon')).toBe('i-lucide-user-x')
const action = wrapper.find('button')
expect(action.text()).toBe('Go to log in')
await action.trigger('click')
await vi.waitFor(() => expect(router.currentRoute.value.path).toBe('/login'))
})
})
describe('Server or network error — the form is kept and re-enabled', () => {
it.each([
{ name: 'a 500 response', handler: () => mockResponse(500) },
{
name: 'a network failure',
handler: () => Promise.reject(new TypeError('Failed to fetch')),
},
])('shows the error alert and keeps the values for $name', async ({ handler }) => {
const register = vi.fn(handler)
const { wrapper, fetchMock } = await mountRegister({
'POST /v1/auth/register': register,
})
await fillValidForm(wrapper)
await wrapper.find('form').trigger('submit')
await flushPromises()
expect(fetchMock).toHaveBeenCalledWith(
'/v1/auth/register',
expect.objectContaining({
method: 'POST',
body: JSON.stringify({
username: 'marta',
email: 'marta@renew.example',
password: 'limewash2026',
}),
}),
)
expect(wrapper.text()).toContain("Couldn't create the account")
expect(wrapper.text()).toContain(
'Something went wrong on the server. Try again in a moment.',
)
expect((usernameInput(wrapper).element as HTMLInputElement).value).toBe('marta')
expect((emailInput(wrapper).element as HTMLInputElement).value).toBe('marta@renew.example')
expect((passwordInput(wrapper).element as HTMLInputElement).value).toBe('limewash2026')
expect((usernameInput(wrapper).element as HTMLInputElement).disabled).toBe(false)
expect((emailInput(wrapper).element as HTMLInputElement).disabled).toBe(false)
expect((passwordInput(wrapper).element as HTMLInputElement).disabled).toBe(false)
const submitButton = wrapper.find('button[type="submit"]')
expect(submitButton.text()).toBe('Create account')
expect((submitButton.element as HTMLButtonElement).disabled).toBe(false)
})
})
describe('A successful registration goes straight to the pending page', () => {
it('navigates directly to /register/pending on submit resolution', async () => {
const { wrapper, fetchMock } = await mountRegister({
'POST /v1/auth/register': () => mockResponse(200),
'GET /v1/auth/me': () => mockResponse(200, { is_verified: false }),
})
await fillValidForm(wrapper)
await wrapper.find('form').trigger('submit')
await vi.waitFor(() => expect(router.currentRoute.value.path).toBe('/register/pending'))
expect(fetchMock).toHaveBeenCalledWith(
'/v1/auth/register',
expect.objectContaining({
method: 'POST',
body: JSON.stringify({
username: 'marta',
email: 'marta@renew.example',
password: 'limewash2026',
}),
}),
)
})
})