feat: login page T0
This commit is contained in:
1 parent
12faab7f92
commit
001f9f4774
5 files changed
+824
-2
No files matched your search
+264
-2
@@ -1,9 +1,271 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onMounted, ref } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import AuthShell from '@/components/AuthShell.vue'
|
||||
import { ApiError, useApi } from '@/composables/useApi'
|
||||
import { useRetryAfter } from '@/composables/useRetryAfter'
|
||||
import { useSessionStore } from '@/stores/session'
|
||||
|
||||
interface AlertState {
|
||||
tone: 'error' | 'info' | 'success'
|
||||
icon: string
|
||||
title: string
|
||||
description: string
|
||||
closable: boolean
|
||||
}
|
||||
|
||||
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.',
|
||||
closable: false,
|
||||
}
|
||||
|
||||
const tooManyAttemptsAlert: AlertState = {
|
||||
tone: 'info',
|
||||
icon: 'i-lucide-timer',
|
||||
title: 'Too many attempts',
|
||||
description: 'For your security, wait a moment before trying again.',
|
||||
closable: false,
|
||||
}
|
||||
|
||||
const serverErrorAlert: AlertState = {
|
||||
tone: 'error',
|
||||
icon: 'i-lucide-circle-x',
|
||||
title: "Couldn't reach RenewCMS",
|
||||
description: 'Check your connection and try again.',
|
||||
closable: false,
|
||||
}
|
||||
|
||||
const sessionExpiredAlert: AlertState = {
|
||||
tone: 'info',
|
||||
icon: 'i-lucide-clock',
|
||||
title: 'Your session expired',
|
||||
description:
|
||||
'Log in again to pick up where you left off. Unsaved changes are kept on this device.',
|
||||
closable: true,
|
||||
}
|
||||
|
||||
const passwordChangedAlert: AlertState = {
|
||||
tone: 'success',
|
||||
icon: 'i-lucide-circle-check',
|
||||
title: 'Password changed',
|
||||
description: 'Log in with your new password.',
|
||||
closable: true,
|
||||
}
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const api = useApi()
|
||||
const session = useSessionStore()
|
||||
const retryAfter = useRetryAfter()
|
||||
|
||||
const registrationOpen = ref(false)
|
||||
const username = ref('')
|
||||
const password = ref('')
|
||||
const usernameError = ref('')
|
||||
const passwordError = ref('')
|
||||
const submitting = ref(false)
|
||||
const passwordShown = ref(false)
|
||||
const formEl = ref<HTMLFormElement | null>(null)
|
||||
|
||||
const initialReason = typeof route.query.reason === 'string' ? route.query.reason : null
|
||||
|
||||
const alert = ref<AlertState | null>(
|
||||
initialReason === 'expired'
|
||||
? sessionExpiredAlert
|
||||
: initialReason === 'password-changed'
|
||||
? passwordChangedAlert
|
||||
: null,
|
||||
)
|
||||
|
||||
const alertRole = computed(() => (alert.value?.tone === 'error' ? 'alert' : 'status'))
|
||||
|
||||
const submitLabel = computed(() => {
|
||||
if (submitting.value) {
|
||||
return 'Logging in…'
|
||||
}
|
||||
if (retryAfter.active.value) {
|
||||
return `Try again in ${retryAfter.formatted.value}`
|
||||
}
|
||||
return 'Log in'
|
||||
})
|
||||
|
||||
const submitDisabled = computed(() => submitting.value || retryAfter.active.value)
|
||||
|
||||
function focusField(selector: string) {
|
||||
nextTick(() => {
|
||||
formEl.value?.querySelector<HTMLInputElement>(selector)?.focus()
|
||||
})
|
||||
}
|
||||
|
||||
function focusPassword() {
|
||||
focusField('input[autocomplete="current-password"]')
|
||||
}
|
||||
|
||||
function focusUsername() {
|
||||
focusField('input[placeholder="Your username"]')
|
||||
}
|
||||
|
||||
function focusFirstInvalid() {
|
||||
if (usernameError.value) {
|
||||
focusUsername()
|
||||
return
|
||||
}
|
||||
if (passwordError.value) {
|
||||
focusPassword()
|
||||
}
|
||||
}
|
||||
|
||||
function validate() {
|
||||
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 afterLoginSuccess() {
|
||||
await session.retry()
|
||||
|
||||
const redirect = typeof route.query.redirect === 'string' ? route.query.redirect : null
|
||||
if (redirect) {
|
||||
await router.push(redirect)
|
||||
return
|
||||
}
|
||||
|
||||
if (session.session?.verified) {
|
||||
await router.push('/home')
|
||||
return
|
||||
}
|
||||
|
||||
await router.push('/register/pending')
|
||||
}
|
||||
|
||||
function handleLoginError(error: unknown) {
|
||||
if (error instanceof ApiError && error.status === 403) {
|
||||
alert.value = wrongCredentialsAlert
|
||||
password.value = ''
|
||||
focusPassword()
|
||||
return
|
||||
}
|
||||
|
||||
if (error instanceof ApiError && error.status === 429) {
|
||||
alert.value = tooManyAttemptsAlert
|
||||
retryAfter.start(error.retryAfter ?? 0)
|
||||
return
|
||||
}
|
||||
|
||||
alert.value = serverErrorAlert
|
||||
}
|
||||
|
||||
async function onSubmit() {
|
||||
if (submitDisabled.value) {
|
||||
return
|
||||
}
|
||||
|
||||
if (!validate()) {
|
||||
focusFirstInvalid()
|
||||
return
|
||||
}
|
||||
|
||||
submitting.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 }),
|
||||
})
|
||||
await afterLoginSuccess()
|
||||
} catch (error) {
|
||||
handleLoginError(error)
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
if (initialReason === 'expired') {
|
||||
focusPassword()
|
||||
}
|
||||
|
||||
try {
|
||||
const status = await api.request<{ open: boolean }>('/v1/auth/registration')
|
||||
registrationOpen.value = status.open
|
||||
} catch {
|
||||
registrationOpen.value = false
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AuthShell title="Log in">
|
||||
<p>Log in placeholder.</p>
|
||||
<AuthShell title="Log in" description="Welcome back. Log in to manage your articles.">
|
||||
<template v-if="alert" #notice>
|
||||
<UAlert
|
||||
:color="alert.tone"
|
||||
:icon="alert.icon"
|
||||
:title="alert.title"
|
||||
:description="alert.description"
|
||||
variant="soft"
|
||||
:close="alert.closable"
|
||||
:role="alertRole"
|
||||
@close="alert = null"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<form ref="formEl" class="flex flex-col gap-4" @submit.prevent="onSubmit">
|
||||
<UFormField label="Username" name="username" :error="usernameError">
|
||||
<UInput
|
||||
v-model="username"
|
||||
placeholder="Your username"
|
||||
autocomplete="username"
|
||||
:disabled="submitting"
|
||||
class="w-full"
|
||||
/>
|
||||
</UFormField>
|
||||
|
||||
<UFormField name="password" :error="passwordError">
|
||||
<template #label>
|
||||
<div class="flex w-full items-center justify-between">
|
||||
<span>Password</span>
|
||||
<RouterLink to="/register/reset/request" class="text-primary text-sm">
|
||||
Forgot password?
|
||||
</RouterLink>
|
||||
</div>
|
||||
</template>
|
||||
<UInput
|
||||
v-model="password"
|
||||
:type="passwordShown ? 'text' : 'password'"
|
||||
autocomplete="current-password"
|
||||
:disabled="submitting"
|
||||
class="w-full"
|
||||
>
|
||||
<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 :loading="submitting" :disabled="submitDisabled">
|
||||
{{ submitLabel }}
|
||||
</UButton>
|
||||
</form>
|
||||
|
||||
<template v-if="registrationOpen" #footer>
|
||||
<p>
|
||||
First time here?
|
||||
<RouterLink to="/register" class="text-primary"
|
||||
>Create the owner account</RouterLink
|
||||
>
|
||||
</p>
|
||||
</template>
|
||||
</AuthShell>
|
||||
</template>
|
||||
@@ -0,0 +1,306 @@
|
||||
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 LoginView from '../LoginView.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 mountLogin(
|
||||
path: string,
|
||||
handlers: Record<string, () => Response | Promise<Response>>,
|
||||
) {
|
||||
setActivePinia(createPinia())
|
||||
global.fetch = fetchRouter({
|
||||
'GET /v1/auth/registration': () => mockResponse(200, { open: false }),
|
||||
...handlers,
|
||||
}) as unknown as typeof fetch
|
||||
await router.push(path)
|
||||
const wrapper = mount(LoginView, {
|
||||
attachTo: document.body,
|
||||
global: {
|
||||
plugins: [router, uiPlugin],
|
||||
},
|
||||
})
|
||||
currentWrapper = wrapper
|
||||
await flushPromises()
|
||||
return wrapper
|
||||
}
|
||||
|
||||
async function fillAndSubmit(
|
||||
wrapper: Awaited<ReturnType<typeof mountLogin>>,
|
||||
username: string,
|
||||
password: string,
|
||||
) {
|
||||
await wrapper.find('input[placeholder="Your username"]').setValue(username)
|
||||
await wrapper.find('input[autocomplete="current-password"]').setValue(password)
|
||||
await wrapper.find('form').trigger('submit')
|
||||
await flushPromises()
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
currentWrapper?.unmount()
|
||||
currentWrapper = null
|
||||
await router.push('/login')
|
||||
})
|
||||
|
||||
describe('Default — registration is closed', () => {
|
||||
it('renders the default state with no create-account footer link', async () => {
|
||||
const wrapper = await mountLogin('/login', {
|
||||
'GET /v1/auth/registration': () => mockResponse(200, { open: false }),
|
||||
})
|
||||
|
||||
expect(wrapper.find('h1').text()).toBe('Log in')
|
||||
expect(wrapper.text()).toContain('Welcome back. Log in to manage your articles.')
|
||||
|
||||
const usernameInput = wrapper.find('input[placeholder="Your username"]')
|
||||
expect((usernameInput.element as HTMLInputElement).value).toBe('')
|
||||
|
||||
const passwordInput = wrapper.find('input[autocomplete="current-password"]')
|
||||
expect((passwordInput.element as HTMLInputElement).value).toBe('')
|
||||
|
||||
expect(wrapper.find('button[type="submit"]').text()).toBe('Log in')
|
||||
expect(wrapper.text()).not.toContain('Create the owner account')
|
||||
})
|
||||
})
|
||||
|
||||
describe('Fresh install — registration is open', () => {
|
||||
it('renders the same fields plus the create-account footer link', async () => {
|
||||
const wrapper = await mountLogin('/login', {
|
||||
'GET /v1/auth/registration': () => mockResponse(200, { open: true }),
|
||||
})
|
||||
|
||||
expect(wrapper.find('h1').text()).toBe('Log in')
|
||||
expect(wrapper.text()).toContain('First time here?')
|
||||
expect(wrapper.text()).toContain('Create the owner account')
|
||||
})
|
||||
})
|
||||
|
||||
describe('Validation errors — nothing is sent for a short username and an empty password', () => {
|
||||
it('shows both field errors and never calls the login endpoint', async () => {
|
||||
const login = vi.fn(() => mockResponse(200))
|
||||
const wrapper = await mountLogin('/login', {
|
||||
'POST /v1/auth/login': login,
|
||||
})
|
||||
|
||||
await wrapper.find('input[placeholder="Your username"]').setValue('ma')
|
||||
await wrapper.find('form').trigger('submit')
|
||||
await flushPromises()
|
||||
|
||||
expect(login).not.toHaveBeenCalled()
|
||||
expect(wrapper.text()).toContain('Use at least 3 characters.')
|
||||
expect(wrapper.text()).toContain('Enter your password.')
|
||||
})
|
||||
})
|
||||
|
||||
describe('Submitting — fields and button are disabled while the request is in flight', () => {
|
||||
it('disables the fields and shows the loading label', async () => {
|
||||
let resolveLogin: (() => void) | null = null
|
||||
const wrapper = await mountLogin('/login', {
|
||||
'POST /v1/auth/login': () =>
|
||||
new Promise((resolve) => {
|
||||
resolveLogin = () => resolve(mockResponse(200))
|
||||
}),
|
||||
})
|
||||
|
||||
await wrapper.find('input[placeholder="Your username"]').setValue('marta')
|
||||
await wrapper.find('input[autocomplete="current-password"]').setValue('limewash2026')
|
||||
await wrapper.find('form').trigger('submit')
|
||||
await flushPromises()
|
||||
|
||||
expect(
|
||||
(wrapper.find('input[placeholder="Your username"]').element as HTMLInputElement)
|
||||
.disabled,
|
||||
).toBe(true)
|
||||
expect(
|
||||
(wrapper.find('input[autocomplete="current-password"]').element as HTMLInputElement)
|
||||
.disabled,
|
||||
).toBe(true)
|
||||
const submitButton = wrapper.find('button[type="submit"]')
|
||||
expect(submitButton.text()).toBe('Logging in…')
|
||||
expect((submitButton.element as HTMLButtonElement).disabled).toBe(true)
|
||||
|
||||
resolveLogin?.()
|
||||
await flushPromises()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Wrong credentials — the password is cleared and focused', () => {
|
||||
it('shows the mismatch alert, keeps the username, clears and focuses the password', async () => {
|
||||
const wrapper = await mountLogin('/login', {
|
||||
'POST /v1/auth/login': () => mockResponse(403),
|
||||
})
|
||||
|
||||
await fillAndSubmit(wrapper, 'marta', 'wrong-password')
|
||||
|
||||
expect(wrapper.text()).toContain("That username and password don't match")
|
||||
expect(wrapper.text()).toContain('Check both and try again. Passwords are case-sensitive.')
|
||||
|
||||
const usernameInput = wrapper.find('input[placeholder="Your username"]')
|
||||
expect((usernameInput.element as HTMLInputElement).value).toBe('marta')
|
||||
|
||||
const passwordInput = wrapper.find('input[autocomplete="current-password"]')
|
||||
expect((passwordInput.element as HTMLInputElement).value).toBe('')
|
||||
expect(passwordInput.element).toBe(document.activeElement)
|
||||
|
||||
const submitButton = wrapper.find('button[type="submit"]')
|
||||
expect(submitButton.text()).toBe('Log in')
|
||||
expect((submitButton.element as HTMLButtonElement).disabled).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Too many attempts — the button is disabled with a live countdown', () => {
|
||||
it('counts down from the Retry-After value and re-enables at zero', async () => {
|
||||
vi.useFakeTimers()
|
||||
const wrapper = await mountLogin('/login', {
|
||||
'POST /v1/auth/login': () => mockResponse(429, null, { 'Retry-After': '42' }),
|
||||
})
|
||||
|
||||
await fillAndSubmit(wrapper, 'marta', 'limewash')
|
||||
|
||||
expect(wrapper.text()).toContain('Too many attempts')
|
||||
expect(wrapper.text()).toContain('For your security, wait a moment before trying again.')
|
||||
|
||||
expect(
|
||||
(wrapper.find('input[placeholder="Your username"]').element as HTMLInputElement).value,
|
||||
).toBe('marta')
|
||||
expect(
|
||||
(wrapper.find('input[autocomplete="current-password"]').element as HTMLInputElement)
|
||||
.value,
|
||||
).toBe('limewash')
|
||||
|
||||
const button = wrapper.find('button[type="submit"]')
|
||||
expect(button.text()).toBe('Try again in 0:42')
|
||||
expect((button.element as HTMLButtonElement).disabled).toBe(true)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(42000)
|
||||
await flushPromises()
|
||||
|
||||
expect(wrapper.find('button[type="submit"]').text()).toBe('Log in')
|
||||
expect((wrapper.find('button[type="submit"]').element as HTMLButtonElement).disabled).toBe(
|
||||
false,
|
||||
)
|
||||
vi.useRealTimers()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Session expired — redirected from a 401 elsewhere', () => {
|
||||
it('shows the session-expired alert and focuses the password field', async () => {
|
||||
const wrapper = await mountLogin('/login?redirect=/article/12/edit&reason=expired', {})
|
||||
|
||||
expect(wrapper.text()).toContain('Your session expired')
|
||||
expect(wrapper.text()).toContain(
|
||||
'Log in again to pick up where you left off. Unsaved changes are kept on this device.',
|
||||
)
|
||||
|
||||
const passwordInput = wrapper.find('input[autocomplete="current-password"]')
|
||||
expect(passwordInput.element).toBe(document.activeElement)
|
||||
expect(wrapper.find('button[type="submit"]').text()).toBe('Log in')
|
||||
})
|
||||
})
|
||||
|
||||
describe('Password changed — arrived from a successful reset', () => {
|
||||
it('shows the success alert and the untouched fields', async () => {
|
||||
const wrapper = await mountLogin('/login?reason=password-changed', {})
|
||||
|
||||
expect(wrapper.text()).toContain('Password changed')
|
||||
expect(wrapper.text()).toContain('Log in with your new password.')
|
||||
|
||||
const usernameInput = wrapper.find('input[placeholder="Your username"]')
|
||||
expect((usernameInput.element as HTMLInputElement).value).toBe('')
|
||||
expect(wrapper.find('button[type="submit"]').text()).toBe('Log in')
|
||||
})
|
||||
})
|
||||
|
||||
describe('Server or network error — the fields keep their values', () => {
|
||||
it.each([
|
||||
{ name: 'a 500 response', password: 'limewash2026', handler: () => mockResponse(500) },
|
||||
{
|
||||
name: 'a network failure',
|
||||
password: 'limewash2026',
|
||||
handler: () => Promise.reject(new TypeError('Failed to fetch')),
|
||||
},
|
||||
{
|
||||
name: 'a 400 response under the server minimum',
|
||||
password: 'short1',
|
||||
handler: () => mockResponse(400),
|
||||
},
|
||||
])(
|
||||
'shows the network/server error alert and keeps the fields for $name',
|
||||
async ({ password, handler }) => {
|
||||
const login = vi.fn(handler)
|
||||
const wrapper = await mountLogin('/login', {
|
||||
'POST /v1/auth/login': login,
|
||||
})
|
||||
|
||||
await fillAndSubmit(wrapper, 'marta', password)
|
||||
|
||||
expect(login).toHaveBeenCalled()
|
||||
expect(wrapper.text()).toContain("Couldn't reach RenewCMS")
|
||||
expect(wrapper.text()).toContain('Check your connection and try again.')
|
||||
|
||||
expect(
|
||||
(wrapper.find('input[placeholder="Your username"]').element as HTMLInputElement)
|
||||
.value,
|
||||
).toBe('marta')
|
||||
expect(
|
||||
(wrapper.find('input[autocomplete="current-password"]').element as HTMLInputElement)
|
||||
.value,
|
||||
).toBe(password)
|
||||
|
||||
const submitButton = wrapper.find('button[type="submit"]')
|
||||
expect(submitButton.text()).toBe('Log in')
|
||||
expect((submitButton.element as HTMLButtonElement).disabled).toBe(false)
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
describe('A successful log in navigates to the right destination', () => {
|
||||
it.each([
|
||||
{ path: '/login', verified: true, destination: '/home' },
|
||||
{ path: '/login', verified: false, destination: '/register/pending' },
|
||||
{
|
||||
path: '/login?redirect=/article/12/edit',
|
||||
verified: true,
|
||||
destination: '/article/12/edit',
|
||||
},
|
||||
])(
|
||||
'navigates to $destination for path $path and verified $verified',
|
||||
async ({ path, verified, destination }) => {
|
||||
const wrapper = await mountLogin(path, {
|
||||
'POST /v1/auth/login': () => mockResponse(200),
|
||||
'GET /v1/auth/me': () => mockResponse(200, { is_verified: verified }),
|
||||
})
|
||||
|
||||
await fillAndSubmit(wrapper, 'marta', 'limewash2026')
|
||||
|
||||
await vi.waitFor(() => expect(router.currentRoute.value.path).toBe(destination))
|
||||
},
|
||||
)
|
||||
})
|
||||
Reference in new issue
Block a user