fix: load turnstile script in layout and explicitly render

chore: npm run format + lint
This commit is contained in:
2026-01-04 09:22:27 -05:00
parent 24b25c2291
commit 2c24af5ac9
11 changed files with 109 additions and 91 deletions
+18
View File
@@ -8,6 +8,24 @@ declare global {
// interface PageState {}
// interface Platform {}
}
interface Window {
turnstile?: {
getResponse: () => string | null;
render: (container: string | HTMLElement, options?: Record<string, unknown>) => string;
reset: (widgetId?: string) => void;
remove: (widgetId?: string) => void;
};
turnstileLoaded?: () => void;
}
var turnstile:
| {
getResponse: () => string | null;
render: (container: string | HTMLElement, options?: Record<string, unknown>) => string;
reset: (widgetId?: string) => void;
remove: (widgetId?: string) => void;
}
| undefined;
var turnstileLoaded: (() => void) | undefined;
}
export {};
@@ -2,10 +2,10 @@
import { user } from '$lib/stores/user';
import { resolve } from '$app/paths';
import { page } from '$app/state';
import { clearTokens } from '$lib/utils/auth';
function logout() {
localStorage.removeItem('token');
localStorage.removeItem('refreshToken');
clearTokens();
user.set(null);
window.location.href = '/';
}
@@ -0,0 +1,11 @@
import type { LayoutServerLoad } from './$types';
export const load: LayoutServerLoad = async ({ fetch }) => {
try {
const res = await fetch('/api/auth/info');
const options = await res.json();
return { options };
} catch {
return { options: null };
}
};
@@ -5,9 +5,16 @@
import Navbar from '$lib/components/Navbar.svelte';
import { user } from '$lib/stores/user';
import { startTokenRefreshInterval, getToken, refreshTokenIfNeeded } from '$lib/utils/auth';
import { page } from '$app/state';
import type { LayoutData } from './$types';
export let data: LayoutData;
if (typeof window !== 'undefined') {
startTokenRefreshInterval();
window.turnstileLoaded = () => {
window.dispatchEvent(new CustomEvent('turnstile:loaded'));
};
}
onMount(async () => {
@@ -29,6 +36,13 @@
<svelte:head>
<link rel="icon" href={favicon} />
{#if data.options?.cf_turnstile_site_key && (page.url.pathname === '/login' || page.url.pathname === '/register')}
<script
src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit&onload=turnstileLoaded"
async
defer
></script>
{/if}
</svelte:head>
<Navbar />
@@ -1,5 +1,5 @@
import { json } from '@sveltejs/kit';
export const GET = () => {
return json({ status: 'ok' });
return json({ status: 'ok' });
};
@@ -1,11 +0,0 @@
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ fetch }) => {
try {
const res = await fetch('/api/auth/info');
const options = await res.json();
return { options };
} catch {
return { options: null };
}
};
+26 -14
View File
@@ -1,6 +1,7 @@
<script lang="ts">
import { resolve } from '$app/paths';
import { setTokens, startTokenRefreshInterval } from '$lib/utils/auth';
import { onMount } from 'svelte';
import type { PageData } from './$types';
let username = '';
@@ -8,14 +9,35 @@
let error = '';
export let data: PageData;
onMount(() => {
const render = () => {
if (window.turnstile && data.options?.cf_turnstile_site_key) {
window.turnstile.render('.cf-turnstile', {
sitekey: data.options.cf_turnstile_site_key,
theme: 'dark'
});
}
};
if (window.turnstile) {
render();
} else {
window.addEventListener('turnstile:loaded', render, { once: true });
}
return () => {
window.removeEventListener('turnstile:loaded', render);
};
});
async function login() {
const body: { username: string; password: string; token?: string } = {
username,
password
};
if (data.options?.cf_turnstile_site_key && (window as any).turnstile) {
const token = (window as any).turnstile.getResponse();
if (data.options?.cf_turnstile_site_key && window.turnstile) {
const token = window.turnstile.getResponse();
if (token) {
body.token = token;
}
@@ -45,12 +67,6 @@
}
</script>
<svelte:head>
{#if data.options?.cf_turnstile_site_key}
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
{/if}
</svelte:head>
<main
class="flex min-h-screen w-full flex-col items-center justify-center bg-neutral-950 text-white"
>
@@ -75,16 +91,12 @@
/>
{#if data.options?.cf_turnstile_site_key}
<div class="flex w-full justify-center">
<div
class="cf-turnstile"
data-sitekey={data.options.cf_turnstile_site_key}
data-theme="dark"
></div>
<div class="cf-turnstile"></div>
</div>
{/if}
<button
type="submit"
class="w-full rounded bg-neutral-700 px-4 py-2 font-semibold text-white transition-colors duration-200 hover:bg-neutral-800 active:bg-neutral-900"
class="w-full cursor-pointer rounded bg-neutral-700 px-4 py-2 font-semibold text-white transition-colors duration-200 hover:bg-neutral-800 active:bg-neutral-900"
>
Login
</button>
@@ -1,11 +0,0 @@
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ fetch }) => {
try {
const res = await fetch('/api/auth/info');
const options = await res.json();
return { options };
} catch {
return { options: null };
}
};
@@ -4,6 +4,7 @@
import { Check, X } from '@lucide/svelte';
import { slide, fade } from 'svelte/transition';
import { resolve } from '$app/paths';
import { onMount } from 'svelte';
import type { PageData } from './$types';
let username = '';
@@ -25,6 +26,27 @@
export let data: PageData;
onMount(() => {
const render = () => {
if (window.turnstile && data.options?.cf_turnstile_site_key) {
window.turnstile.render('.cf-turnstile', {
sitekey: data.options.cf_turnstile_site_key,
theme: 'dark'
});
}
};
if (window.turnstile) {
render();
} else {
window.addEventListener('turnstile:loaded', render, { once: true });
}
return () => {
window.removeEventListener('turnstile:loaded', render);
};
});
function validatePassword(pw: string) {
passwordChecks.length = pw.length >= 8;
passwordChecks.upper = /[A-Z]/.test(pw);
@@ -44,8 +66,8 @@
loading = true;
error = '';
const body: Record<string, unknown> = { username, password, email, displayName };
if (data.options?.cf_turnstile_site_key && (window as any).turnstile) {
const token = (window as any).turnstile.getResponse();
if (data.options?.cf_turnstile_site_key && window.turnstile) {
const token = window.turnstile.getResponse();
if (token) body.token = token;
}
const res = await fetch('/api/auth/register', {
@@ -76,12 +98,6 @@
}
</script>
<svelte:head>
{#if data.options?.cf_turnstile_site_key}
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
{/if}
</svelte:head>
<main
class="flex min-h-screen w-full flex-col items-center justify-center bg-neutral-950 text-white"
>
@@ -197,17 +213,13 @@
{/if}
{#if data.options?.cf_turnstile_site_key}
<div class="flex w-full justify-center">
<div
class="cf-turnstile"
data-sitekey={data.options.cf_turnstile_site_key}
data-theme="dark"
></div>
<div class="cf-turnstile"></div>
</div>
{/if}
<button
type="submit"
disabled={!passwordValid || password !== confirmPassword || loading}
class="w-full rounded bg-neutral-700 px-4 py-2 font-semibold text-white transition-colors duration-200 hover:bg-neutral-800 active:bg-neutral-900 disabled:cursor-not-allowed disabled:bg-neutral-800 disabled:text-neutral-500"
class="w-full cursor-pointer rounded bg-neutral-700 px-4 py-2 font-semibold text-white transition-colors duration-200 hover:bg-neutral-800 active:bg-neutral-900 disabled:cursor-not-allowed disabled:bg-neutral-800 disabled:text-neutral-500"
>
{loading ? 'Registering...' : 'Register'}
</button>
@@ -1,34 +1,31 @@
<script lang="ts">
import { resolve } from '$app/paths';
import type { PageData } from './$types';
import type { Pagination } from '$lib/types/pagination';
import type { Pagination } from '$lib/types/pagination';
import { User, CalendarDays, ShieldUser, Ban, File, AtSign } from '@lucide/svelte';
import { extractDateFromUUIDv7, tooltip } from '$lib/utils/misc';
import { roles } from '$lib/consts';
import { getToken } from '$lib/utils/auth';
import { getToken } from '$lib/utils/auth';
export let data: PageData;
let currentPage = data.user.pagination?.page ?? 1;
let pagination: Pagination = data.user.pagination ?? {
page: 1,
pageSize: 50,
totalCount: 0,
totalPages: 1
};
page: 1,
pageSize: 50,
totalCount: 0,
totalPages: 1
};
let pastes = data.user.pastes ?? [];
let loading = false;
async function fetchPage(pageNum: number) {
if (pageNum < 1 || pageNum > (pagination.totalPages || 1) || loading) return;
loading = true;
const token = getToken();
const res = await fetch(
`/api/user/${data.user.username}?page=${pageNum}`,
{
headers: token ? { Authorization: `Bearer ${token}` } : {}
}
);
const token = getToken();
const res = await fetch(`/api/user/${data.user.username}?page=${pageNum}`, {
headers: token ? { Authorization: `Bearer ${token}` } : {}
});
if (!res.ok) {
loading = false;
return;