feat: login & registration; enhanced paste view; custom dropdown + search; navbar; global user access via store; auto token refresh; paste creation as user; /api/user/me, returns info on yourself including pastes;

fix: auth check
refactor: remove user UID api endpoint
This commit is contained in:
2025-12-28 13:54:01 -05:00
parent b9b14a3d5a
commit db1d8704a1
38 changed files with 1334 additions and 103 deletions
+29 -3
View File
@@ -1,9 +1,35 @@
<script lang="ts">
import { onMount } from 'svelte';
import './layout.css';
import favicon from '$lib/assets/favicon.svg';
import Navbar from '$lib/components/Navbar.svelte';
import { user } from '$lib/stores/user';
import { startTokenRefreshInterval, getToken, refreshTokenIfNeeded } from '$lib/utils/auth';
let { children } = $props();
if (typeof window !== 'undefined') {
startTokenRefreshInterval();
}
onMount(async () => {
await refreshTokenIfNeeded();
const token = getToken();
if (!token) return;
const res = await fetch('/api/user/me', {
headers: { Authorization: `Bearer ${token}` }
});
if (res.ok) {
user.set(await res.json());
} else {
user.set(null);
}
});
</script>
<svelte:head><link rel="icon" href={favicon} /></svelte:head>
{@render children()}
<svelte:head>
<link rel="icon" href={favicon} />
</svelte:head>
<Navbar />
<slot />
+7 -3
View File
@@ -1,7 +1,11 @@
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ fetch }) => {
const res = await fetch('/api/paste/create/options');
const options = await res.json();
return { options };
try {
const res = await fetch('/api/paste/create/options');
const options = await res.json();
return { options };
} catch {
return { options: null };
}
};
+70 -19
View File
@@ -1,21 +1,54 @@
<script lang="ts">
import type { PageData } from './$types';
import { displayNames } from '$lib/consts';
import { user } from '$lib/stores/user';
import { getToken } from '$lib/utils/auth';
import { fly } from 'svelte/transition';
import Dropdown from '$lib/components/Dropdown.svelte';
export let data: PageData;
let error = '';
let title = '';
let content = '';
let selectedSyntax = data.options.syntaxes[0];
let expiresIn: number = 0;
let selectedVisibility = data.options.visibilities[0].value;
let password = '';
const syntaxOptions = data.options.syntaxes.map((lang: string) => ({
value: lang,
label: displayNames[lang] ?? lang.charAt(0).toUpperCase() + lang.slice(1)
}));
const expiresOptions = [
{ value: 0, label: 'Never Expire' },
{ value: 600000, label: 'Expire in 10 Minutes' },
{ value: 3600000, label: 'Expire in 1 Hour' },
{ value: 86400000, label: 'Expire in 1 Day' },
{ value: 604800000, label: 'Expire in 1 Week' },
{ value: 1209600000, label: 'Expire in 2 Weeks' },
{ value: 2592000000, label: 'Expire in 1 Month' },
{ value: 7776000000, label: 'Expire in 3 Months' },
{ value: 15552000000, label: 'Expire in 6 Months' },
{ value: 31536000000, label: 'Expire in 1 Year' },
{ value: 63072000000, label: 'Expire in 2 Years' },
{ value: 157680000000, label: 'Expire in 5 Years' },
{ value: 315360000000, label: 'Expire in 10 Years' }
];
const visibilityOptions = data.options.visibilities.map((visibility: { value: number; displayName: string }) => ({
value: visibility.value,
label: visibility.displayName
}));
async function handleSubmit(event: Event) {
event.preventDefault();
const params = new URLSearchParams({
title: title.trim(),
syntax: selectedSyntax,
visibility: selectedVisibility.toString()
visibility: selectedVisibility.toString(),
expiresAt: expiresIn > 0 ? (Date.now() + Number(expiresIn)).toString() : '0'
});
let body = content;
if (selectedVisibility === 2) {
@@ -27,12 +60,24 @@
headers: { 'Content-Type': 'text/plain' },
body
};
if ($user) {
const token = getToken();
if (token) {
options.headers = {
...options.headers,
Authorization: `Bearer ${token}`
};
}
}
const response = await fetch(url, options);
if (response.ok) {
const result = await response.json();
window.location.href = `/${result.id}`;
} else {
alert('Failed to create paste. Please try again.');
error = 'Failed to create paste. Please try again.';
setInterval(() => {
error = '';
}, 5000);
}
}
@@ -86,7 +131,7 @@
<main
class="flex min-h-screen w-full flex-col items-center justify-center bg-neutral-950 text-white"
>
<div class="rounded border-2 border-neutral-800 bg-neutral-900 p-6 w-full max-w-5xl">
<div class="w-[95%] max-w-5xl rounded border-2 border-neutral-800 bg-neutral-900 p-6">
<h1 class="mb-6 text-center text-4xl font-bold">Create a Paste</h1>
<form class="mt-4" on:submit|preventDefault={handleSubmit}>
<input
@@ -104,24 +149,22 @@
autocomplete="off"
bind:value={content}
></textarea>
<select
class="mb-4 w-full rounded border border-neutral-700 bg-neutral-800 p-2"
<Dropdown
options={syntaxOptions}
bind:value={selectedSyntax}
>
{#each data.options.syntaxes as lang (lang)}
<option value={lang}
>{displayNames[lang] ?? lang.charAt(0).toUpperCase() + lang.slice(1)}</option
>
{/each}
</select>
<select
class="mb-4 w-full rounded border border-neutral-700 bg-neutral-800 p-2"
placeholder="Select syntax..."
searchable={true}
/>
<Dropdown
options={expiresOptions}
bind:value={expiresIn}
placeholder="Select expiration..."
/>
<Dropdown
options={visibilityOptions}
bind:value={selectedVisibility}
>
{#each data.options.visibilities as visibility (visibility.value)}
<option value={visibility.value}>{visibility.displayName}</option>
{/each}
</select>
placeholder="Select visibility..."
/>
{#if selectedVisibility === 2}
<input
type="password"
@@ -137,6 +180,14 @@
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"
>Create Paste</button
>
{#if error}
<div
transition:fly={{ y: 40, duration: 300 }}
class="rounded border border-red-900 bg-red-950 p-2 text-sm text-red-200"
>
{error}
</div>
{/if}
</form>
</div>
</main>
@@ -1,5 +1,6 @@
import type { PageServerLoad } from './$types';
import { getShiki } from '$lib/shiki';
import type { Paste } from '$lib/types/paste';
import { getShiki } from '$lib/server/shiki';
export const load: PageServerLoad = async ({ params, fetch }) => {
const { id } = params;
@@ -11,7 +12,7 @@ export const load: PageServerLoad = async ({ params, fetch }) => {
error: { message: 'Paste not found' }
};
}
const pasteData = await paste.json();
const pasteData = (await paste.json()) as Paste;
const pasteContent = await fetch(`/api/paste/raw/${id}`);
const pasteOptions = await fetch('/api/paste/create/options');
const options = await pasteOptions.json();
+87 -7
View File
@@ -1,6 +1,12 @@
<script lang="ts">
import type { PageData } from './$types';
import { FileBox, Eye, User, CalendarDays, CalendarOff, Code } from '@lucide/svelte/icons/index';
import { formatBytes, extractDateFromUUIDv7, dateToRelativeString } from '$lib/utils/misc';
import { displayNames } from '$lib/consts';
import { fade } from 'svelte/transition';
import { resolve } from '$app/paths';
export let data: PageData;
let fileSizeHovered = false;
function addLineNumbers(html: string): string {
const match = html.match(/<pre.*?>[\s\S]*?<code.*?>([\s\S]*?)<\/code><\/pre>/);
@@ -21,20 +27,90 @@
<main
class="flex min-h-screen w-full flex-col items-center justify-center bg-neutral-950 text-white"
>
{#if data.paste}
<div class="max-h-[80vh] rounded border-2 border-neutral-800 bg-neutral-900 p-4 w-full max-w-5xl">
<div
class="max-h-[80vh] w-[95%] max-w-5xl rounded border-2 border-neutral-800 bg-neutral-900 p-4"
>
{#if data.paste}
<h1 class="mb-4 text-center text-4xl font-bold">{data.paste.title || 'Untitled Paste'}</h1>
<div class="mb-2 flex flex-wrap items-center justify-center gap-4">
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="relative flex shrink-0 items-center">
<div
class="flex"
on:mouseenter={() => (fileSizeHovered = true)}
on:mouseleave={() => (fileSizeHovered = false)}
>
<FileBox class="mr-2 h-6 w-6 text-neutral-400" />
<span class="text-neutral-400">{formatBytes(data.paste.size)}</span>
</div>
{#if fileSizeHovered}
<div
class="absolute -top-8 left-1/2 z-10 w-fit -translate-x-1/2 rounded bg-neutral-800 px-2 py-1 text-sm whitespace-nowrap text-white shadow-lg"
transition:fade={{ duration: 150 }}
>
True Size: {formatBytes(data.paste.trueSize)}
</div>
{/if}
</div>
<div class="flex shrink-0 items-center">
<Eye class="mr-2 h-6 w-6 text-neutral-400" />
<span class="text-neutral-400"
>{data.paste.views} view{data.paste.views !== 1 ? 's' : ''}</span
>
</div>
<div class="flex shrink-0 items-center">
<CalendarDays class="mr-2 h-6 w-6 text-neutral-400" />
<span
class="text-neutral-400"
title={extractDateFromUUIDv7(data.paste.uuid)?.toLocaleString() ?? 'Unknown Date'}
>
{extractDateFromUUIDv7(data.paste.uuid)?.toLocaleDateString() ?? 'Unknown Date'}
</span>
</div>
{#if data.paste.expiresAt !== 0}
<div class="flex shrink-0 items-center">
<CalendarOff class="mr-2 h-6 w-6 text-neutral-400" />
<span class="text-neutral-400" title={new Date(data.paste.expiresAt).toLocaleString()}>
Expires in {dateToRelativeString(new Date(data.paste.expiresAt), false)}
</span>
</div>
{/if}
<div class="flex shrink-0 items-center">
<User class="mr-2 h-6 w-6 text-neutral-400" />
{#if data.paste.author}
<a
href={resolve(`/user/${data.paste.author.username}`)}
class="text-neutral-400 transition-colors duration-300 hover:text-neutral-500"
>{data.paste.author.username}</a
>
{:else}
<span class="text-neutral-400">Anonymous</span>
{/if}
</div>
<div class="flex shrink-0 items-center">
<Code class="mr-2 h-6 w-6 text-neutral-400" />
<span class="text-neutral-400">
{displayNames[data.paste.syntax] ??
data.paste.syntax.charAt(0).toUpperCase() + data.paste.syntax.slice(1)}
</span>
</div>
</div>
<div
class="codeblock-with-lines max-w-full overflow-x-auto overflow-y-auto"
style="max-width:100vw; min-width:0;"
>
{@html addLineNumbers(data.highlighted ?? '')}
</div>
</div>
{:else}
<h1 class="text-2xl font-bold">Paste not found</h1>
<h2 class="mt-2 text-lg">The paste you are looking for does not exist.</h2>
{/if}
{:else}
<h1 class="mb-4 text-center text-4xl font-bold">Paste not found</h1>
<h2 class="mt-2 text-center text-xl">The paste you are looking for does not exist.</h2>
{/if}
</div>
<style>
.codeblock-with-lines {
max-width: 100vw;
@@ -59,6 +135,10 @@
align-items: flex-start;
min-width: max-content;
padding: 0.1em 0;
border-radius: 0.15em;
}
.code-row:hover {
background-color: rgba(255, 255, 255, 0.05);
}
.line-number {
flex-shrink: 0;
@@ -0,0 +1,68 @@
<script lang="ts">
import { resolve } from '$app/paths';
let username = '';
let password = '';
let error = '';
import { setTokens, startTokenRefreshInterval } from '$lib/utils/auth';
async function login() {
const res = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
});
if (res.ok) {
const data = await res.json();
if (data.result.token && data.result.refreshToken) {
setTokens(data.result.token, data.result.refreshToken);
startTokenRefreshInterval();
}
window.location.href = '/';
} else {
error = 'Invalid username or password';
}
}
</script>
<main
class="flex min-h-screen w-full flex-col items-center justify-center bg-neutral-950 text-white"
>
<div class="w-full max-w-md rounded border-2 border-neutral-800 bg-neutral-900 p-6">
<h1 class="mb-6 text-center text-3xl font-bold">Login</h1>
<form on:submit|preventDefault={login} class="space-y-4">
<input
type="text"
placeholder="Username"
bind:value={username}
autocomplete="username"
required
class="focus:bg-neutral-750 w-full rounded border border-neutral-700 bg-neutral-800 p-2 placeholder-neutral-500 transition-colors duration-200 focus:border-neutral-600"
/>
<input
type="password"
placeholder="Password"
bind:value={password}
required
autocomplete="current-password"
class="focus:bg-neutral-750 w-full rounded border border-neutral-700 bg-neutral-800 p-2 placeholder-neutral-500 transition-colors duration-200 focus:border-neutral-600"
/>
<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"
>
Login
</button>
{#if error}
<div class="rounded border border-red-900 bg-red-950 p-2 text-sm text-red-200">
{error}
</div>
{/if}
</form>
<p class="mt-4 text-center text-sm text-neutral-400">
Don't have an account? <a
href={resolve('/register')}
class="text-neutral-200 transition-colors duration-200 hover:text-white">Register</a
>
</p>
</div>
</main>
@@ -0,0 +1,193 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { setTokens, startTokenRefreshInterval } from '$lib/utils/auth';
import { Check, X } from '@lucide/svelte';
import { slide, fade } from 'svelte/transition';
import { resolve } from '$app/paths';
let username = '';
let password = '';
let confirmPassword = '';
let email = '';
let displayName = '';
let error = '';
let passwordFocused = false;
let passwordChecks = {
length: false,
upper: false,
lower: false,
number: false
};
let passwordValid = false;
function validatePassword(pw: string) {
passwordChecks.length = pw.length >= 8;
passwordChecks.upper = /[A-Z]/.test(pw);
passwordChecks.lower = /[a-z]/.test(pw);
passwordChecks.number = /[0-9]/.test(pw);
passwordValid =
passwordChecks.length &&
passwordChecks.upper &&
passwordChecks.lower &&
passwordChecks.number;
}
$: validatePassword(password);
async function register() {
if (!passwordValid || password !== confirmPassword) return;
const res = await fetch('/api/auth/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password, email, displayName })
});
if (res.ok) {
const data = await res.json();
if (data.token && data.refreshToken) {
setTokens(data.token, data.refreshToken);
startTokenRefreshInterval();
goto(resolve('/'));
} else {
goto(resolve('/login'));
}
} else {
error = 'Registration failed';
}
}
</script>
<main
class="flex min-h-screen w-full flex-col items-center justify-center bg-neutral-950 text-white"
>
<div class="w-full max-w-md rounded border-2 border-neutral-800 bg-neutral-900 p-6">
<h1 class="mb-6 text-center text-3xl font-bold">Register</h1>
<form on:submit|preventDefault={register} class="space-y-4">
<input
type="text"
placeholder="Username"
bind:value={username}
autocomplete="username"
required
class="focus:bg-neutral-750 w-full rounded border border-neutral-700 bg-neutral-800 p-2 placeholder-neutral-500 transition-colors duration-200 focus:border-neutral-600"
/>
<div>
<input
type="email"
placeholder="Email (optional)"
bind:value={email}
autocomplete="email"
class="focus:bg-neutral-750 w-full rounded border border-neutral-700 bg-neutral-800 p-2 placeholder-neutral-500 transition-colors duration-200 focus:border-neutral-600"
/>
</div>
<div>
<input
type="text"
placeholder="Display Name (optional)"
bind:value={displayName}
autocomplete="name"
class="focus:bg-neutral-750 w-full rounded border border-neutral-700 bg-neutral-800 p-2 placeholder-neutral-500 transition-colors duration-200 focus:border-neutral-600"
/>
</div>
<input
type="password"
placeholder="Password"
bind:value={password}
required
on:focus={() => (passwordFocused = true)}
on:blur={() => (passwordFocused = false)}
autocomplete="new-password"
class="focus:bg-neutral-750 w-full rounded border border-neutral-700 bg-neutral-800 p-2 placeholder-neutral-500 transition-colors duration-200 focus:border-neutral-600"
/>
{#if passwordFocused}
<ul
transition:slide
class="space-y-2 rounded border border-neutral-700 bg-neutral-800 p-3 text-sm"
>
<li
class="flex items-center gap-2 {passwordChecks.length
? 'text-green-400'
: 'text-red-400'}"
>
{#if passwordChecks.length}
<Check class="h-4 w-4" />
{:else}
<X class="h-4 w-4" />
{/if}
At least 8 characters
</li>
<li
class="flex items-center gap-2 {passwordChecks.upper
? 'text-green-400'
: 'text-red-400'}"
>
{#if passwordChecks.upper}
<Check class="h-4 w-4" />
{:else}
<X class="h-4 w-4" />
{/if}
At least one uppercase letter
</li>
<li
class="flex items-center gap-2 {passwordChecks.lower
? 'text-green-400'
: 'text-red-400'}"
>
{#if passwordChecks.lower}
<Check class="h-4 w-4" />
{:else}
<X class="h-4 w-4" />
{/if}
At least one lowercase letter
</li>
<li
class="flex items-center gap-2 {passwordChecks.number
? 'text-green-400'
: 'text-red-400'}"
>
{#if passwordChecks.number}
<Check class="h-4 w-4" />
{:else}
<X class="h-4 w-4" />
{/if}
At least one number
</li>
</ul>
{/if}
<input
type="password"
placeholder="Confirm Password"
bind:value={confirmPassword}
required
autocomplete="new-password"
class="focus:bg-neutral-750 w-full rounded border border-neutral-700 bg-neutral-800 p-2 placeholder-neutral-500 transition-colors duration-200 focus:border-neutral-600"
/>
{#if confirmPassword && password !== confirmPassword}
<div
transition:fade
class="rounded border border-red-900 bg-red-950 p-2 text-sm text-red-200"
>
Passwords do not match.
</div>
{/if}
<button
type="submit"
disabled={!passwordValid || password !== confirmPassword}
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"
>
Register
</button>
{#if error}
<div class="rounded border border-red-900 bg-red-950 p-2 text-sm text-red-200">
{error}
</div>
{/if}
</form>
<p class="mt-4 text-center text-sm text-neutral-400">
Already have an account? <a
href={resolve('/login')}
class="text-neutral-200 transition-colors duration-200 hover:text-white">Login</a
>
</p>
</div>
</main>