mirror of
https://github.com/whoswhip/Sharpbin.git
synced 2026-12-06 02:48:43 +00:00
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:
@@ -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>
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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}`;
|
||||
}
|
||||
Reference in New Issue
Block a user