Files
RenewCMS/web/src/views/VerifyView.vue
T

415 lines
11 KiB
Vue

<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 ResultPanel from '@/components/ResultPanel.vue'
import { ApiError, useApi } from '@/composables/useApi'
import { useRetryAfter } from '@/composables/useRetryAfter'
import { registrationCancelledToast } from '@/lib/registrationToasts'
import { VERIFIED_REDIRECT_DELAY_MS, wait } from '@/lib/verifiedRedirect'
import { useSessionStore } from '@/stores/session'
type VerifyState =
| 'verifying'
| 'noSessionRetrying'
| 'success'
| 'invalid'
| 'noSession'
| 'missing'
interface AlertState {
tone: 'error' | 'info'
icon: string
title: string
description: string
}
const wrongCredentialsAlert: AlertState = {
tone: 'error',
icon: 'i-lucide-circle-x',
title: "That username and password don't match",
description: 'Check both and try again. Passwords are case-sensitive.',
}
const tooManyAttemptsAlert: AlertState = {
tone: 'info',
icon: 'i-lucide-timer',
title: 'Too many attempts',
description: 'For your security, wait a moment before trying again.',
}
const serverErrorAlert: AlertState = {
tone: 'error',
icon: 'i-lucide-circle-x',
title: "Couldn't reach RenewCMS",
description: 'Check your connection and try again.',
}
const cancelFailedAlert: AlertState = {
tone: 'error',
icon: 'i-lucide-circle-x',
title: "Couldn't cancel registration",
description: 'Something went wrong on the server. Try again in a moment.',
}
const route = useRoute()
const router = useRouter()
const api = useApi()
const session = useSessionStore()
const toast = useToast()
const retryAfter = useRetryAfter()
const state = ref<VerifyState>('missing')
const invalidActionsDisabled = ref(false)
const cancelAlert = ref<AlertState | null>(null)
const username = ref('')
const password = ref('')
const passwordShown = ref(false)
const loginSubmitting = ref(false)
const loginAlert = ref<AlertState | null>(null)
const shellTitle = computed(() => (state.value === 'noSession' ? 'Log in to finish verifying' : ''))
const shellDescription = computed(() =>
state.value === 'noSession'
? "You opened this link somewhere you're not logged in. Log in here and we'll verify your account right after."
: undefined,
)
const usernameError = ref('')
const passwordError = ref('')
const loginSubmitDisabled = computed(() => loginSubmitting.value || retryAfter.active.value)
const loginSubmitLabel = computed(() => {
if (loginSubmitting.value) {
return 'Logging in…'
}
if (retryAfter.active.value) {
return `Try again in ${retryAfter.formatted.value}`
}
return 'Log in and verify'
})
async function focusPassword() {
await nextTick()
await nextTick()
document.querySelector<HTMLInputElement>('input[autocomplete="current-password"]')?.focus()
}
async function performVerify(code: string) {
try {
await api.request('/v1/auth/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code }),
onUnauthorized: 'passthrough',
onForbidden: 'passthrough',
})
state.value = 'success'
toast.add({
color: 'success',
icon: 'i-lucide-circle-check',
title: 'Your account is verified',
description: 'Welcome to RenewCMS.',
})
await Promise.all([session.retry(), wait(VERIFIED_REDIRECT_DELAY_MS)])
await router.push('/home')
return
} catch (error) {
if (error instanceof ApiError && error.status === 401) {
state.value = 'noSession'
return
}
state.value = 'invalid'
}
}
async function startVerifying(code: string) {
state.value = 'verifying'
await performVerify(code)
}
async function retryVerifying(code: string) {
state.value = 'noSessionRetrying'
await performVerify(code)
}
function handleLoginError(error: unknown) {
if (error instanceof ApiError && error.status === 403) {
loginAlert.value = wrongCredentialsAlert
password.value = ''
focusPassword()
return
}
if (error instanceof ApiError && error.status === 429) {
loginAlert.value = tooManyAttemptsAlert
retryAfter.start(error.retryAfter ?? 0)
return
}
loginAlert.value = serverErrorAlert
}
function validateLogin() {
usernameError.value = username.value.trim().length < 3 ? 'Use at least 3 characters.' : ''
passwordError.value = password.value.length === 0 ? 'Enter your password.' : ''
return !usernameError.value && !passwordError.value
}
async function onLoginSubmit() {
if (loginSubmitDisabled.value) {
return
}
if (!validateLogin()) {
return
}
loginAlert.value = null
loginSubmitting.value = true
try {
await api.request('/v1/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: username.value, password: password.value }),
})
const code = typeof route.query.c === 'string' ? route.query.c : ''
await retryVerifying(code)
} catch (error) {
handleLoginError(error)
} finally {
loginSubmitting.value = false
}
}
async function cancelAndStartOver() {
cancelAlert.value = null
invalidActionsDisabled.value = true
try {
await api.request('/v1/auth/register', {
method: 'DELETE',
onForbidden: 'passthrough',
})
await router.push('/register')
toast.add(registrationCancelledToast)
} catch {
cancelAlert.value = cancelFailedAlert
} finally {
invalidActionsDisabled.value = false
}
}
async function logOutFromInvalid() {
invalidActionsDisabled.value = true
try {
await api.request('/v1/auth/logout', { method: 'POST' })
} finally {
invalidActionsDisabled.value = false
}
session.clear()
await router.push('/login')
}
const invalidActions = computed(() => [
{
label: 'Cancel registration and start over',
color: 'primary' as const,
variant: 'solid' as const,
disabled: invalidActionsDisabled.value,
onClick: cancelAndStartOver,
},
{
label: 'Log out',
color: 'neutral' as const,
variant: 'outline' as const,
disabled: invalidActionsDisabled.value,
onClick: logOutFromInvalid,
},
])
function goToLogin() {
router.push('/login')
}
const missingCodeActions = [
{
label: 'Go to log in',
color: 'neutral' as const,
variant: 'outline' as const,
onClick: goToLogin,
},
]
onMounted(() => {
const code = typeof route.query.c === 'string' ? route.query.c : ''
if (!code) {
state.value = 'missing'
return
}
startVerifying(code)
})
</script>
<template>
<AuthShell :title="shellTitle" :description="shellDescription">
<template v-if="state === 'invalid' && cancelAlert" #notice>
<UAlert
:color="cancelAlert.tone"
:icon="cancelAlert.icon"
:title="cancelAlert.title"
:description="cancelAlert.description"
variant="soft"
:close="false"
role="alert"
/>
</template>
<template v-else-if="state === 'noSession' && loginAlert" #notice>
<UAlert
:color="loginAlert.tone"
:icon="loginAlert.icon"
:title="loginAlert.title"
:description="loginAlert.description"
variant="soft"
:close="false"
:role="loginAlert.tone === 'error' ? 'alert' : 'status'"
/>
</template>
<template #default="{ controlSize, controlClass, inputClass }">
<div
v-if="state === 'verifying' || state === 'noSessionRetrying'"
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">Verifying your account…</p>
<p class="text-base text-muted">This only takes a moment.</p>
</div>
<ResultPanel
v-else-if="state === 'success'"
tone="success"
icon="i-lucide-shield-check"
title="Your account is verified"
description="Taking you to your dashboard…"
:actions="[]"
/>
<ResultPanel
v-else-if="state === 'invalid'"
tone="error"
icon="i-lucide-link-2-off"
title="This verification link doesn't work"
description="It may have expired (links last 2 hours) or already been used."
:actions="invalidActions"
>
<p class="text-sm text-pretty text-muted">
Cancel your registration and start over to get a new link.
</p>
</ResultPanel>
<ResultPanel
v-else-if="state === 'missing'"
tone="error"
icon="i-lucide-link-2-off"
title="This link is incomplete"
description="The verification code is missing. Open the link from your email again, or copy the full address into your browser."
:actions="missingCodeActions"
/>
<UForm
v-else-if="state === 'noSession'"
:state="{ username, password }"
class="flex flex-col gap-4.5"
@submit="onLoginSubmit"
>
<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>
<UInput
v-model="username"
:highlight="!!usernameError"
placeholder="Your username"
autocomplete="username"
:disabled="loginSubmitDisabled"
variant="outline"
color="primary"
:size="controlSize"
:ui="{ base: inputClass, trailing: 'pe-1' }"
class="w-full"
/>
</UFormField>
<UFormField
label="Password"
name="password"
:error="passwordError || undefined"
:size="controlSize"
>
<template v-if="passwordError" #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>
<UInput
v-model="password"
:highlight="!!passwordError"
:type="passwordShown ? 'text' : 'password'"
autocomplete="current-password"
:disabled="loginSubmitDisabled"
variant="outline"
color="primary"
:size="controlSize"
:ui="{
base: `${inputClass} ${passwordShown ? '' : 'tracking-[2px]'}`,
trailing: 'pe-1',
}"
class="w-full"
>
<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="loginSubmitting"
:disabled="loginSubmitDisabled"
>
{{ loginSubmitLabel }}
</UButton>
</UForm>
</template>
</AuthShell>
</template>