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 PageState {}
// interface Platform {} // 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 {}; export {};
@@ -2,10 +2,10 @@
import { user } from '$lib/stores/user'; import { user } from '$lib/stores/user';
import { resolve } from '$app/paths'; import { resolve } from '$app/paths';
import { page } from '$app/state'; import { page } from '$app/state';
import { clearTokens } from '$lib/utils/auth';
function logout() { function logout() {
localStorage.removeItem('token'); clearTokens();
localStorage.removeItem('refreshToken');
user.set(null); user.set(null);
window.location.href = '/'; 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 Navbar from '$lib/components/Navbar.svelte';
import { user } from '$lib/stores/user'; import { user } from '$lib/stores/user';
import { startTokenRefreshInterval, getToken, refreshTokenIfNeeded } from '$lib/utils/auth'; 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') { if (typeof window !== 'undefined') {
startTokenRefreshInterval(); startTokenRefreshInterval();
window.turnstileLoaded = () => {
window.dispatchEvent(new CustomEvent('turnstile:loaded'));
};
} }
onMount(async () => { onMount(async () => {
@@ -29,6 +36,13 @@
<svelte:head> <svelte:head>
<link rel="icon" href={favicon} /> <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> </svelte:head>
<Navbar /> <Navbar />
@@ -1,5 +1,5 @@
import { json } from '@sveltejs/kit'; import { json } from '@sveltejs/kit';
export const GET = () => { 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"> <script lang="ts">
import { resolve } from '$app/paths'; import { resolve } from '$app/paths';
import { setTokens, startTokenRefreshInterval } from '$lib/utils/auth'; import { setTokens, startTokenRefreshInterval } from '$lib/utils/auth';
import { onMount } from 'svelte';
import type { PageData } from './$types'; import type { PageData } from './$types';
let username = ''; let username = '';
@@ -8,14 +9,35 @@
let error = ''; let error = '';
export let data: PageData; 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() { async function login() {
const body: { username: string; password: string; token?: string } = { const body: { username: string; password: string; token?: string } = {
username, username,
password password
}; };
if (data.options?.cf_turnstile_site_key && (window as any).turnstile) { if (data.options?.cf_turnstile_site_key && window.turnstile) {
const token = (window as any).turnstile.getResponse(); const token = window.turnstile.getResponse();
if (token) { if (token) {
body.token = token; body.token = token;
} }
@@ -45,12 +67,6 @@
} }
</script> </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 <main
class="flex min-h-screen w-full flex-col items-center justify-center bg-neutral-950 text-white" 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} {#if data.options?.cf_turnstile_site_key}
<div class="flex w-full justify-center"> <div class="flex w-full justify-center">
<div <div class="cf-turnstile"></div>
class="cf-turnstile"
data-sitekey={data.options.cf_turnstile_site_key}
data-theme="dark"
></div>
</div> </div>
{/if} {/if}
<button <button
type="submit" 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 Login
</button> </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 { Check, X } from '@lucide/svelte';
import { slide, fade } from 'svelte/transition'; import { slide, fade } from 'svelte/transition';
import { resolve } from '$app/paths'; import { resolve } from '$app/paths';
import { onMount } from 'svelte';
import type { PageData } from './$types'; import type { PageData } from './$types';
let username = ''; let username = '';
@@ -25,6 +26,27 @@
export let data: PageData; 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) { function validatePassword(pw: string) {
passwordChecks.length = pw.length >= 8; passwordChecks.length = pw.length >= 8;
passwordChecks.upper = /[A-Z]/.test(pw); passwordChecks.upper = /[A-Z]/.test(pw);
@@ -44,8 +66,8 @@
loading = true; loading = true;
error = ''; error = '';
const body: Record<string, unknown> = { username, password, email, displayName }; const body: Record<string, unknown> = { username, password, email, displayName };
if (data.options?.cf_turnstile_site_key && (window as any).turnstile) { if (data.options?.cf_turnstile_site_key && window.turnstile) {
const token = (window as any).turnstile.getResponse(); const token = window.turnstile.getResponse();
if (token) body.token = token; if (token) body.token = token;
} }
const res = await fetch('/api/auth/register', { const res = await fetch('/api/auth/register', {
@@ -76,12 +98,6 @@
} }
</script> </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 <main
class="flex min-h-screen w-full flex-col items-center justify-center bg-neutral-950 text-white" class="flex min-h-screen w-full flex-col items-center justify-center bg-neutral-950 text-white"
> >
@@ -197,17 +213,13 @@
{/if} {/if}
{#if data.options?.cf_turnstile_site_key} {#if data.options?.cf_turnstile_site_key}
<div class="flex w-full justify-center"> <div class="flex w-full justify-center">
<div <div class="cf-turnstile"></div>
class="cf-turnstile"
data-sitekey={data.options.cf_turnstile_site_key}
data-theme="dark"
></div>
</div> </div>
{/if} {/if}
<button <button
type="submit" type="submit"
disabled={!passwordValid || password !== confirmPassword || loading} 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'} {loading ? 'Registering...' : 'Register'}
</button> </button>
@@ -1,34 +1,31 @@
<script lang="ts"> <script lang="ts">
import { resolve } from '$app/paths'; import { resolve } from '$app/paths';
import type { PageData } from './$types'; 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 { User, CalendarDays, ShieldUser, Ban, File, AtSign } from '@lucide/svelte';
import { extractDateFromUUIDv7, tooltip } from '$lib/utils/misc'; import { extractDateFromUUIDv7, tooltip } from '$lib/utils/misc';
import { roles } from '$lib/consts'; import { roles } from '$lib/consts';
import { getToken } from '$lib/utils/auth'; import { getToken } from '$lib/utils/auth';
export let data: PageData; export let data: PageData;
let currentPage = data.user.pagination?.page ?? 1; let currentPage = data.user.pagination?.page ?? 1;
let pagination: Pagination = data.user.pagination ?? { let pagination: Pagination = data.user.pagination ?? {
page: 1, page: 1,
pageSize: 50, pageSize: 50,
totalCount: 0, totalCount: 0,
totalPages: 1 totalPages: 1
}; };
let pastes = data.user.pastes ?? []; let pastes = data.user.pastes ?? [];
let loading = false; let loading = false;
async function fetchPage(pageNum: number) { async function fetchPage(pageNum: number) {
if (pageNum < 1 || pageNum > (pagination.totalPages || 1) || loading) return; if (pageNum < 1 || pageNum > (pagination.totalPages || 1) || loading) return;
loading = true; loading = true;
const token = getToken(); const token = getToken();
const res = await fetch( const res = await fetch(`/api/user/${data.user.username}?page=${pageNum}`, {
`/api/user/${data.user.username}?page=${pageNum}`, headers: token ? { Authorization: `Bearer ${token}` } : {}
{ });
headers: token ? { Authorization: `Bearer ${token}` } : {}
}
);
if (!res.ok) { if (!res.ok) {
loading = false; loading = false;
return; return;
-24
View File
@@ -1,24 +0,0 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.5.2.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SharpbinV3.Server", "SharpbinV3.Server.csproj", "{79A5E17C-498C-F55E-C79E-1F32E48383EF}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{79A5E17C-498C-F55E-C79E-1F32E48383EF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{79A5E17C-498C-F55E-C79E-1F32E48383EF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{79A5E17C-498C-F55E-C79E-1F32E48383EF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{79A5E17C-498C-F55E-C79E-1F32E48383EF}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {7F30EE13-B933-4515-AA54-DBDD2605C90C}
EndGlobalSection
EndGlobal