feat: invitation accept screen and api

This commit is contained in:
fsylvain committed 2026-09-29 09:21:53 +02:00
1 parent 310cfd528e
commit 55525c06d6
23 files changed
+2043 -11

No files matched your search

+372
View File
@@ -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>