feat: invitation accept screen and api
This commit is contained in:
1 parent
310cfd528e
commit
55525c06d6
23 files changed
+2043
-11
No files matched your search
@@ -46,6 +46,11 @@ const router = createRouter({
|
||||
component: () => import('@/views/ResetConfirmView.vue'),
|
||||
meta: { auth: 'public' },
|
||||
},
|
||||
{
|
||||
path: '/invite/accept',
|
||||
component: () => import('@/views/AcceptInviteView.vue'),
|
||||
meta: { auth: 'public' },
|
||||
},
|
||||
{
|
||||
path: '/home',
|
||||
component: () => import('@/views/HomeView.vue'),
|
||||
@@ -153,10 +158,7 @@ router.afterEach((to) => {
|
||||
: Promise.resolve()
|
||||
|
||||
settled.then(() => {
|
||||
const destination = resolveAuthRedirect(
|
||||
router.currentRoute.value,
|
||||
session,
|
||||
)
|
||||
const destination = resolveAuthRedirect(router.currentRoute.value, session)
|
||||
if (destination !== true) {
|
||||
router.replace(destination)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,372 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onMounted, ref } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { useToast } from '@nuxt/ui/composables'
|
||||
import AuthShell from '@/components/AuthShell.vue'
|
||||
import PasswordStrengthHint from '@/components/PasswordStrengthHint.vue'
|
||||
import ResultPanel from '@/components/ResultPanel.vue'
|
||||
import { ApiError, useApi } from '@/composables/useApi'
|
||||
import { VERIFIED_REDIRECT_DELAY_MS, wait } from '@/lib/verifiedRedirect'
|
||||
import { useSessionStore } from '@/stores/session'
|
||||
|
||||
type InviteState = 'checking' | 'form' | 'invalid' | 'expired' | 'success'
|
||||
|
||||
const EMAIL_HAS_ACCOUNT_MESSAGE = 'This address already has an account.'
|
||||
const USERNAME_TAKEN_MESSAGE = 'That username is taken. Try another.'
|
||||
const USERNAME_RULE_MESSAGE = 'Use 3 to 20 characters.'
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const api = useApi()
|
||||
const session = useSessionStore()
|
||||
const toast = useToast()
|
||||
|
||||
const code = typeof route.query.c === 'string' ? route.query.c : ''
|
||||
|
||||
const state = ref<InviteState>(code ? 'checking' : 'invalid')
|
||||
const inviteEmail = ref('')
|
||||
const username = ref('')
|
||||
const password = ref('')
|
||||
|
||||
const usernameTouched = ref(false)
|
||||
const passwordTouched = ref(false)
|
||||
const usernameTaken = ref(false)
|
||||
const submitting = ref(false)
|
||||
const passwordShown = ref(false)
|
||||
const serverErrorAlert = ref(false)
|
||||
|
||||
const usernameValid = computed(() => username.value.length >= 3 && username.value.length <= 20)
|
||||
const passwordValid = computed(() => password.value.length >= 8)
|
||||
|
||||
const usernameError = computed(() => {
|
||||
if (usernameTaken.value) {
|
||||
return USERNAME_TAKEN_MESSAGE
|
||||
}
|
||||
return usernameTouched.value && !usernameValid.value ? USERNAME_RULE_MESSAGE : ''
|
||||
})
|
||||
|
||||
const passwordRules = computed(() => [{ label: 'At least 8 characters', met: passwordValid.value }])
|
||||
|
||||
const formValid = computed(() => usernameValid.value && passwordValid.value)
|
||||
|
||||
const showForm = computed(() => state.value === 'form')
|
||||
|
||||
const pageTitle = computed(() => (showForm.value ? 'Accept your invite' : ''))
|
||||
|
||||
const pageDescription = computed(() =>
|
||||
showForm.value
|
||||
? 'Choose a username and password to finish setting up your account.'
|
||||
: undefined,
|
||||
)
|
||||
|
||||
function goToLogin() {
|
||||
router.push('/login')
|
||||
}
|
||||
|
||||
const invalidActions = [{ label: 'Go to log in', onClick: goToLogin }]
|
||||
|
||||
const expiredActions = [
|
||||
{
|
||||
label: 'Go to log in',
|
||||
color: 'neutral' as const,
|
||||
variant: 'outline' as const,
|
||||
onClick: goToLogin,
|
||||
},
|
||||
]
|
||||
|
||||
function onUsernameInput() {
|
||||
usernameTaken.value = false
|
||||
}
|
||||
|
||||
async function focusUsername() {
|
||||
await nextTick()
|
||||
await nextTick()
|
||||
document.querySelector<HTMLInputElement>('input[autocomplete="username"]')?.focus()
|
||||
}
|
||||
|
||||
function applyDeadLinkStatus(error: unknown): boolean {
|
||||
if (!(error instanceof ApiError)) {
|
||||
return false
|
||||
}
|
||||
if (error.status === 404) {
|
||||
state.value = 'invalid'
|
||||
return true
|
||||
}
|
||||
if (error.status === 410) {
|
||||
state.value = 'expired'
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
async function loadInvite() {
|
||||
try {
|
||||
const invite = await api.request<{ email: string }>(
|
||||
`/v1/auth/invite?c=${encodeURIComponent(code)}`,
|
||||
{ onUnauthorized: 'passthrough', onForbidden: 'passthrough' },
|
||||
)
|
||||
inviteEmail.value = invite.email
|
||||
state.value = 'form'
|
||||
} catch (error) {
|
||||
applyDeadLinkStatus(error)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSuccess() {
|
||||
state.value = 'success'
|
||||
toast.add({
|
||||
color: 'success',
|
||||
icon: 'i-lucide-circle-check',
|
||||
title: 'Welcome to RenewCMS',
|
||||
description: `You're logged in as ${username.value}.`,
|
||||
})
|
||||
await Promise.all([session.retry(), wait(VERIFIED_REDIRECT_DELAY_MS)])
|
||||
await router.push('/home')
|
||||
}
|
||||
|
||||
function handleFailure(error: unknown) {
|
||||
if (applyDeadLinkStatus(error)) {
|
||||
return
|
||||
}
|
||||
if (error instanceof ApiError && error.status === 409) {
|
||||
if (error.body === EMAIL_HAS_ACCOUNT_MESSAGE) {
|
||||
state.value = 'invalid'
|
||||
return
|
||||
}
|
||||
usernameTaken.value = true
|
||||
focusUsername()
|
||||
return
|
||||
}
|
||||
serverErrorAlert.value = true
|
||||
}
|
||||
|
||||
async function onSubmit() {
|
||||
usernameTouched.value = true
|
||||
passwordTouched.value = true
|
||||
|
||||
if (!formValid.value) {
|
||||
return
|
||||
}
|
||||
|
||||
serverErrorAlert.value = false
|
||||
submitting.value = true
|
||||
try {
|
||||
await api.request('/v1/auth/invite/accept', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
code,
|
||||
username: username.value,
|
||||
password: password.value,
|
||||
}),
|
||||
onUnauthorized: 'passthrough',
|
||||
onForbidden: 'passthrough',
|
||||
})
|
||||
} catch (error) {
|
||||
handleFailure(error)
|
||||
submitting.value = false
|
||||
return
|
||||
}
|
||||
submitting.value = false
|
||||
await handleSuccess()
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
if (code) {
|
||||
loadInvite()
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AuthShell :title="pageTitle" :description="pageDescription">
|
||||
<template v-if="serverErrorAlert && showForm" #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 #default="{ controlSize, controlClass, inputClass }">
|
||||
<div
|
||||
v-if="state === 'checking'"
|
||||
role="status"
|
||||
class="flex flex-col items-center gap-4 py-10 text-center"
|
||||
>
|
||||
<UIcon name="i-lucide-loader-2" class="size-8 animate-spin text-highlighted" />
|
||||
<p class="text-xl/7 font-semibold text-highlighted">Checking your invite…</p>
|
||||
<p class="text-base text-muted">This only takes a moment.</p>
|
||||
</div>
|
||||
|
||||
<ResultPanel
|
||||
v-else-if="state === 'invalid'"
|
||||
tone="error"
|
||||
icon="i-lucide-link-2-off"
|
||||
title="This invite link doesn't work"
|
||||
description="It may be incomplete, or it may already have been used. If you already set up your account, log in instead."
|
||||
:actions="invalidActions"
|
||||
>
|
||||
<p class="text-sm text-pretty text-muted">
|
||||
Open the link from your email again, or copy the full address into your browser.
|
||||
</p>
|
||||
</ResultPanel>
|
||||
|
||||
<ResultPanel
|
||||
v-else-if="state === 'expired'"
|
||||
tone="error"
|
||||
icon="i-lucide-clock"
|
||||
title="This invite has expired"
|
||||
description="Invites work once, for 3 days. Ask the person who invited you to send a new one."
|
||||
:actions="expiredActions"
|
||||
/>
|
||||
|
||||
<ResultPanel
|
||||
v-else-if="state === 'success'"
|
||||
tone="success"
|
||||
icon="i-lucide-circle-check"
|
||||
title="Your account is ready"
|
||||
description="Taking you to your dashboard…"
|
||||
:actions="[]"
|
||||
/>
|
||||
|
||||
<UForm
|
||||
v-else
|
||||
:state="{ email: inviteEmail, username, password }"
|
||||
class="flex flex-col gap-4.5"
|
||||
@submit="onSubmit"
|
||||
>
|
||||
<UFormField
|
||||
label="Email"
|
||||
name="email"
|
||||
help="From your invitation."
|
||||
:size="controlSize"
|
||||
>
|
||||
<UInput
|
||||
:model-value="inviteEmail"
|
||||
placeholder="you@example.com"
|
||||
autocomplete="email"
|
||||
readonly
|
||||
:disabled="submitting"
|
||||
variant="outline"
|
||||
color="primary"
|
||||
:size="controlSize"
|
||||
:ui="{
|
||||
base: `${inputClass} bg-elevated text-dimmed ring-(--ui-border)`,
|
||||
}"
|
||||
class="w-full"
|
||||
/>
|
||||
</UFormField>
|
||||
|
||||
<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="size-3.5 shrink-0 text-error"
|
||||
/>
|
||||
{{ 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="[
|
||||
'font-mono text-xs',
|
||||
usernameError ? 'text-error' : 'text-muted',
|
||||
]"
|
||||
>
|
||||
{{ username.length }} / 20
|
||||
</span>
|
||||
</template>
|
||||
<UInput
|
||||
v-model="username"
|
||||
placeholder="e.g. lea"
|
||||
autocomplete="username"
|
||||
:disabled="submitting"
|
||||
variant="outline"
|
||||
color="primary"
|
||||
:highlight="!!usernameError"
|
||||
:size="controlSize"
|
||||
:ui="{ base: inputClass, trailing: 'pe-1' }"
|
||||
class="w-full"
|
||||
@update:model-value="onUsernameInput"
|
||||
@blur="usernameTouched = 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: `${inputClass} ${passwordShown ? '' : 'tracking-[2px]'}`,
|
||||
trailing: 'pe-1',
|
||||
}"
|
||||
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
|
||||
class="size-8 justify-center text-toned"
|
||||
: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…' : 'Accept invite' }}
|
||||
</UButton>
|
||||
</UForm>
|
||||
</template>
|
||||
|
||||
<template v-if="showForm" #footer>
|
||||
<span class="flex flex-wrap items-center gap-1.5">
|
||||
Already have an account?
|
||||
<RouterLink
|
||||
to="/login"
|
||||
class="font-medium text-highlighted underline underline-offset-3"
|
||||
>
|
||||
Log in
|
||||
</RouterLink>
|
||||
</span>
|
||||
</template>
|
||||
</AuthShell>
|
||||
</template>
|
||||
@@ -0,0 +1,370 @@
|
||||
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 AcceptInviteView from '../AcceptInviteView.vue'
|
||||
|
||||
type Handler = () => Response | Promise<Response>
|
||||
|
||||
function mockResponse(status: number, body: unknown = null, text = '') {
|
||||
return {
|
||||
ok: status >= 200 && status < 300,
|
||||
status,
|
||||
headers: { get: () => null },
|
||||
json: async () => body,
|
||||
text: async () => text,
|
||||
} as unknown as Response
|
||||
}
|
||||
|
||||
const invalidText =
|
||||
'It may be incomplete, or it may already have been used. If you already set up your account, log in instead.'
|
||||
|
||||
let toastAdd: ReturnType<typeof vi.fn>
|
||||
|
||||
vi.mock('@nuxt/ui/composables', () => ({
|
||||
useToast: () => ({ add: toastAdd }),
|
||||
}))
|
||||
|
||||
let currentWrapper: Awaited<ReturnType<typeof mount>> | null = null
|
||||
|
||||
async function mountAccept(path: string, handlers: Record<string, Handler> = {}) {
|
||||
setActivePinia(createPinia())
|
||||
toastAdd = vi.fn()
|
||||
const fetchMock = vi.fn((url: string, init?: RequestInit) => {
|
||||
const key = `${init?.method ?? 'GET'} ${url}`
|
||||
const handler = handlers[key]
|
||||
if (!handler) {
|
||||
throw new Error(`Unexpected fetch call: ${key}`)
|
||||
}
|
||||
return handler()
|
||||
})
|
||||
global.fetch = fetchMock as unknown as typeof fetch
|
||||
await router.push(path)
|
||||
const wrapper = mount(AcceptInviteView, {
|
||||
attachTo: document.body,
|
||||
global: { plugins: [router, uiPlugin] },
|
||||
})
|
||||
currentWrapper = wrapper
|
||||
await flushPromises()
|
||||
return { wrapper, fetchMock }
|
||||
}
|
||||
|
||||
type Wrapper = Awaited<ReturnType<typeof mountAccept>>['wrapper']
|
||||
|
||||
const validInvite: Record<string, Handler> = {
|
||||
'GET /v1/auth/invite?c=abc123': () => mockResponse(200, { email: 'lea.martin@renew.example' }),
|
||||
}
|
||||
|
||||
function withAccept(accept: Handler): Record<string, Handler> {
|
||||
return { ...validInvite, 'POST /v1/auth/invite/accept': accept }
|
||||
}
|
||||
|
||||
function usernameInput(wrapper: Wrapper) {
|
||||
return wrapper.find('input[placeholder="e.g. lea"]')
|
||||
}
|
||||
|
||||
function emailInput(wrapper: Wrapper) {
|
||||
return wrapper.find('input[placeholder="you@example.com"]')
|
||||
}
|
||||
|
||||
function passwordInput(wrapper: Wrapper) {
|
||||
return wrapper.find('input[autocomplete="new-password"]')
|
||||
}
|
||||
|
||||
async function fill(wrapper: Wrapper, username: string, password: string) {
|
||||
await usernameInput(wrapper).setValue(username)
|
||||
await passwordInput(wrapper).setValue(password)
|
||||
}
|
||||
|
||||
async function submit(wrapper: Wrapper) {
|
||||
await wrapper.find('form').trigger('submit')
|
||||
await flushPromises()
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
currentWrapper?.unmount()
|
||||
currentWrapper = null
|
||||
vi.useRealTimers()
|
||||
await router.push('/login')
|
||||
})
|
||||
|
||||
describe('Checking the link', () => {
|
||||
it('shows a full-card spinner while the invite is looked up', async () => {
|
||||
const { wrapper, fetchMock } = await mountAccept('/invite/accept?c=abc123', {
|
||||
'GET /v1/auth/invite?c=abc123': () => new Promise(() => {}),
|
||||
})
|
||||
|
||||
expect(wrapper.text()).toContain('Checking your invite…')
|
||||
expect(wrapper.find('form').exists()).toBe(false)
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Default', () => {
|
||||
it('renders the form with the invited email read-only', async () => {
|
||||
const { wrapper } = await mountAccept('/invite/accept?c=abc123', validInvite)
|
||||
|
||||
expect(wrapper.find('h1').text()).toBe('Accept your invite')
|
||||
expect(wrapper.text()).toContain(
|
||||
'Choose a username and password to finish setting up your account.',
|
||||
)
|
||||
const email = emailInput(wrapper).element as HTMLInputElement
|
||||
expect(email.value).toBe('lea.martin@renew.example')
|
||||
expect(email.readOnly).toBe(true)
|
||||
expect(wrapper.text()).toContain('From your invitation.')
|
||||
expect((usernameInput(wrapper).element as HTMLInputElement).value).toBe('')
|
||||
expect(wrapper.text()).toContain('0 / 20')
|
||||
expect(wrapper.text()).toContain(
|
||||
"Letters and numbers, 3 to 20 characters. You'll use it to log in.",
|
||||
)
|
||||
expect(passwordInput(wrapper).attributes('type')).toBe('password')
|
||||
expect(wrapper.text()).toContain('At least 8 characters')
|
||||
expect(wrapper.find('button[type="submit"]').text()).toBe('Accept invite')
|
||||
expect(wrapper.text()).toContain('Already have an account?')
|
||||
expect(wrapper.find('a[href="/login"]').text()).toBe('Log in')
|
||||
})
|
||||
|
||||
it('shows the same form to a logged-in visitor without redirecting', async () => {
|
||||
const { wrapper } = await mountAccept('/invite/accept?c=abc123', validInvite)
|
||||
|
||||
expect(router.currentRoute.value.path).toBe('/invite/accept')
|
||||
expect(wrapper.find('form').exists()).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Validation errors', () => {
|
||||
it('shows the errors and never calls the accept endpoint', async () => {
|
||||
const accept = vi.fn(() => mockResponse(200))
|
||||
const { wrapper } = await mountAccept('/invite/accept?c=abc123', withAccept(accept))
|
||||
|
||||
await usernameInput(wrapper).setValue('ma')
|
||||
await usernameInput(wrapper).trigger('blur')
|
||||
await passwordInput(wrapper).setValue('lime')
|
||||
await passwordInput(wrapper).trigger('blur')
|
||||
await submit(wrapper)
|
||||
|
||||
expect(accept).not.toHaveBeenCalled()
|
||||
expect(wrapper.text()).toContain('2 / 20')
|
||||
expect(wrapper.text()).toContain('Use 3 to 20 characters.')
|
||||
const item = wrapper.findAll('li').find((li) => li.text().includes('At least 8 characters'))
|
||||
expect(item?.find('.text-error').exists()).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Filled, valid', () => {
|
||||
it('shows the counter and a met checklist item without errors', async () => {
|
||||
const { wrapper } = await mountAccept('/invite/accept?c=abc123', validInvite)
|
||||
|
||||
await fill(wrapper, 'lea', 'limewash2026')
|
||||
await wrapper.find('button[aria-label="Show password"]').trigger('click')
|
||||
|
||||
expect(wrapper.text()).toContain('3 / 20')
|
||||
expect(passwordInput(wrapper).attributes('type')).toBe('text')
|
||||
expect(wrapper.text()).not.toContain('Use 3 to 20 characters.')
|
||||
const item = wrapper.findAll('li').find((li) => li.text().includes('At least 8 characters'))
|
||||
expect(item?.find('.text-success').exists()).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Submitting', () => {
|
||||
it('sends the code, username and password and disables the form', async () => {
|
||||
const accept = vi.fn(() => new Promise<Response>(() => {}))
|
||||
const { wrapper, fetchMock } = await mountAccept(
|
||||
'/invite/accept?c=abc123',
|
||||
withAccept(accept),
|
||||
)
|
||||
|
||||
await fill(wrapper, 'lea', 'limewash2026')
|
||||
await submit(wrapper)
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'/v1/auth/invite/accept',
|
||||
expect.objectContaining({
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
code: 'abc123',
|
||||
username: 'lea',
|
||||
password: 'limewash2026',
|
||||
}),
|
||||
}),
|
||||
)
|
||||
const button = wrapper.find('button[type="submit"]')
|
||||
expect(button.text()).toBe('Creating account…')
|
||||
expect(button.attributes('disabled')).toBeDefined()
|
||||
expect(usernameInput(wrapper).attributes('disabled')).toBeDefined()
|
||||
expect(passwordInput(wrapper).attributes('disabled')).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Username taken (409)', () => {
|
||||
it('keeps the values, focuses the username and shows the error', async () => {
|
||||
const { wrapper } = await mountAccept(
|
||||
'/invite/accept?c=abc123',
|
||||
withAccept(() => mockResponse(409, null, 'That username is taken. Try another.')),
|
||||
)
|
||||
|
||||
await fill(wrapper, 'marta', 'limewash2026')
|
||||
await submit(wrapper)
|
||||
|
||||
expect((usernameInput(wrapper).element as HTMLInputElement).value).toBe('marta')
|
||||
expect(wrapper.text()).toContain('5 / 20')
|
||||
expect(wrapper.text()).toContain('That username is taken. Try another.')
|
||||
expect(document.activeElement).toBe(usernameInput(wrapper).element)
|
||||
expect((passwordInput(wrapper).element as HTMLInputElement).value).toBe('limewash2026')
|
||||
expect(passwordInput(wrapper).attributes('disabled')).toBeUndefined()
|
||||
expect(wrapper.find('button[type="submit"]').text()).toBe('Accept invite')
|
||||
})
|
||||
})
|
||||
|
||||
describe('The link does not work', () => {
|
||||
async function expectInvalidPanel(wrapper: Wrapper) {
|
||||
expect(wrapper.find('form').exists()).toBe(false)
|
||||
expect(wrapper.text()).toContain("This invite link doesn't work")
|
||||
expect(wrapper.text()).toContain(invalidText)
|
||||
expect(wrapper.text()).toContain(
|
||||
'Open the link from your email again, or copy the full address into your browser.',
|
||||
)
|
||||
const buttons = wrapper.find('[role="alert"]').findAll('button')
|
||||
expect(buttons.map((button) => button.text())).toEqual(['Go to log in'])
|
||||
await buttons[0]!.trigger('click')
|
||||
await flushPromises()
|
||||
expect(router.currentRoute.value.path).toBe('/login')
|
||||
}
|
||||
|
||||
it('renders it without any request when there is no c parameter', async () => {
|
||||
const { wrapper, fetchMock } = await mountAccept('/invite/accept')
|
||||
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
await expectInvalidPanel(wrapper)
|
||||
})
|
||||
|
||||
it('renders it without any request when c is empty', async () => {
|
||||
const { wrapper, fetchMock } = await mountAccept('/invite/accept?c=')
|
||||
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
await expectInvalidPanel(wrapper)
|
||||
})
|
||||
|
||||
it('renders it when the lookup answers 404', async () => {
|
||||
const { wrapper } = await mountAccept('/invite/accept?c=abc123', {
|
||||
'GET /v1/auth/invite?c=abc123': () => mockResponse(404),
|
||||
})
|
||||
|
||||
await expectInvalidPanel(wrapper)
|
||||
})
|
||||
|
||||
it('replaces the form when the submit answers 404', async () => {
|
||||
const { wrapper } = await mountAccept(
|
||||
'/invite/accept?c=abc123',
|
||||
withAccept(() => mockResponse(404)),
|
||||
)
|
||||
|
||||
await fill(wrapper, 'lea', 'limewash2026')
|
||||
await submit(wrapper)
|
||||
|
||||
await expectInvalidPanel(wrapper)
|
||||
})
|
||||
|
||||
it('replaces the form when the submit answers the email-has-account 409', async () => {
|
||||
const { wrapper } = await mountAccept(
|
||||
'/invite/accept?c=abc123',
|
||||
withAccept(() => mockResponse(409, null, 'This address already has an account.')),
|
||||
)
|
||||
|
||||
await fill(wrapper, 'lea', 'limewash2026')
|
||||
await submit(wrapper)
|
||||
|
||||
await expectInvalidPanel(wrapper)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Expired link (410)', () => {
|
||||
async function expectExpiredPanel(wrapper: Wrapper) {
|
||||
expect(wrapper.find('form').exists()).toBe(false)
|
||||
expect(wrapper.text()).toContain('This invite has expired')
|
||||
expect(wrapper.text()).toContain(
|
||||
'Invites work once, for 3 days. Ask the person who invited you to send a new one.',
|
||||
)
|
||||
const buttons = wrapper.find('[role="alert"]').findAll('button')
|
||||
expect(buttons.map((button) => button.text())).toEqual(['Go to log in'])
|
||||
await buttons[0]!.trigger('click')
|
||||
await flushPromises()
|
||||
expect(router.currentRoute.value.path).toBe('/login')
|
||||
}
|
||||
|
||||
it('renders it when the lookup answers 410', async () => {
|
||||
const { wrapper } = await mountAccept('/invite/accept?c=abc123', {
|
||||
'GET /v1/auth/invite?c=abc123': () => mockResponse(410),
|
||||
})
|
||||
|
||||
await expectExpiredPanel(wrapper)
|
||||
})
|
||||
|
||||
it('replaces the form when the submit answers 410', async () => {
|
||||
const { wrapper } = await mountAccept(
|
||||
'/invite/accept?c=abc123',
|
||||
withAccept(() => mockResponse(410)),
|
||||
)
|
||||
|
||||
await fill(wrapper, 'lea', 'limewash2026')
|
||||
await submit(wrapper)
|
||||
|
||||
await expectExpiredPanel(wrapper)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Server error', () => {
|
||||
it.each([
|
||||
{ name: 'resolves 500', handler: () => mockResponse(500) },
|
||||
{ name: 'resolves 429', handler: () => mockResponse(429) },
|
||||
{
|
||||
name: 'never reaches the server',
|
||||
handler: () => Promise.reject(new TypeError('Failed to fetch')),
|
||||
},
|
||||
])('shows the alert and keeps the form when the submit $name', async ({ handler }) => {
|
||||
const { wrapper } = await mountAccept('/invite/accept?c=abc123', withAccept(handler))
|
||||
|
||||
await fill(wrapper, 'lea', 'limewash2026')
|
||||
await submit(wrapper)
|
||||
|
||||
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((emailInput(wrapper).element as HTMLInputElement).value).toBe(
|
||||
'lea.martin@renew.example',
|
||||
)
|
||||
expect((usernameInput(wrapper).element as HTMLInputElement).value).toBe('lea')
|
||||
expect((passwordInput(wrapper).element as HTMLInputElement).value).toBe('limewash2026')
|
||||
expect(usernameInput(wrapper).attributes('disabled')).toBeUndefined()
|
||||
expect(wrapper.find('button[type="submit"]').text()).toBe('Accept invite')
|
||||
})
|
||||
})
|
||||
|
||||
describe('Success', () => {
|
||||
it('shows the panel and toast, then navigates to /home after 800 ms', async () => {
|
||||
const { wrapper } = await mountAccept('/invite/accept?c=abc123', {
|
||||
...withAccept(() => mockResponse(200, { message: 'ok' })),
|
||||
'GET /v1/auth/me': () => mockResponse(200, { is_verified: true }),
|
||||
})
|
||||
vi.useFakeTimers()
|
||||
|
||||
await fill(wrapper, 'lea', 'limewash2026')
|
||||
await submit(wrapper)
|
||||
|
||||
expect(wrapper.text()).toContain('Your account is ready')
|
||||
expect(wrapper.text()).toContain('Taking you to your dashboard…')
|
||||
expect(wrapper.find('form').exists()).toBe(false)
|
||||
expect(toastAdd).toHaveBeenCalledWith({
|
||||
color: 'success',
|
||||
icon: 'i-lucide-circle-check',
|
||||
title: 'Welcome to RenewCMS',
|
||||
description: "You're logged in as lea.",
|
||||
})
|
||||
expect(router.currentRoute.value.path).toBe('/invite/accept')
|
||||
|
||||
await vi.advanceTimersByTimeAsync(800)
|
||||
await vi.waitFor(() => expect(router.currentRoute.value.path).toBe('/home'))
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user