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
+6
View File
@@ -0,0 +1,6 @@
{
"files.associations": {
"*.css": "tailwindcss"
},
"tailwindCSS.experimental.configFile": "SharpbinV3.Client/src/routes/layout.css"
}
+12 -19
View File
@@ -7,6 +7,9 @@
"": {
"name": "sharpbinv3.client",
"version": "0.0.1",
"dependencies": {
"@lucide/svelte": "^0.562.0"
},
"devDependencies": {
"@eslint/compat": "^1.4.0",
"@eslint/js": "^9.39.1",
@@ -707,7 +710,6 @@
"version": "0.3.13",
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
"integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/sourcemap-codec": "^1.5.0",
@@ -718,7 +720,6 @@
"version": "2.3.5",
"resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz",
"integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/gen-mapping": "^0.3.5",
@@ -729,7 +730,6 @@
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
"integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6.0.0"
@@ -739,20 +739,27 @@
"version": "1.5.5",
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
"integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",
"dev": true,
"license": "MIT"
},
"node_modules/@jridgewell/trace-mapping": {
"version": "0.3.31",
"resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
"integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/resolve-uri": "^3.1.0",
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
"node_modules/@lucide/svelte": {
"version": "0.562.0",
"resolved": "https://registry.npmjs.org/@lucide/svelte/-/svelte-0.562.0.tgz",
"integrity": "sha512-wDMULwtTFN2Sc/TFBm6gfuVCNb4Y5P9LDrwxNnUbV52+IEU7NXZmvxwXoz+vrrpad6Xupq+Hw5eUlqIHEGhouw==",
"license": "ISC",
"peerDependencies": {
"svelte": "^5"
}
},
"node_modules/@polka/url": {
"version": "1.0.0-next.29",
"resolved": "https://registry.npmjs.org/@polka/url/-/url-1.0.0-next.29.tgz",
@@ -1153,7 +1160,6 @@
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/@sveltejs/acorn-typescript/-/acorn-typescript-1.0.8.tgz",
"integrity": "sha512-esgN+54+q0NjB0Y/4BomT9samII7jGwNy/2a3wNZbT2A2RpmXsXwUt24LvLhx6jUq2gVk4cWEvcRO6MFQbOfNA==",
"dev": true,
"license": "MIT",
"peerDependencies": {
"acorn": "^8.9.0"
@@ -1530,7 +1536,6 @@
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",
"integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/hast": {
@@ -1844,7 +1849,6 @@
"version": "8.15.0",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
"dev": true,
"license": "MIT",
"bin": {
"acorn": "bin/acorn"
@@ -1907,7 +1911,6 @@
"version": "5.3.2",
"resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.2.tgz",
"integrity": "sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw==",
"dev": true,
"license": "Apache-2.0",
"engines": {
"node": ">= 0.4"
@@ -1917,7 +1920,6 @@
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz",
"integrity": "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==",
"dev": true,
"license": "Apache-2.0",
"engines": {
"node": ">= 0.4"
@@ -2021,7 +2023,6 @@
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz",
"integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6"
@@ -2162,7 +2163,6 @@
"version": "5.6.1",
"resolved": "https://registry.npmjs.org/devalue/-/devalue-5.6.1.tgz",
"integrity": "sha512-jDwizj+IlEZBunHcOuuFVBnIMPAEHvTsJj0BcIp94xYguLRVBcXO853px/MyIJvbVzWdsGvrRweIUWJw8hBP7A==",
"dev": true,
"license": "MIT"
},
"node_modules/devlop": {
@@ -2392,7 +2392,6 @@
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/esm-env/-/esm-env-1.2.2.tgz",
"integrity": "sha512-Epxrv+Nr/CaL4ZcFGPJIYLWFom+YeV1DqMLHJoEd9SYRxNbaFruBwfEX/kkHUJf55j2+TUbmDcmuilbP1TmXHA==",
"dev": true,
"license": "MIT"
},
"node_modules/espree": {
@@ -2430,7 +2429,6 @@
"version": "2.2.1",
"resolved": "https://registry.npmjs.org/esrap/-/esrap-2.2.1.tgz",
"integrity": "sha512-GiYWG34AN/4CUyaWAgunGt0Rxvr1PTMlGC0vvEov/uOQYWne2bpN03Um+k8jT+q3op33mKouP2zeJ6OlM+qeUg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/sourcemap-codec": "^1.4.15"
@@ -2730,7 +2728,6 @@
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/is-reference/-/is-reference-3.0.3.tgz",
"integrity": "sha512-ixkJoqQvAP88E6wLydLGGqCJsrFUnqoH6HnaczB8XmDH1oaWU+xxdptvikTgaEhtZ53Ky6YXiBuUI2WXLMCwjw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/estree": "^1.0.6"
@@ -3103,7 +3100,6 @@
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/locate-character/-/locate-character-3.0.0.tgz",
"integrity": "sha512-SW13ws7BjaeJ6p7Q6CO2nchbYEc3X3J6WrmTTDto7yMPqVSZTUyY5Tjbid+Ab8gLnATtygYtiDIJGQRRn2ZOiA==",
"dev": true,
"license": "MIT"
},
"node_modules/locate-path": {
@@ -3133,7 +3129,6 @@
"version": "0.30.21",
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
"integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/sourcemap-codec": "^1.5.5"
@@ -3964,7 +3959,6 @@
"version": "5.46.1",
"resolved": "https://registry.npmjs.org/svelte/-/svelte-5.46.1.tgz",
"integrity": "sha512-ynjfCHD3nP2el70kN5Pmg37sSi0EjOm9FgHYQdC4giWG/hzO3AatzXXJJgP305uIhGQxSufJLuYWtkY8uK/8RA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/remapping": "^2.3.4",
@@ -4429,7 +4423,6 @@
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/zimmerframe/-/zimmerframe-1.1.4.tgz",
"integrity": "sha512-B58NGBEoc8Y9MWWCQGl/gq9xBCe4IiKM0a2x7GZdQKOW5Exr8S1W24J6OgM1njK8xCRGvAJIL/MxXHf6SkmQKQ==",
"dev": true,
"license": "MIT"
},
"node_modules/zwitch": {
+3
View File
@@ -35,5 +35,8 @@
"typescript": "^5.9.3",
"typescript-eslint": "^8.48.1",
"vite": "^7.2.6"
},
"dependencies": {
"@lucide/svelte": "^0.562.0"
}
}
@@ -0,0 +1,95 @@
<script lang="ts">
interface Option {
value: string | number;
label: string;
}
export let options: Option[] = [];
export let value: string | number = '';
export let placeholder = 'Select...';
export let searchable = false;
export let displayValue: (val: string | number) => string = (val) => {
return options.find((o) => o.value === val)?.label ?? String(val);
};
let isOpen = false;
let searchQuery = '';
let dropdownElement: HTMLDivElement;
$: filteredOptions = searchable
? options.filter(
(opt) =>
opt.label.toLowerCase().includes(searchQuery.toLowerCase()) ||
String(opt.value).toLowerCase().includes(searchQuery.toLowerCase())
)
: options;
function handleSelect(selectedValue: string | number) {
value = selectedValue;
isOpen = false;
searchQuery = '';
}
function handleKeyDown(e: KeyboardEvent) {
if (e.key === 'Escape') {
isOpen = false;
}
}
function toggleDropdown() {
isOpen = !isOpen;
if (isOpen && searchable) {
setTimeout(() => {
const input = dropdownElement?.querySelector('input[type="text"]') as HTMLInputElement;
input?.focus();
}, 0);
}
}
function handleClickOutside(event: MouseEvent) {
if (dropdownElement && !dropdownElement.contains(event.target as Node)) {
isOpen = false;
}
}
</script>
<svelte:window on:click={handleClickOutside} />
<div bind:this={dropdownElement} class="relative w-full mb-2">
<button
type="button"
on:click={toggleDropdown}
class="w-full rounded border border-neutral-700 bg-neutral-800 p-2 text-left transition-colors hover:bg-neutral-700"
>
{displayValue(value) || placeholder}
</button>
{#if isOpen}
<div
class="absolute top-full z-50 mt-1 w-full rounded border border-neutral-700 bg-neutral-800 shadow-lg"
>
{#if searchable}
<input
type="text"
placeholder="Search..."
class="w-full border-b border-neutral-700 bg-neutral-800 p-2 outline-none"
bind:value={searchQuery}
on:keydown={handleKeyDown}
/>
{/if}
<div class="max-h-48 overflow-y-auto">
{#each filteredOptions as option (option.value)}
<button
type="button"
on:click={() => handleSelect(option.value)}
class="w-full border-b border-neutral-700 px-3 py-2 text-left last:border-b-0 hover:bg-neutral-600"
class:bg-neutral-700={value === option.value}
>
{option.label}
</button>
{/each}
</div>
</div>
{/if}
</div>
@@ -0,0 +1,35 @@
<script lang="ts">
import { user } from '$lib/stores/user';
import { resolve } from '$app/paths';
function logout() {
localStorage.removeItem('token');
localStorage.removeItem('refreshToken');
user.set(null);
window.location.href = '/';
}
</script>
<div class="fixed top-0 left-0 h-15 w-full bg-neutral-900">
<div class="mx-auto flex h-15 max-w-5xl items-center px-4 py-2">
<a href={resolve('/')} class="text-xl font-bold text-white hover:text-neutral-300">Sharpbin</a>
{#if $user}
<div class="ml-auto flex items-center space-x-4">
<span class="text-neutral-400">{$user.username}</span>
<button
on:click={logout}
class="rounded bg-neutral-700 px-3 py-1 text-white hover:bg-neutral-800">Logout</button
>
</div>
{:else}
<div class="ml-auto flex items-center space-x-4">
<a href={resolve('/login')} class="rounded bg-neutral-700 px-3 py-1 text-white hover:bg-neutral-800"
>Login</a
>
<a href={resolve('/register')} class="rounded bg-neutral-700 px-3 py-1 text-white hover:bg-neutral-800"
>Register</a
>
</div>
{/if}
</div>
</div>
+4
View File
@@ -0,0 +1,4 @@
import { writable } from 'svelte/store';
import type { User } from '$lib/types/user';
export const user = writable<User | null>(null);
@@ -0,0 +1,6 @@
export interface Author {
uid: number;
uuid: string;
username: string;
visibility: 0 | 1 | 2;
}
+15
View File
@@ -0,0 +1,15 @@
import type { Author } from './author';
export interface Paste {
id: string;
uuid: string;
title: string | null;
size: number;
trueSize: number;
isCompressed: boolean;
views: number;
syntax: string;
visibility: 0 | 1 | 2;
expiresAt: number;
author: Author | null;
}
+13
View File
@@ -0,0 +1,13 @@
import type { Paste } from './paste';
export interface User {
uid: number;
uuid: string;
username: string;
displayName: string | null;
email: string | null;
lastLogin: number | null;
roles: number[];
visibility: 0 | 1 | 2;
pastes: Paste[] | null;
}
+53
View File
@@ -0,0 +1,53 @@
import { browser } from '$app/environment';
const TOKEN_KEY = 'token';
const REFRESH_TOKEN_KEY = 'refreshToken';
export function getToken() {
if (!browser) return null;
return localStorage.getItem(TOKEN_KEY);
}
export function getRefreshToken() {
if (!browser) return null;
return localStorage.getItem(REFRESH_TOKEN_KEY);
}
export function setTokens(token: string, refreshToken: string) {
if (!browser) return;
localStorage.setItem(TOKEN_KEY, token);
localStorage.setItem(REFRESH_TOKEN_KEY, refreshToken);
}
export function clearTokens() {
if (!browser) return;
localStorage.removeItem(TOKEN_KEY);
localStorage.removeItem(REFRESH_TOKEN_KEY);
}
export async function refreshTokenIfNeeded() {
const token = getToken();
const refreshToken = getRefreshToken();
if (!token || !refreshToken) return;
const payload = JSON.parse(atob(token.split('.')[1]));
const exp = payload.exp * 1000;
const now = Date.now();
if (exp - now < 2 * 60 * 1000) {
const res = await fetch('/api/auth/refresh', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token, refreshToken })
});
if (res.ok) {
const data = await res.json();
if (data.token.token && data.token.refreshToken) {
setTokens(data.token.token, data.token.refreshToken);
}
}
}
}
export function startTokenRefreshInterval() {
if (!browser) return;
setInterval(refreshTokenIfNeeded, 60 * 1000);
}
+37
View File
@@ -0,0 +1,37 @@
export function formatBytes(bytes: number, decimals = 2): string {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
export function extractDateFromUUIDv7(uuid?: string): Date | null {
if (!uuid) return null;
const hex = uuid.replace(/-/g, '');
const timestampHex = hex.slice(0, 12);
return new Date(parseInt(timestampHex, 16));
}
export function dateToRelativeString(date: Date, useSuffix = true): string {
const now = new Date();
const isFuture = date > now;
const suffix = useSuffix ? (isFuture ? 'from now' : 'ago') : '';
const diff = Math.abs(now.getTime() - date.getTime());
const seconds = Math.floor(diff / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
const weeks = Math.floor(days / 7);
const months = Math.floor(days / 30);
const years = Math.floor(days / 365);
if (years > 0) return `${years} year${years > 1 ? 's' : ''} ${suffix}`;
if (months > 0) return `${months} month${months > 1 ? 's' : ''} ${suffix}`;
if (weeks > 0) return `${weeks} week${weeks > 1 ? 's' : ''} ${suffix}`;
if (days > 0) return `${days} day${days > 1 ? 's' : ''} ${suffix}`;
if (hours > 0) return `${hours} hour${hours > 1 ? 's' : ''} ${suffix}`;
if (minutes > 0) return `${minutes} minute${minutes > 1 ? 's' : ''} ${suffix}`;
return `${seconds} second${seconds !== 1 ? 's' : ''} ${suffix}`;
}
+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 />
@@ -1,7 +1,11 @@
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ fetch }) => {
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();
+84 -4
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"
>
<div
class="max-h-[80vh] w-[95%] max-w-5xl rounded border-2 border-neutral-800 bg-neutral-900 p-4"
>
{#if data.paste}
<div class="max-h-[80vh] rounded border-2 border-neutral-800 bg-neutral-900 p-4 w-full max-w-5xl">
<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>
<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>
+36
View File
@@ -22,6 +22,16 @@ namespace SharpbinV3.Server.Controllers
var existingUser = await _userService.GetByUsername(request.Username);
if (existingUser != null)
return Conflict(new { message = "Username already exists." });
if (!string.IsNullOrEmpty(request.Email))
{
var existingEmailUser = await _userService.GetByEmail(request.Email);
if (existingEmailUser != null)
return Conflict(new { message = "Email already in use." });
if (!IsValidEmail(request.Email))
return BadRequest(new { message = "Invalid email." });
}
if (!IsValidPassword(request.Password))
return BadRequest(new { message = "Password should have at least 8 characters, including uppercase, lowercase, and digits." });
var user = await _authService.CreateUser(request.Username, request.Password, request.Email, request.DisplayName);
return Ok(new
@@ -75,5 +85,31 @@ namespace SharpbinV3.Server.Controllers
return BadRequest(new { message = ex.Message });
}
}
private static bool IsValidPassword(string password)
{
if (password.Length < 6)
return false;
if (!password.Any(char.IsUpper))
return false;
if (!password.Any(char.IsLower))
return false;
if (!password.Any(char.IsDigit))
return false;
return true;
}
private static bool IsValidEmail(string email)
{
try
{
var addr = new System.Net.Mail.MailAddress(email);
return addr.Address == email;
}
catch
{
return false;
}
}
}
}
+8 -2
View File
@@ -31,8 +31,13 @@ namespace SharpbinV3.Server.Controllers
string content = await new StreamReader(Request.Body).ReadToEndAsync();
var httpUser = HttpContext.User;
foreach (var key in httpUser.Claims)
{
Console.WriteLine($"Claim: {key.Type} = {key.Value}");
}
var userUUID = httpUser?.FindFirst("UUID")?.Value;
User? user = userUUID is not null ? await _userService.GetByUUID(Guid.Parse(userUUID)) : null;
Console.WriteLine($"Creating paste for user: {(user != null ? user.Username : "Anonymous")}");
Paste paste = await _pasteService.Create(user, content, title, syntax, visibility, expiresAt);
return Ok(new
{
@@ -62,12 +67,13 @@ namespace SharpbinV3.Server.Controllers
paste.Syntax,
paste.Visibility,
paste.ExpiresAt,
Author = paste.User != null && paste.User.Visiblity == 0 ? new
Author = paste.User != null && paste.User.Visibility == 0 ? new
{
paste.User.UID,
paste.User.UUID,
paste.User.Username,
paste.User.Visiblity
paste.User.DisplayName,
paste.User.Visibility
} : null
});
}
+35 -10
View File
@@ -10,15 +10,7 @@ namespace SharpbinV3.Server.Controllers
{
private readonly IUserService _userService = userService;
[HttpGet("{uid}")]
public async Task<IActionResult> GetByUid(int uid)
{
var user = await _userService.GetByUID(uid);
if (user == null) return NotFound();
return Ok(new { user.UID, user.Username, user.UUID, user.DisplayName });
}
[HttpGet("username/{username}")]
[HttpGet("{username}")]
public async Task<IActionResult> GetByUsername(string username)
{
var user = await _userService.GetByUsername(username);
@@ -26,12 +18,45 @@ namespace SharpbinV3.Server.Controllers
return Ok(new { user.UID, user.Username, user.UUID, user.DisplayName });
}
[HttpGet("uuid/{uuid}")]
[Authorize]
public async Task<IActionResult> GetByUUID(Guid uuid)
{
var user = await _userService.GetByUUID(uuid);
if (user == null) return NotFound();
return Ok(new { user.UID, user.Username, user.UUID, user.DisplayName });
}
[HttpGet("me")]
[Authorize]
public async Task<IActionResult> GetMe()
{
var httpUser = HttpContext.User;
var userUUID = httpUser?.FindFirst("UUID")?.Value;
if (userUUID is null)
return Unauthorized(new { message = "Invalid token." });
var user = await _userService.GetByUUID(Guid.Parse(userUUID), true);
if (user == null)
return NotFound();
var pastes = user.Pastes?.Select(p => new {
p.UUID,
p.Title,
p.Syntax,
p.Size,
p.TrueSize,
p.Views,
p.Visibility,
p.EditedAt,
p.ExpiresAt
});
return Ok(new {
user.UID,
user.Username,
user.UUID,
user.DisplayName,
user.Email,
user.LastLogin,
user.Roles,
user.Visibility,
Pastes = pastes
});
}
}
}
-1
View File
@@ -6,7 +6,6 @@ namespace SharpbinV3.Server.DTOs
{
[StringLength(50, MinimumLength = 3)]
public string? Username { get; set; }
[EmailAddress]
public string? Email { get; set; }
[StringLength(128, MinimumLength = 6)]
public string? Password { get; set; }
-1
View File
@@ -12,7 +12,6 @@ namespace SharpbinV3.Server.DTOs
[StringLength(128, MinimumLength = 6)]
public required string Password { get; set; }
[EmailAddress]
public string? Email { get; set; }
public string? DisplayName { get; set; }
+2 -2
View File
@@ -24,8 +24,8 @@ namespace SharpbinV3.Server.Data.Entities
public long? EditedAt { get; set; }
public required byte[] Content { get; set; }
public int Size { get; set; } // stored size (may be compressed)
public int TrueSize { get; set; } // uncompressed size
public long Size { get; set; } // stored size (may be compressed)
public long TrueSize { get; set; } // uncompressed size
public bool IsCompressed { get; set; } = false;
public int Views { get; set; }
+1 -2
View File
@@ -3,7 +3,6 @@ using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.Server.Data.Entities
{
[Index(nameof(UID), IsUnique = true)]
[Index(nameof(UUID), IsUnique = true)]
public sealed class User
{
@@ -16,7 +15,7 @@ namespace SharpbinV3.Server.Data.Entities
public string? DisplayName { get; set; }
public long? LastLogin { get; set; }
public int[] Roles { get; set; } = [0]; // 0 = regular user, 1 = moderator, 255 = admin
public int Visiblity { get; set; } = 0; // 0 = public, 1 = unlisted, 2 = private
public int Visibility { get; set; } = 0; // 0 = public, 1 = unlisted, 2 = private
public List<Paste> Pastes { get; set; } = [];
}
}
@@ -0,0 +1,195 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SharpbinV3.Server.Data;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20251228173503_UserGrammarFix")]
partial class UserGrammarFix
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.0");
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.Property<int>("PID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<Guid>("AuthorUUID")
.HasColumnType("TEXT");
b.Property<byte[]>("Content")
.IsRequired()
.HasColumnType("BLOB");
b.Property<long?>("EditedAt")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("ID")
.HasColumnType("TEXT");
b.Property<bool>("IsCompressed")
.HasColumnType("INTEGER");
b.Property<int>("Size")
.HasColumnType("INTEGER");
b.Property<string>("Syntax")
.HasColumnType("TEXT");
b.Property<string>("Title")
.HasColumnType("TEXT");
b.Property<int>("TrueSize")
.HasColumnType("INTEGER");
b.Property<Guid>("UUID")
.HasColumnType("TEXT");
b.Property<int?>("UserUID")
.HasColumnType("INTEGER");
b.Property<int>("Views")
.HasColumnType("INTEGER");
b.Property<int>("Visibility")
.HasColumnType("INTEGER");
b.HasKey("PID");
b.HasIndex("AuthorUUID");
b.HasIndex("ExpiresAt");
b.HasIndex("ID")
.IsUnique();
b.HasIndex("PID")
.IsUnique();
b.HasIndex("UUID")
.IsUnique();
b.HasIndex("UserUID");
b.HasIndex("Views");
b.HasIndex("Visibility");
b.ToTable("Pastes");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.Property<Guid>("UserUUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("JwtId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Token")
.IsRequired()
.HasColumnType("TEXT");
b.Property<bool>("Used")
.HasColumnType("INTEGER");
b.Property<int?>("UserUID")
.HasColumnType("INTEGER");
b.HasKey("UserUUID");
b.HasIndex("UserUID");
b.ToTable("RefreshTokens");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Property<int>("UID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("DisplayName")
.HasColumnType("TEXT");
b.Property<string>("Email")
.HasColumnType("TEXT");
b.Property<long?>("LastLogin")
.HasColumnType("INTEGER");
b.Property<string>("PasswordHash")
.IsRequired()
.HasColumnType("TEXT");
b.PrimitiveCollection<string>("Roles")
.IsRequired()
.HasColumnType("TEXT");
b.Property<Guid>("UUID")
.HasColumnType("TEXT");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Visibility")
.HasColumnType("INTEGER");
b.HasKey("UID");
b.HasIndex("UUID")
.IsUnique();
b.ToTable("Users");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Pastes")
.HasForeignKey("UserUID");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany()
.HasForeignKey("UserUID");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Navigation("Pastes");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,38 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
/// <inheritdoc />
public partial class UserGrammarFix : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_Users_UID",
table: "Users");
migrationBuilder.RenameColumn(
name: "Visiblity",
table: "Users",
newName: "Visibility");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "Visibility",
table: "Users",
newName: "Visiblity");
migrationBuilder.CreateIndex(
name: "IX_Users_UID",
table: "Users",
column: "UID",
unique: true);
}
}
}
@@ -0,0 +1,195 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SharpbinV3.Server.Data;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20251228175338_LongFileSizes")]
partial class LongFileSizes
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.0");
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.Property<int>("PID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<Guid>("AuthorUUID")
.HasColumnType("TEXT");
b.Property<byte[]>("Content")
.IsRequired()
.HasColumnType("BLOB");
b.Property<long?>("EditedAt")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("ID")
.HasColumnType("TEXT");
b.Property<bool>("IsCompressed")
.HasColumnType("INTEGER");
b.Property<long>("Size")
.HasColumnType("INTEGER");
b.Property<string>("Syntax")
.HasColumnType("TEXT");
b.Property<string>("Title")
.HasColumnType("TEXT");
b.Property<long>("TrueSize")
.HasColumnType("INTEGER");
b.Property<Guid>("UUID")
.HasColumnType("TEXT");
b.Property<int?>("UserUID")
.HasColumnType("INTEGER");
b.Property<int>("Views")
.HasColumnType("INTEGER");
b.Property<int>("Visibility")
.HasColumnType("INTEGER");
b.HasKey("PID");
b.HasIndex("AuthorUUID");
b.HasIndex("ExpiresAt");
b.HasIndex("ID")
.IsUnique();
b.HasIndex("PID")
.IsUnique();
b.HasIndex("UUID")
.IsUnique();
b.HasIndex("UserUID");
b.HasIndex("Views");
b.HasIndex("Visibility");
b.ToTable("Pastes");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.Property<Guid>("UserUUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("JwtId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Token")
.IsRequired()
.HasColumnType("TEXT");
b.Property<bool>("Used")
.HasColumnType("INTEGER");
b.Property<int?>("UserUID")
.HasColumnType("INTEGER");
b.HasKey("UserUUID");
b.HasIndex("UserUID");
b.ToTable("RefreshTokens");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Property<int>("UID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("DisplayName")
.HasColumnType("TEXT");
b.Property<string>("Email")
.HasColumnType("TEXT");
b.Property<long?>("LastLogin")
.HasColumnType("INTEGER");
b.Property<string>("PasswordHash")
.IsRequired()
.HasColumnType("TEXT");
b.PrimitiveCollection<string>("Roles")
.IsRequired()
.HasColumnType("TEXT");
b.Property<Guid>("UUID")
.HasColumnType("TEXT");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Visibility")
.HasColumnType("INTEGER");
b.HasKey("UID");
b.HasIndex("UUID")
.IsUnique();
b.ToTable("Users");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Pastes")
.HasForeignKey("UserUID");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany()
.HasForeignKey("UserUID");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Navigation("Pastes");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,22 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
/// <inheritdoc />
public partial class LongFileSizes : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}
@@ -17,7 +17,7 @@ namespace SharpbinV3.Server.Migrations
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.0");
modelBuilder.Entity("SharpbinV3.Data.Entities.Paste", b =>
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.Property<int>("PID")
.ValueGeneratedOnAdd()
@@ -42,7 +42,7 @@ namespace SharpbinV3.Server.Migrations
b.Property<bool>("IsCompressed")
.HasColumnType("INTEGER");
b.Property<int>("Size")
b.Property<long>("Size")
.HasColumnType("INTEGER");
b.Property<string>("Syntax")
@@ -51,7 +51,7 @@ namespace SharpbinV3.Server.Migrations
b.Property<string>("Title")
.HasColumnType("TEXT");
b.Property<int>("TrueSize")
b.Property<long>("TrueSize")
.HasColumnType("INTEGER");
b.Property<Guid>("UUID")
@@ -90,7 +90,7 @@ namespace SharpbinV3.Server.Migrations
b.ToTable("Pastes");
});
modelBuilder.Entity("SharpbinV3.Data.Entities.RefreshToken", b =>
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.Property<Guid>("UserUUID")
.ValueGeneratedOnAdd()
@@ -123,7 +123,7 @@ namespace SharpbinV3.Server.Migrations
b.ToTable("RefreshTokens");
});
modelBuilder.Entity("SharpbinV3.Data.Entities.User", b =>
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Property<int>("UID")
.ValueGeneratedOnAdd()
@@ -153,39 +153,36 @@ namespace SharpbinV3.Server.Migrations
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Visiblity")
b.Property<int>("Visibility")
.HasColumnType("INTEGER");
b.HasKey("UID");
b.HasIndex("UID")
.IsUnique();
b.HasIndex("UUID")
.IsUnique();
b.ToTable("Users");
});
modelBuilder.Entity("SharpbinV3.Data.Entities.Paste", b =>
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.HasOne("SharpbinV3.Data.Entities.User", "User")
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Pastes")
.HasForeignKey("UserUID");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Data.Entities.RefreshToken", b =>
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.HasOne("SharpbinV3.Data.Entities.User", "User")
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany()
.HasForeignKey("UserUID");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Data.Entities.User", b =>
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Navigation("Pastes");
});
+4 -3
View File
@@ -38,16 +38,17 @@ namespace SharpbinV3.Server
})
.AddJwtBearer(jwt =>
{
var key = Encoding.ASCII.GetBytes(builder.Configuration.GetSection("JwtConfig:Secret").Value ?? string.Empty);
var jwtSettings = builder.Configuration.GetSection("JwtSettings");
var key = Encoding.ASCII.GetBytes(jwtSettings["Secret"] ?? string.Empty);
jwt.SaveToken = true;
jwt.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = true,
ValidIssuer = builder.Configuration["JwtConfig:Issuer"],
ValidIssuer = jwtSettings["Issuer"],
ValidateAudience = true,
ValidAudience = builder.Configuration["JwtConfig:Audience"],
ValidAudience = jwtSettings["Audience"],
RequireExpirationTime = true,
ValidateLifetime = true
};
+4 -4
View File
@@ -35,7 +35,7 @@ namespace SharpbinV3.Server.Services
public async Task<JWTResult> GenerateJWTToken(User user)
{
var jwtHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_jwtSettings.SecretKey);
var key = Encoding.ASCII.GetBytes(_jwtSettings.Secret);
var descriptor = new SecurityTokenDescriptor
{
@@ -93,7 +93,7 @@ namespace SharpbinV3.Server.Services
public async Task<bool> ValidateJWTToken(string token)
{
var jwtHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_jwtSettings.SecretKey);
var key = Encoding.ASCII.GetBytes(_jwtSettings.Secret);
try
{
jwtHandler.ValidateToken(token, new TokenValidationParameters
@@ -115,7 +115,7 @@ namespace SharpbinV3.Server.Services
public async Task<JWTResult> RefreshJWTToken(string token, string refreshToken)
{
var jwtHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_jwtSettings.SecretKey);
var key = Encoding.ASCII.GetBytes(_jwtSettings.Secret);
try
{
var principal = jwtHandler.ValidateToken(token, new TokenValidationParameters
@@ -162,7 +162,7 @@ namespace SharpbinV3.Server.Services
existingUser.DisplayName = user.DisplayName;
existingUser.Roles = user.Roles;
existingUser.LastLogin = user.LastLogin;
existingUser.Visiblity = user.Visiblity;
existingUser.Visibility = user.Visibility;
_db.Users.Update(existingUser);
await _db.SaveChangesAsync();
return user;
+4 -4
View File
@@ -4,9 +4,9 @@ namespace SharpbinV3.Server.Services
{
public interface IUserService
{
Task<User?> GetByUID(int uid);
Task<User?> GetByUsername(string username);
Task<User?> GetByUUID(Guid uuid);
Task<User?> GetByEmail(string email);
Task<User?> GetByUID(int uid, bool withPastes = false);
Task<User?> GetByUsername(string username, bool withPastes = false);
Task<User?> GetByUUID(Guid uuid, bool withPastes = false);
Task<User?> GetByEmail(string email, bool withPastes = false);
}
}
+5
View File
@@ -32,6 +32,11 @@ namespace SharpbinV3.Server.Services
ExpiresAt = expiresAt,
};
_db.Pastes.Add(paste);
if (author != null)
{
author.Pastes.Add(paste);
_db.Users.Update(author);
}
await _db.SaveChangesAsync();
return paste;
}
+30 -4
View File
@@ -8,10 +8,36 @@ namespace SharpbinV3.Server.Services
public sealed class UserService(AppDbContext db) : IUserService
{
private readonly AppDbContext _db = db;
public Task<User?> GetByUID(int uid, bool withPastes = false)
{
IQueryable<User> query = _db.Users;
if (withPastes)
query = query.Include(u => u.Pastes);
return query.FirstOrDefaultAsync(u => u.UID == uid);
}
public Task<User?> GetByUID(int uid) => _db.Users.FirstOrDefaultAsync(u => u.UID == uid);
public Task<User?> GetByUUID(Guid uuid) => _db.Users.FirstOrDefaultAsync(u => u.UUID == uuid);
public Task<User?> GetByUsername(string username) => _db.Users.FirstOrDefaultAsync(u => u.Username == username);
public Task<User?> GetByEmail(string email) => _db.Users.FirstOrDefaultAsync(u => u.Email == email);
public Task<User?> GetByUUID(Guid uuid, bool withPastes = false)
{
IQueryable<User> query = _db.Users;
if (withPastes)
query = query.Include(u => u.Pastes);
return query.FirstOrDefaultAsync(u => u.UUID == uuid);
}
public Task<User?> GetByUsername(string username, bool withPastes = false)
{
IQueryable<User> query = _db.Users;
if (withPastes)
query = query.Include(u => u.Pastes);
return query.FirstOrDefaultAsync(u => u.Username == username);
}
public Task<User?> GetByEmail(string email, bool withPastes = false)
{
IQueryable<User> query = _db.Users;
if (withPastes)
query = query.Include(u => u.Pastes);
return query.FirstOrDefaultAsync(u => u.Email == email);
}
}
}
+3 -3
View File
@@ -2,8 +2,8 @@
{
public class JWTSettings
{
public string SecretKey { get; set; } = Utilities.GenerateRandomString(64);
public string Issuer { get; set; } = "SharpbinV3";
public string Audience { get; set; } = "SharpbinV3.Client";
public string Secret { get; set; } = Utilities.GenerateRandomString(64);
public string Issuer { get; set; } = "SharpbinApi";
public string Audience { get; set; } = "SharpbinClient";
}
}
+5
View File
@@ -4,5 +4,10 @@
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"JwtSettings": {
"Secret": "ad277c181e51d2131017abc53a5805ccb85410ab902d2e1e09266304e4e86d6c38f2b2543b708d678dfdbfb76016dcf568925ddb25dc91638a69e479e31a23c9",
"Issuer": "SharpbinApi",
"Audience": "SharpbinClient"
}
}