Refactor to use recovery code on TOTP as separate form.

This commit is contained in:
Bradley Shellnut 2024-07-14 20:59:51 -07:00
parent 16ba22c76d
commit 091bcd2e88
5 changed files with 104 additions and 80 deletions

View file

@ -25,5 +25,9 @@ export const signInSchema = z.object({
});
export const totpSchema = z.object({
totpToken: z.string().trim().min(6).max(10),
totpToken: z.string().trim().min(6).max(6),
});
export const recoveryCodeSchema = z.object({
recoveryCode: z.string().trim().min(10).max(10),
});

View file

@ -1,5 +1,5 @@
import { fail, error, type Actions } from '@sveltejs/kit';
import { eq } from 'drizzle-orm';
import { eq, or } from 'drizzle-orm';
import { Argon2id } from 'oslo/password';
import { zod } from 'sveltekit-superforms/adapters';
import { setError, superValidate } from 'sveltekit-superforms/server';
@ -58,7 +58,7 @@ export const actions: Actions = {
let session;
let sessionCookie;
const user: Users | undefined = await db.query.users.findFirst({
where: eq(users.username, form.data.username),
where: or(eq(users.username, form.data.username), eq(users.email, form.data.username)),
});
if (!user) {

View file

@ -41,15 +41,29 @@
</svelte:head>
<div class="login">
<form method="POST" use:enhance>
<h2
<h2
class="scroll-m-20 border-b pb-2 text-3xl font-semibold tracking-tight transition-colors first:mt-0"
>
Log into your account
</h2>
>
Log into your account
</h2>
{@render usernamePasswordForm()}
<p class="px-8 text-center text-sm text-muted-foreground">
By clicking continue, you agree to our
<a href="/terms" class="underline underline-offset-4 hover:text-primary">
Terms of Use
</a>
and
<a href="/privacy" class="underline underline-offset-4 hover:text-primary">
Privacy Policy
</a>.
</p>
</div>
{#snippet usernamePasswordForm()}
<form method="POST" use:enhance>
<Form.Field form={superLoginForm} name="username">
<Form.Control let:attrs>
<Form.Label for="username">Username</Form.Label>
<Form.Label for="username">Username/Email</Form.Label>
<Input {...attrs} autocomplete="username" bind:value={$loginForm.username} />
</Form.Control>
<Form.FieldErrors />
@ -62,22 +76,13 @@
<Form.FieldErrors />
</Form.Field>
<Form.Button>Login</Form.Button>
<p class="px-8 text-center text-sm text-muted-foreground">
By clicking continue, you agree to our
<a href="/terms" class="underline underline-offset-4 hover:text-primary">
Terms of Use
</a>
and
<a href="/privacy" class="underline underline-offset-4 hover:text-primary">
Privacy Policy
</a>.
</p>
</form>
</div>
{/snippet}
<style lang="postcss">
.login {
display: flex;
gap: 1rem;
margin-top: 1.5rem;
flex-direction: column;
justify-content: center;

View file

@ -1,4 +1,4 @@
import { fail, error, type Actions, type Cookies, type RequestEvent } from '@sveltejs/kit';
import { fail, error, type Actions } from '@sveltejs/kit';
import { and, eq } from 'drizzle-orm';
import { Argon2id } from 'oslo/password';
import { decodeHex } from 'oslo/encoding';
@ -9,7 +9,7 @@ import { redirect } from 'sveltekit-flash-message/server';
import { RateLimiter } from 'sveltekit-rate-limiter/server';
import db from '../../../db';
import { lucia } from '$lib/server/auth';
import { totpSchema } from '$lib/validations/auth';
import { recoveryCodeSchema, totpSchema } from '$lib/validations/auth';
import { users, twoFactor, recoveryCodes } from '$db/schema';
import type { PageServerLoad } from './$types';
import { notSignedInMessage } from '$lib/flashMessages';
@ -33,7 +33,10 @@ export const load: PageServerLoad = async (event) => {
});
if (!twoFactorDetails || !twoFactorDetails.enabled) {
const message = { type: 'error', message: 'Two factor authentication is not enabled' } as const;
const message = {
type: 'error',
message: 'Two factor authentication is not enabled',
} as const;
redirect(302, '/login', message, event);
}
@ -51,7 +54,11 @@ export const load: PageServerLoad = async (event) => {
// Check if two factor started less than TWO_FACTOR_TIMEOUT
const totpElapsed = totpTimeElapsed(twoFactorInitiatedTime);
if (totpElapsed) {
console.log('Time elapsed was more than TWO_FACTOR_TIMEOUT', timeElapsed, env.TWO_FACTOR_TIMEOUT);
console.log(
'Time elapsed was more than TWO_FACTOR_TIMEOUT',
totpElapsed,
env.TWO_FACTOR_TIMEOUT,
);
await lucia.invalidateSession(session!.id!);
const sessionCookie = lucia.createBlankSessionCookie();
cookies.set(sessionCookie.name, sessionCookie.value, {
@ -67,20 +74,15 @@ export const load: PageServerLoad = async (event) => {
console.log('session', session);
console.log('isTwoFactorAuthenticated', isTwoFactorAuthenticated);
if (
isTwoFactorAuthenticated &&
twoFactorDetails?.enabled &&
twoFactorDetails?.secret !== ''
) {
if (isTwoFactorAuthenticated && twoFactorDetails?.enabled && twoFactorDetails?.secret !== '') {
const message = { type: 'success', message: 'You are already signed in' } as const;
throw redirect('/', message, event);
}
}
const form = await superValidate(event, zod(totpSchema));
return {
form,
totpForm: await superValidate(event, zod(totpSchema)),
recoveryCodeForm: await superValidate(event, zod(recoveryCodeSchema)),
};
};
@ -121,11 +123,7 @@ export const actions: Actions = {
throw redirect(302, '/login', message, event);
}
if (
isTwoFactorAuthenticated &&
twoFactorDetails.enabled &&
twoFactorDetails.secret !== ''
) {
if (isTwoFactorAuthenticated && twoFactorDetails.enabled && twoFactorDetails.secret !== '') {
const message = { type: 'success', message: 'You are already signed in' } as const;
throw redirect('/', message, event);
}
@ -151,7 +149,7 @@ export const actions: Actions = {
});
} else if (twoFactorSecretPopulated && totpToken) {
// Check if two factor started less than TWO_FACTOR_TIMEOUT
const totpElapsed = totpTimeElapsed(twoFactorDetails.initiatedTime);
const totpElapsed = totpTimeElapsed(twoFactorDetails.initiatedTime ?? new Date());
if (totpElapsed) {
await lucia.invalidateSession(session!.id!);
const sessionCookie = lucia.createBlankSessionCookie();
@ -178,6 +176,7 @@ export const actions: Actions = {
const usedRecoveryCode = await checkRecoveryCode(totpToken, dbUser.id);
if (!usedRecoveryCode) {
console.log('invalid TOTP code');
form.data.totpToken = '';
return setError(form, 'totpToken', 'Invalid code.');
}
}

View file

@ -3,20 +3,17 @@
import { superForm } from 'sveltekit-superforms/client';
import * as flashModule from 'sveltekit-flash-message/client';
import { AlertCircle } from "lucide-svelte";
import { signInSchema, totpSchema } from '$lib/validations/auth';
import { recoveryCodeSchema, totpSchema } from '$lib/validations/auth';
import * as Form from '$lib/components/ui/form';
import { Label } from '$components/ui/label';
import { Input } from '$components/ui/input';
import { Button } from '$components/ui/button';
import * as Alert from "$components/ui/alert";
import { boredState } from '$lib/stores/boredState.js';
import PinInput from '$components/pin-input.svelte';
const { data } = $props();
const superTotpForm = superForm(data.form, {
onSubmit: () => boredState.update((n) => ({ ...n, loading: true })),
onResult: () => boredState.update((n) => ({ ...n, loading: false })),
const superTotpForm = superForm(data.totpForm, {
flashMessage: {
module: flashModule,
onError: ({ result, flashMessage }) => {
@ -34,59 +31,78 @@
delayMs: 0,
});
const superRecoveryCodeForm = superForm(data.recoveryCodeForm, {
validators: zodClient(recoveryCodeSchema),
resetForm: false,
flashMessage: {
module: flashModule,
onError: ({ result, flashMessage }) => {
// Error handling for the flash message:
// - result is the ActionResult
// - message is the flash store (not the status message store)
const errorMessage = result.error.message
flashMessage.set({ type: 'error', message: errorMessage });
}
},
syncFlashMessage: false,
taintedMessage: null,
validationMethod: 'oninput',
delayMs: 0,
});
let showRecoveryCode = $state(false);
const { form: totpForm, enhance } = superTotpForm;
const { form: totpFormData, enhance: totpEnhance } = superTotpForm;
const { form: recoveryCodeFormData, enhance: recoveryCodeEnhance } = superRecoveryCodeForm;
</script>
<svelte:head>
<title>Bored Game | Login</title>
</svelte:head>
<div class="login">
<form method="POST" use:enhance>
<h2
class="scroll-m-20 border-b pb-2 text-3xl font-semibold tracking-tight transition-colors first:mt-0"
>
Please enter your {showRecoveryCode ? 'recovery code' : 'TOTP code'}
</h2>
<Form.Field form={superTotpForm} name="totpToken">
<div class="totp">
<h2
class="scroll-m-20 border-b pb-2 text-3xl font-semibold tracking-tight transition-colors first:mt-0"
>
Please enter your {showRecoveryCode ? 'recovery code' : 'TOTP code'}
</h2>
{#if !showRecoveryCode}
{@render totpForm()}
<Button variant="link" class="text-secondary-foreground" on:click={() => showRecoveryCode = true}>Show Recovery Code</Button>
{:else}
{@render recoveryCodeForm()}
<Button variant="link" class="text-secondary-foreground" on:click={() => showRecoveryCode = false}>Show TOTP Code</Button>
{/if}
</div>
{#snippet totpForm()}
<form method="POST" use:totpEnhance>
<Form.Field form={totpFormData} name="totpToken">
<Form.Control let:attrs>
{#if showRecoveryCode}
<Form.Label for="totpToken">Recovery Code</Form.Label>
<Input {...attrs} autocomplete="one-time-code" bind:value={$totpForm.totpToken} />
{:else}
<Form.Label for="totpToken">TOTP Code</Form.Label>
<PinInput {...attrs} bind:value={$totpForm.totpToken} />
{/if}
<Form.Label for="totpToken">TOTP Code</Form.Label>
<PinInput {...attrs} bind:value={$totpFormData.totpToken} />
</Form.Control>
<Form.FieldErrors />
</Form.Field>
<Form.Button>Submit</Form.Button>
</form>
{#if !showRecoveryCode}
<Button variant="link" class="text-secondary-foreground" on:click={() => showRecoveryCode = true}>Show Recovery Code</Button>
{:else}
<Button variant="link" class="text-secondary-foreground" on:click={() => showRecoveryCode = false}>Show TOTP Code</Button>
{/if}
</div>
{/snippet}
{#snippet recoveryCodeForm()}
<form method="POST" use:recoveryCodeEnhance>
<Form.Field form={recoveryCodeFormData} name="recoveryCode">
<Form.Control let:attrs>
<Form.Label for="totpToken">Recovery Code</Form.Label>
<PinInput {...attrs} bind:value={$recoveryCodeFormData.recoveryCode} inputCount={10} />
</Form.Control>
<Form.FieldErrors />
</Form.Field>
<Form.Button>Submit</Form.Button>
</form>
{/snippet}
<style lang="postcss">
.loading {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 101;
display: grid;
place-items: center;
gap: 1rem;
h3 {
color: white;
}
}
.login {
.totp {
display: flex;
margin-top: 1.5rem;
flex-direction: column;