Implement TOTP 2FA modal; add QR code generation and recovery codes management

This commit is contained in:
Sean Morley
2024-12-13 10:48:18 -05:00
parent 7b7db1c530
commit 1b54f8ed69
6 changed files with 387 additions and 7 deletions

View File

@@ -0,0 +1,191 @@
<script lang="ts">
import { addToast } from '$lib/toasts';
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
import { onMount } from 'svelte';
let modal: HTMLDialogElement;
// @ts-ignore
import QRCode from 'qrcode';
import { t } from 'svelte-i18n';
import type { User } from '$lib/types';
export let user: User | null = null;
let secret: string | null = null;
let qrCodeDataUrl: string | null = null;
let totpUrl: string | null = null;
let first_code: string = '';
let recovery_codes: string[] = [];
export let is_enabled: boolean;
let reauthError: boolean = false;
onMount(() => {
modal = document.getElementById('my_modal_1') as HTMLDialogElement;
if (modal) {
modal.showModal();
}
fetchSetupInfo();
console.log(secret);
});
async function generateQRCode(secret: string | null) {
try {
if (secret) {
qrCodeDataUrl = await QRCode.toDataURL(secret);
}
} catch (error) {
console.error('Error generating QR code:', error);
}
}
async function fetchSetupInfo() {
const res = await fetch('/_allauth/browser/v1/account/authenticators/totp', {
method: 'GET'
});
const data = await res.json();
if (res.status == 404) {
secret = data.meta.secret;
totpUrl = `otpauth://totp/AdventureLog:${user?.username}?secret=${secret}&issuer=AdventureLog`;
generateQRCode(totpUrl);
} else if (res.ok) {
close();
} else {
addToast('error', $t('settings.generic_error'));
}
}
async function sendTotp() {
console.log('sending totp');
let sessionid = document.cookie
.split('; ')
.find((row) => row.startsWith('sessionid'))
?.split('=')[1];
const res = await fetch('/_allauth/browser/v1/account/authenticators/totp', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Cookie: `sessionid=${sessionid}`
},
body: JSON.stringify({
code: first_code
}),
credentials: 'include'
});
console.log(res);
if (res.ok) {
addToast('success', '2FA enabled');
is_enabled = true;
getRecoveryCodes();
} else {
if (res.status == 401) {
reauthError = true;
}
addToast('error', $t('settings.generic_error'));
}
}
async function getRecoveryCodes() {
console.log('getting recovery codes');
const res = await fetch('/_allauth/browser/v1/account/authenticators/recovery-codes', {
method: 'GET'
});
if (res.ok) {
let data = await res.json();
recovery_codes = data.data.unused_codes;
} else {
addToast('error', $t('settings.generic_error'));
}
}
function close() {
dispatch('close');
}
function handleKeydown(event: KeyboardEvent) {
if (event.key === 'Escape') {
dispatch('close');
}
}
function copyToClipboard(copyText: string | null) {
if (copyText) {
navigator.clipboard.writeText(copyText).then(
() => {
addToast('success', $t('adventures.copied_to_clipboard'));
},
() => {
addToast('error', $t('adventures.copy_failed'));
}
);
}
}
</script>
<dialog id="my_modal_1" class="modal">
<!-- svelte-ignore a11y-no-noninteractive-element-interactions -->
<!-- svelte-ignore a11y-no-noninteractive-tabindex -->
<div class="modal-box" role="dialog" on:keydown={handleKeydown} tabindex="0">
<h3 class="font-bold text-lg">Enable 2FA</h3>
{#if qrCodeDataUrl}
<div class="mb-4 flex items-center justify-center">
<img src={qrCodeDataUrl} alt="QR Code" class="w-64 h-64" />
</div>
{/if}
<div class="flex items-center justify-center mb-6">
{#if secret}
<div class="flex items-center">
<input
type="text"
placeholder={secret}
class="input input-bordered w-full max-w-xs"
readonly
/>
<button class="btn btn-primary ml-2" on:click={() => copyToClipboard(secret)}>Copy</button
>
</div>
{/if}
</div>
<input
type="text"
placeholder="Authenticator Code"
class="input input-bordered w-full max-w-xs"
bind:value={first_code}
/>
<div class="recovery-codes-container">
{#if recovery_codes.length > 0}
<h3 class="mt-4 text-center font-bold text-lg">Recovery Codes</h3>
<p class="text-center text-lg mb-2">
These are your recovery codes. Keep them safe. You will not be able to see them again.
</p>
<button
class="btn btn-primary ml-2"
on:click={() => copyToClipboard(recovery_codes.join(', '))}>Copy</button
>
{/if}
<div class="recovery-codes-grid flex flex-wrap">
{#each recovery_codes as code}
<div
class="recovery-code-item flex items-center justify-center m-2 w-full sm:w-1/2 md:w-1/3 lg:w-1/4"
>
<input type="text" value={code} class="input input-bordered w-full" readonly />
</div>
{/each}
</div>
</div>
{#if reauthError}
<div class="alert alert-error mt-4">
Please logout and back in to refresh your session and try again.
</div>
{/if}
{#if !is_enabled}
<button class="btn btn-primary mt-4" on:click={sendTotp}>Enable 2FA</button>
{/if}
<button class="btn btn-primary mt-4" on:click={close}>{$t('about.close')}</button>
</div>
</dialog>

View File

@@ -211,6 +211,8 @@
"day": "Day",
"itineary_by_date": "Itinerary by Date",
"nothing_planned": "Nothing planned for this day. Enjoy the journey!",
"copied_to_clipboard": "Copied to clipboard!",
"copy_failed": "Copy failed",
"days": "days",
"activities": {
"general": "General 🌍",

View File

@@ -54,7 +54,7 @@ export const load: PageServerLoad = async (event) => {
}
);
let mfaAuthenticatorResponse = (await mfaAuthenticatorFetch.json()) as MFAAuthenticatorResponse;
let authenticators = mfaAuthenticatorResponse.data;
let authenticators = (mfaAuthenticatorResponse.data.length > 0) as boolean;
return {
props: {

View File

@@ -6,6 +6,7 @@
import { onMount } from 'svelte';
import { browser } from '$app/environment';
import { t } from 'svelte-i18n';
import TotpModal from '$lib/components/TOTPModal.svelte';
export let data;
let user: User;
@@ -17,6 +18,8 @@
let new_email: string = '';
let is2FAModalOpen: boolean = false;
onMount(async () => {
if (browser) {
const queryParams = new URLSearchParams($page.url.search);
@@ -124,8 +127,31 @@
addToast('error', $t('settings.email_set_primary_error'));
}
}
async function disableMfa() {
const res = await fetch('/_allauth/browser/v1/account/authenticators/totp', {
method: 'DELETE'
});
if (res.ok) {
addToast('success', '2FA disabled');
data.props.authenticators = false;
} else {
if (res.status == 401) {
addToast('error', 'Logout and back in to refresh your session and try again.');
}
addToast('error', $t('settings.generic_error'));
}
}
</script>
{#if is2FAModalOpen}
<TotpModal
user={data.user}
on:close={() => (is2FAModalOpen = false)}
bind:is_enabled={data.props.authenticators}
/>
{/if}
<h1 class="text-center font-extrabold text-4xl mb-6">{$t('settings.settings_page')}</h1>
<h1 class="text-center font-extrabold text-xl">{$t('settings.account_settings')}</h1>
@@ -284,14 +310,14 @@
<div class="flex justify-center mb-4">
<div>
{#if data.props.authenticators.length === 0}
{#if !data.props.authenticators}
<p>MFA not enabled</p>
<button class="btn btn-primary mt-2" on:click={() => (is2FAModalOpen = true)}
>Enable MFA</button
>
{:else}
<button class="btn btn-warning mt-2" on:click={disableMfa}>Disable MFA</button>
{/if}
{#each data.props.authenticators as authenticator}
<p class="mb-2">
{authenticator.type} - {authenticator.created_at}
</p>
{/each}
</div>
</div>