mirror of
https://github.com/whoswhip/Sharpbin.git
synced 2026-12-06 02:48:43 +00:00
feat: reports; improved+simplifed modals; extractError funcction;
refactor: change jwt claims to lowercase; use response dtos for sensitive data fix: nullify user on token clears; change appsettings.dev View_Internal_API_Key
This commit is contained in:
@@ -3,6 +3,7 @@
|
||||
import './layout.css';
|
||||
import favicon from '$lib/assets/favicon.svg';
|
||||
import Navbar from '$lib/components/Navbar.svelte';
|
||||
import ModalHost from '$lib/components/ModalHost.svelte';
|
||||
import { user } from '$lib/stores/user';
|
||||
import { startTokenRefreshInterval, getToken, refreshTokenIfNeeded } from '$lib/utils/auth';
|
||||
import { parseTotpEnabled } from '$lib/utils/totp';
|
||||
@@ -21,7 +22,10 @@
|
||||
onMount(async () => {
|
||||
await refreshTokenIfNeeded();
|
||||
const token = getToken();
|
||||
if (!token) return;
|
||||
if (!token) {
|
||||
user.set(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const res = await fetch('/api/user/me', {
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
@@ -29,7 +33,12 @@
|
||||
|
||||
if (res.ok) {
|
||||
const me = await res.json();
|
||||
user.set({ ...me, totpEnabled: parseTotpEnabled(getToken()) });
|
||||
let userData = me;
|
||||
if (me && 'user' in me && typeof me.user === 'object') {
|
||||
const { user: nestedUser, ...rest } = me;
|
||||
userData = { ...rest, ...nestedUser };
|
||||
}
|
||||
user.set({ ...userData, totpEnabled: parseTotpEnabled(getToken()) });
|
||||
} else {
|
||||
user.set(null);
|
||||
}
|
||||
@@ -50,3 +59,5 @@
|
||||
<Navbar {data} />
|
||||
<div class="h-15 w-full"></div>
|
||||
<slot />
|
||||
|
||||
<ModalHost />
|
||||
|
||||
@@ -4,11 +4,23 @@ import { getServerToken } from '$lib/utils/auth';
|
||||
import { env } from '$env/dynamic/private';
|
||||
|
||||
const apiUrl = process.env.VITE_API_URL || 'http://localhost:5050';
|
||||
const apiKey =
|
||||
env.NODE_ENV === 'development'
|
||||
? 'cccdd42d9f2f648493e402f1da7c855ea798ad510e6bb9ea712dd7bed838e58'
|
||||
: (env.VIEW_INTERNAL_API_KEY ?? env.View_HMAC_Internal_API_Key ?? '');
|
||||
|
||||
export const load: PageServerLoad = async ({ params, fetch, url, cookies }) => {
|
||||
export const load: PageServerLoad = async ({ params, fetch, url, cookies, parent }) => {
|
||||
const { id } = params;
|
||||
const parentData = await parent().catch(() => null);
|
||||
|
||||
const token = getServerToken(cookies);
|
||||
|
||||
const pasteRes = await fetch(`${apiUrl}/api/paste/${id}`, {
|
||||
headers: {
|
||||
Authorization: token ? `Bearer ${token}` : ''
|
||||
}
|
||||
});
|
||||
|
||||
const pasteRes = await fetch(`${apiUrl}/api/paste/${id}`);
|
||||
if (pasteRes.status === 404) {
|
||||
return {
|
||||
status: 404,
|
||||
@@ -16,9 +28,6 @@ export const load: PageServerLoad = async ({ params, fetch, url, cookies }) => {
|
||||
};
|
||||
}
|
||||
|
||||
const token = getServerToken(cookies);
|
||||
const apiKey = env.VIEW_INTERNAL_API_KEY ?? env.View_HMAC_Internal_API_Key ?? '';
|
||||
|
||||
const viewed = await fetch(`${apiUrl}/api/paste/${id}/view`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
@@ -29,7 +38,7 @@ export const load: PageServerLoad = async ({ params, fetch, url, cookies }) => {
|
||||
|
||||
const pasteData = await pasteRes.json();
|
||||
const paste = pasteData.paste as Paste;
|
||||
|
||||
|
||||
if (viewed.status === 200) {
|
||||
const viewJson = await viewed.json();
|
||||
if (viewJson.success === true && viewJson.message !== 'View already recorded.') {
|
||||
@@ -51,5 +60,14 @@ export const load: PageServerLoad = async ({ params, fetch, url, cookies }) => {
|
||||
const options = await pasteOptions.json();
|
||||
const content = await pasteContent.text();
|
||||
|
||||
return { paste, content, options, url: url.href };
|
||||
return {
|
||||
paste,
|
||||
content,
|
||||
options,
|
||||
authOptions:
|
||||
parentData && typeof parentData === 'object' && parentData !== null && 'options' in parentData
|
||||
? (parentData as { options?: unknown }).options
|
||||
: null,
|
||||
url: url.href
|
||||
};
|
||||
};
|
||||
|
||||
@@ -18,7 +18,8 @@
|
||||
Download,
|
||||
Copy,
|
||||
Check,
|
||||
CalendarCog
|
||||
CalendarCog,
|
||||
Flag
|
||||
} from '@lucide/svelte/icons/index';
|
||||
import {
|
||||
formatBytes,
|
||||
@@ -34,13 +35,11 @@
|
||||
import { getToken } from '$lib/utils/auth';
|
||||
import { user } from '$lib/stores/user';
|
||||
import Dropdown from '$lib/components/Dropdown.svelte';
|
||||
import Modal from '$lib/components/Modal.svelte';
|
||||
import { openModal } from '$lib/stores/modal';
|
||||
import type { Paste } from '$lib/types/paste';
|
||||
export let data: PageData;
|
||||
|
||||
let showModal = false;
|
||||
let modalResolve: ((value: string) => void) | null = null;
|
||||
let modalMode: 'decrypt' | 'encrypt' | 'confirm' = 'decrypt';
|
||||
let reportSiteKey: string | null = null;
|
||||
let editing = false;
|
||||
let editContent: string | null = null;
|
||||
let editMetadata: Paste | null = data.paste ? { ...data.paste } : null;
|
||||
@@ -60,6 +59,7 @@
|
||||
: false;
|
||||
|
||||
let interval: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
const syntaxOptions =
|
||||
data.options?.syntaxes?.map((lang: string) => ({
|
||||
value: lang,
|
||||
@@ -86,6 +86,13 @@
|
||||
label: visibility.displayName
|
||||
})) ?? [];
|
||||
|
||||
const modalTitleMap = {
|
||||
decrypt: 'Decrypt Paste',
|
||||
encrypt: 'Encrypt Paste',
|
||||
confirm: 'Are you sure you want to delete this paste?',
|
||||
report: 'Report Paste'
|
||||
};
|
||||
|
||||
onMount(() => {
|
||||
interval = setInterval(() => {
|
||||
now = new Date();
|
||||
@@ -230,12 +237,26 @@
|
||||
}
|
||||
}
|
||||
|
||||
async function promptUser(mode: 'decrypt' | 'encrypt' | 'confirm' = 'decrypt'): Promise<string> {
|
||||
return new Promise((resolve) => {
|
||||
showModal = true;
|
||||
modalResolve = resolve;
|
||||
modalMode = mode;
|
||||
});
|
||||
async function promptUser(mode: 'decrypt' | 'encrypt' | 'confirm' | 'report' = 'decrypt') {
|
||||
const title = modalTitleMap[mode];
|
||||
if (mode === 'confirm') {
|
||||
const ok = await openModal<boolean>({ mode, title, cancelValue: false });
|
||||
return ok ? 'true' : '';
|
||||
}
|
||||
if (mode === 'report') {
|
||||
await openModal({
|
||||
mode,
|
||||
title,
|
||||
reportTarget: 'paste',
|
||||
reportTargetId: data.paste?.id ?? null,
|
||||
reportSiteKey,
|
||||
cancelValue: ''
|
||||
});
|
||||
return '';
|
||||
}
|
||||
const value = await openModal<string>({ mode, title, error: decryptError, cancelValue: '' });
|
||||
decryptError = '';
|
||||
return value;
|
||||
}
|
||||
|
||||
onMount(async () => {
|
||||
@@ -280,6 +301,9 @@
|
||||
});
|
||||
|
||||
$: if (data?.paste && (data.paste.visibility !== 2 || decryptedContent !== null)) renderCode();
|
||||
$: reportSiteKey =
|
||||
(data as unknown as { authOptions?: { cf_turnstile_site_key?: string | null } }).authOptions
|
||||
?.cf_turnstile_site_key ?? null;
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
@@ -370,6 +394,17 @@
|
||||
>
|
||||
</div>
|
||||
|
||||
{#if data.paste.reportCount !== null && data.paste.reportCount > 0}
|
||||
<div class="flex shrink-0 items-center">
|
||||
<Flag class="mr-2 h-6 w-6 text-neutral-400" />
|
||||
<a
|
||||
class="text-neutral-400 hover:text-neutral-200 hover:underline"
|
||||
href={resolve(`/reports?target=pastes&pasteId=${data.paste.id}`)}
|
||||
>{data.paste.reportCount} report{data.paste.reportCount !== 1 ? 's' : ''}</a
|
||||
>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="flex shrink-0 items-center">
|
||||
<CalendarDays class="mr-2 h-6 w-6 text-neutral-400" />
|
||||
<span
|
||||
@@ -558,6 +593,18 @@
|
||||
|
||||
<span class="text-neutral-300">Download</span>
|
||||
</button>
|
||||
{#if $user !== null && $user.uuid !== data.paste?.author?.uuid}
|
||||
<button
|
||||
type="button"
|
||||
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-amber-600/50"
|
||||
on:click={() => {
|
||||
promptUser('report');
|
||||
}}
|
||||
>
|
||||
<Flag class="mr-1 h-5 w-5 text-amber-400" />
|
||||
<span class="text-amber-300">Report</span>
|
||||
</button>
|
||||
{/if}
|
||||
{#if $user && ($user.uuid === data.paste?.author?.uuid || $user.roles.some((r) => r === 1 || r === 255))}
|
||||
{#if !editing}
|
||||
<button
|
||||
@@ -661,33 +708,6 @@
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<Modal
|
||||
bind:show={showModal}
|
||||
mode={modalMode}
|
||||
error={decryptError}
|
||||
onConfirm={(value) => {
|
||||
if (modalResolve) {
|
||||
modalResolve(String(value));
|
||||
modalResolve = null;
|
||||
}
|
||||
showModal = false;
|
||||
decryptError = '';
|
||||
}}
|
||||
onCancel={() => {
|
||||
showModal = false;
|
||||
decryptError = '';
|
||||
if (modalResolve) {
|
||||
modalResolve('');
|
||||
modalResolve = null;
|
||||
}
|
||||
}}
|
||||
title={modalMode === 'decrypt'
|
||||
? 'Decrypt Paste'
|
||||
: modalMode === 'encrypt'
|
||||
? 'Encrypt Paste'
|
||||
: 'Are you sure you want to delete this paste?'}
|
||||
/>
|
||||
|
||||
<style>
|
||||
.hljs {
|
||||
background-color: var(--color-neutral-800) !important;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { resolve } from '$app/paths';
|
||||
import { setTokens, startTokenRefreshInterval } from '$lib/utils/auth';
|
||||
import { extractError } from '$lib/utils/misc';
|
||||
import { onMount } from 'svelte';
|
||||
import type { PageData } from './$types';
|
||||
|
||||
@@ -56,8 +57,8 @@
|
||||
});
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
if (data.result.token && data.result.refreshToken) {
|
||||
setTokens(data.result.token, data.result.refreshToken);
|
||||
if (data.token && data.refreshToken) {
|
||||
setTokens(data.token, data.refreshToken);
|
||||
startTokenRefreshInterval();
|
||||
}
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
@@ -72,19 +73,9 @@
|
||||
if (window.turnstile) {
|
||||
window.turnstile.reset();
|
||||
}
|
||||
if (resData.errors) {
|
||||
const messages = Object.values(resData.errors).flat();
|
||||
error = messages.join('\n');
|
||||
} else {
|
||||
if (resData.message === 'TOTP code is required.') {
|
||||
totpEnabled = true;
|
||||
}
|
||||
if (resData.message === 'Verification failed.') {
|
||||
if (window.turnstile) {
|
||||
window.turnstile.reset();
|
||||
}
|
||||
}
|
||||
error = resData.message || 'Login failed. Please try again.';
|
||||
error = extractError(resData) || 'Login failed. Please try again.';
|
||||
if (error === 'TOTP code is required.') {
|
||||
totpEnabled = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { goto } from '$app/navigation';
|
||||
import { setTokens, startTokenRefreshInterval } from '$lib/utils/auth';
|
||||
import { extractError } from '$lib/utils/misc';
|
||||
import { Check, X } from '@lucide/svelte';
|
||||
import { slide, fade } from 'svelte/transition';
|
||||
import { resolve } from '$app/paths';
|
||||
@@ -103,12 +104,12 @@
|
||||
const messages = Object.values(resData.errors).flat();
|
||||
error = messages.join('\n');
|
||||
} else {
|
||||
if (resData.message === 'Verification failed.') {
|
||||
error = extractError(resData) || 'Registration failed. Please try again.';
|
||||
if (error === 'Verification failed.') {
|
||||
if (window.turnstile) {
|
||||
window.turnstile.reset();
|
||||
}
|
||||
}
|
||||
error = resData.message || 'Registration failed. Please try again.';
|
||||
}
|
||||
}
|
||||
loading = false;
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { PageServerLoad } from './$types';
|
||||
import { error } from '@sveltejs/kit';
|
||||
import { env } from '$env/dynamic/private';
|
||||
import { getServerToken } from '$lib/utils/auth';
|
||||
import type { Report } from '$lib/types/report';
|
||||
|
||||
const API_URL = env.VITE_API_URL ?? 'http://localhost:5050';
|
||||
|
||||
function decodeJwtRoles(token?: string | null): number[] {
|
||||
try {
|
||||
if (!token) return [];
|
||||
const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString());
|
||||
const roles = payload?.role;
|
||||
if (Array.isArray(roles)) {
|
||||
return roles.map((r: string) => parseInt(r, 10)).filter((r: number) => !isNaN(r));
|
||||
}
|
||||
return [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export const load: PageServerLoad = async ({ fetch, cookies, params, url }) => {
|
||||
const token = getServerToken(cookies);
|
||||
if (!token) throw error(401, 'Login required');
|
||||
const roles = decodeJwtRoles(token);
|
||||
const canEdit = roles.includes(1) || roles.includes(255);
|
||||
|
||||
const res = await fetch(`${API_URL}/api/report/${params.reportId}`, {
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const { message } = await res.json().catch(() => ({}));
|
||||
throw error(res.status, message ?? 'Request failed');
|
||||
}
|
||||
|
||||
const report = (await res.json()) as Report;
|
||||
const optionsRes = await fetch(`${API_URL}/api/report/options`);
|
||||
const options = optionsRes.ok ? await optionsRes.json() : { types: [], statuses: [] };
|
||||
|
||||
return { report, url: url.href, canEdit, options };
|
||||
};
|
||||
@@ -0,0 +1,165 @@
|
||||
<script lang="ts">
|
||||
import type { PageData } from './$types';
|
||||
import { resolve } from '$app/paths';
|
||||
import { reportStatusLabels, reportTargetLabels, reportTypeLabels } from '$lib/types/report';
|
||||
import { tooltip } from '$lib/utils/misc';
|
||||
import { getToken } from '$lib/utils/auth';
|
||||
|
||||
export let data: PageData;
|
||||
|
||||
const report = data.report;
|
||||
let saving = false;
|
||||
let saveError = '';
|
||||
const statusOptions = data.options?.statuses ?? [];
|
||||
const typeOptions = data.options?.types ?? [];
|
||||
let statusValue = reportStatusLabels[report.status] ?? '';
|
||||
let typeValue = reportTypeLabels[report.type] ?? '';
|
||||
|
||||
async function updateReport() {
|
||||
saveError = '';
|
||||
saving = true;
|
||||
const token = getToken();
|
||||
const res = await fetch(`/api/report/${report.reportID}`, {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {})
|
||||
},
|
||||
body: JSON.stringify({ status: statusValue, type: typeValue })
|
||||
});
|
||||
if (!res.ok) {
|
||||
const { message } = await res.json().catch(() => ({}));
|
||||
saveError = message ?? 'Failed to update report.';
|
||||
saving = false;
|
||||
return;
|
||||
}
|
||||
const updated = await res.json();
|
||||
report.status = updated.status ?? report.status;
|
||||
report.type = updated.type ?? report.type;
|
||||
report.updatedAt = updated.updatedAt ?? report.updatedAt;
|
||||
report.description = updated.description ?? report.description;
|
||||
saving = false;
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<title>Report #{report.reportID} - Sharpbin</title>
|
||||
</svelte:head>
|
||||
|
||||
<main
|
||||
class="flex min-h-[calc(100vh-60px)] w-full flex-col items-center justify-center pt-5 pb-5 text-white"
|
||||
>
|
||||
<div class="mx-auto w-[95%] max-w-4xl rounded border-2 border-neutral-800 bg-neutral-900 p-6">
|
||||
<h1 class="mb-6 text-center text-3xl font-bold">Report #{report.reportID}</h1>
|
||||
<div class="space-y-4">
|
||||
<div class="flex flex-wrap items-center gap-3 text-neutral-300">
|
||||
<span class="rounded bg-neutral-800 px-3 py-1">
|
||||
{reportTypeLabels[report.type] ?? 'Other'}
|
||||
</span>
|
||||
<span class="rounded bg-neutral-800 px-3 py-1">
|
||||
{reportStatusLabels[report.status] ?? 'Open'}
|
||||
</span>
|
||||
<span class="rounded bg-neutral-800 px-3 py-1">
|
||||
{reportTargetLabels[report.targetType] ?? 'Unknown'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="space-y-2 text-sm text-neutral-400">
|
||||
<div>
|
||||
Reporter:
|
||||
{#if report.reporterUsername}
|
||||
<a
|
||||
class="text-neutral-200 hover:text-white hover:underline"
|
||||
href={resolve(`/user/${report.reporterUsername}`)}
|
||||
use:tooltip={report.reporterUUID}
|
||||
>
|
||||
{report.reporterDisplayName || report.reporterUsername}
|
||||
</a>
|
||||
{:else}
|
||||
<span>{report.reporterUUID}</span>
|
||||
{/if}
|
||||
</div>
|
||||
{#if report.pasteId}
|
||||
<div>
|
||||
Target Paste:
|
||||
<a
|
||||
class="text-neutral-200 hover:text-white hover:underline"
|
||||
href={resolve(`/${report.pasteId}`)}
|
||||
>
|
||||
{report.pasteTitle !== '' ? report.pasteTitle : report.pasteId}
|
||||
</a>
|
||||
</div>
|
||||
{/if}
|
||||
{#if report.userUUID}
|
||||
<div>
|
||||
Target User:
|
||||
{#if report.targetUsername}
|
||||
<a
|
||||
class="text-neutral-200 hover:text-white hover:underline"
|
||||
href={resolve(`/user/${report.targetUsername}`)}
|
||||
use:tooltip={report.userUUID}
|
||||
>
|
||||
{report.targetDisplayName || report.targetUsername}
|
||||
</a>
|
||||
{:else}
|
||||
<span>{report.userUUID}</span>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
<div>Created: {new Date(report.createdAt * 1000).toLocaleString()}</div>
|
||||
{#if report.updatedAt}
|
||||
<div>Updated: {new Date(report.updatedAt * 1000).toLocaleString()}</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if data.canEdit}
|
||||
<div class="mt-4 space-y-3">
|
||||
<div class="grid grid-cols-1 gap-3 md:grid-cols-2">
|
||||
<div class="flex flex-col gap-2">
|
||||
<label class="text-sm text-neutral-400" for="report-update-type">Type</label>
|
||||
<select
|
||||
id="report-update-type"
|
||||
class="rounded border border-neutral-700 bg-neutral-800 p-2"
|
||||
bind:value={typeValue}
|
||||
>
|
||||
{#each typeOptions as t (t)}
|
||||
<option value={t}>{t}</option>
|
||||
{/each}
|
||||
</select>
|
||||
</div>
|
||||
<div class="flex flex-col gap-2">
|
||||
<label class="text-sm text-neutral-400" for="report-update-status">Status</label>
|
||||
<select
|
||||
id="report-update-status"
|
||||
class="rounded border border-neutral-700 bg-neutral-800 p-2"
|
||||
bind:value={statusValue}
|
||||
>
|
||||
{#each statusOptions as s (s)}
|
||||
<option value={s}>{s}</option>
|
||||
{/each}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center gap-3">
|
||||
<button
|
||||
class="rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600 disabled:opacity-60"
|
||||
on:click={updateReport}
|
||||
disabled={saving}
|
||||
>
|
||||
{saving ? 'Saving...' : 'Update Report'}
|
||||
</button>
|
||||
{#if saveError}
|
||||
<span class="text-sm text-red-300">{saveError}</span>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if report.description}
|
||||
<div class="rounded border border-neutral-700 bg-neutral-800 p-4 text-neutral-200">
|
||||
{report.description}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
@@ -0,0 +1,71 @@
|
||||
import type { PageServerLoad } from './$types';
|
||||
import { error } from '@sveltejs/kit';
|
||||
import { env } from '$env/dynamic/private';
|
||||
import { getServerToken } from '$lib/utils/auth';
|
||||
import type { ReportListResponse } from '$lib/types/report';
|
||||
import { extractError } from '$lib/utils/misc';
|
||||
|
||||
const API_URL = env.VITE_API_URL ?? 'http://localhost:5050';
|
||||
|
||||
function decodeJwtRoles(token?: string | null): number[] {
|
||||
try {
|
||||
if (!token) return [];
|
||||
const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString());
|
||||
const roles = payload?.role;
|
||||
if (Array.isArray(roles)) {
|
||||
return roles.map((r: string) => parseInt(r, 10)).filter((r: number) => !isNaN(r));
|
||||
}
|
||||
return [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeTarget(value: string | null): 'all' | 'pastes' | 'users' {
|
||||
if (value === 'pastes' || value === 'users') return value;
|
||||
return 'all';
|
||||
}
|
||||
|
||||
export const load: PageServerLoad = async ({ fetch, cookies, url }) => {
|
||||
const token = getServerToken(cookies);
|
||||
if (!token) throw error(401, 'Login required');
|
||||
|
||||
const roles = decodeJwtRoles(token);
|
||||
if (!roles.includes(1) && !roles.includes(255)) {
|
||||
throw error(403, 'You do not have permission to view reports.');
|
||||
}
|
||||
|
||||
const target = normalizeTarget(url.searchParams.get('target'));
|
||||
const status = url.searchParams.get('status') ?? '';
|
||||
const type = url.searchParams.get('type') ?? '';
|
||||
const pasteId = url.searchParams.get('pasteId') ?? '';
|
||||
const userUuid = url.searchParams.get('userUuid') ?? '';
|
||||
const pageParam = Number(url.searchParams.get('page') ?? '1');
|
||||
const page = Number.isFinite(pageParam) ? Math.max(1, pageParam) : 1;
|
||||
|
||||
const query = new URLSearchParams({ page: String(page), pageSize: '20' });
|
||||
if (status) query.set('status', status);
|
||||
if (type) query.set('type', type);
|
||||
if ((target === 'pastes' || target === 'all') && pasteId) query.set('pasteId', pasteId);
|
||||
if ((target === 'users' || target === 'all') && userUuid) query.set('userUUID', userUuid);
|
||||
|
||||
const reportsRes = await fetch(`${API_URL}/api/report/${target}?${query.toString()}`, {
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
});
|
||||
|
||||
if (!reportsRes.ok) {
|
||||
const json = await reportsRes.json().catch(() => ({}));
|
||||
throw error(reportsRes.status, extractError(json) ?? 'Request failed');
|
||||
}
|
||||
|
||||
const reports = (await reportsRes.json()) as ReportListResponse;
|
||||
|
||||
const optionsRes = await fetch(`${API_URL}/api/report/options`);
|
||||
const options = optionsRes.ok ? await optionsRes.json() : { types: [], statuses: [] };
|
||||
|
||||
return {
|
||||
reports,
|
||||
options,
|
||||
filters: { target, status, type, pasteId, userUuid, page }
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,272 @@
|
||||
<script lang="ts">
|
||||
import type { PageData } from './$types';
|
||||
import { resolve } from '$app/paths';
|
||||
import { goto } from '$app/navigation';
|
||||
import { reportStatusLabels, reportTargetLabels, reportTypeLabels } from '$lib/types/report';
|
||||
import { tooltip } from '$lib/utils/misc';
|
||||
import { SvelteURLSearchParams } from 'svelte/reactivity';
|
||||
|
||||
export let data: PageData;
|
||||
|
||||
let target = data.filters.target;
|
||||
let status = data.filters.status;
|
||||
let type = data.filters.type ?? '';
|
||||
let pasteId = data.filters.pasteId;
|
||||
let userUuid = data.filters.userUuid;
|
||||
let mixedTarget = target === 'all' ? pasteId || userUuid : '';
|
||||
let inputTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
const targets = [
|
||||
{ value: 'all', label: 'All' },
|
||||
{ value: 'pastes', label: 'Pastes' },
|
||||
{ value: 'users', label: 'Users' }
|
||||
];
|
||||
|
||||
const statuses = data.options?.statuses ?? [];
|
||||
const types = data.options?.types ?? [];
|
||||
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
function applyFilters(page = 1) {
|
||||
const params = new SvelteURLSearchParams();
|
||||
params.set('target', target);
|
||||
if (status) params.set('status', status);
|
||||
if (type) params.set('type', type);
|
||||
if (target === 'pastes' && pasteId.trim()) params.set('pasteId', pasteId.trim());
|
||||
if (target === 'users' && userUuid.trim()) params.set('userUuid', userUuid.trim());
|
||||
if (target === 'all' && pasteId.trim()) params.set('pasteId', pasteId.trim());
|
||||
if (target === 'all' && userUuid.trim()) params.set('userUuid', userUuid.trim());
|
||||
params.set('page', String(page));
|
||||
// eslint-disable-next-line svelte/no-navigation-without-resolve
|
||||
goto(`?${params.toString()}`);
|
||||
}
|
||||
|
||||
function scheduleInputApply() {
|
||||
if (inputTimer) clearTimeout(inputTimer);
|
||||
inputTimer = setTimeout(() => applyFilters(1), 300);
|
||||
}
|
||||
|
||||
function handleTargetChange(value: string) {
|
||||
target = value as 'all' | 'pastes' | 'users';
|
||||
if (target === 'all') {
|
||||
mixedTarget = pasteId || userUuid;
|
||||
applyFilters(1);
|
||||
return;
|
||||
}
|
||||
if (target === 'pastes') {
|
||||
userUuid = '';
|
||||
mixedTarget = '';
|
||||
applyFilters(1);
|
||||
return;
|
||||
}
|
||||
pasteId = '';
|
||||
mixedTarget = '';
|
||||
applyFilters(1);
|
||||
}
|
||||
|
||||
function handleTargetInput(value: string) {
|
||||
if (target === 'pastes') {
|
||||
pasteId = value;
|
||||
userUuid = '';
|
||||
scheduleInputApply();
|
||||
return;
|
||||
}
|
||||
if (target === 'users') {
|
||||
userUuid = value;
|
||||
pasteId = '';
|
||||
scheduleInputApply();
|
||||
return;
|
||||
}
|
||||
mixedTarget = value;
|
||||
const trimmed = value.trim();
|
||||
if (uuidRegex.test(trimmed)) {
|
||||
userUuid = trimmed;
|
||||
pasteId = '';
|
||||
} else if (/^\d+$/.test(trimmed)) {
|
||||
pasteId = trimmed;
|
||||
userUuid = '';
|
||||
} else {
|
||||
pasteId = '';
|
||||
userUuid = '';
|
||||
}
|
||||
scheduleInputApply();
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<title>Reports - Sharpbin</title>
|
||||
</svelte:head>
|
||||
|
||||
<main
|
||||
class="flex min-h-[calc(100vh-60px)] w-full flex-col items-center justify-center pt-5 pb-5 text-white"
|
||||
>
|
||||
<div class="mx-auto w-[95%] max-w-6xl rounded border-2 border-neutral-800 bg-neutral-900 p-6">
|
||||
<h1 class="mb-6 text-center text-4xl font-bold">Reports</h1>
|
||||
<div class="mb-6 grid grid-cols-1 gap-4 md:grid-cols-5">
|
||||
<div class="flex flex-col gap-2">
|
||||
<label class="text-sm text-neutral-400" for="report-target">Target</label>
|
||||
<select
|
||||
id="report-target"
|
||||
class="rounded border border-neutral-700 bg-neutral-800 p-2"
|
||||
bind:value={target}
|
||||
on:change={(e) => {
|
||||
if (e.currentTarget instanceof HTMLSelectElement) {
|
||||
handleTargetChange(e.currentTarget.value);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{#each targets as t (t.value)}
|
||||
<option value={t.value}>{t.label}</option>
|
||||
{/each}
|
||||
</select>
|
||||
</div>
|
||||
<div class="flex flex-col gap-2">
|
||||
<label class="text-sm text-neutral-400" for="report-status">Status</label>
|
||||
<select
|
||||
id="report-status"
|
||||
class="rounded border border-neutral-700 bg-neutral-800 p-2"
|
||||
bind:value={status}
|
||||
on:change={() => applyFilters(1)}
|
||||
>
|
||||
<option value="">Any</option>
|
||||
{#each statuses as s (s)}
|
||||
<option value={s}>{s}</option>
|
||||
{/each}
|
||||
</select>
|
||||
</div>
|
||||
<div class="flex flex-col gap-2">
|
||||
<label class="text-sm text-neutral-400" for="report-type">Type</label>
|
||||
<select
|
||||
id="report-type"
|
||||
class="rounded border border-neutral-700 bg-neutral-800 p-2"
|
||||
bind:value={type}
|
||||
on:change={() => applyFilters(1)}
|
||||
>
|
||||
<option value="">Any</option>
|
||||
{#each types as t (t)}
|
||||
<option value={t}>{t}</option>
|
||||
{/each}
|
||||
</select>
|
||||
</div>
|
||||
<div class="flex flex-col gap-2 md:col-span-2">
|
||||
<label class="text-sm text-neutral-400" for="report-target-id">
|
||||
{target === 'pastes'
|
||||
? 'Paste ID'
|
||||
: target === 'users'
|
||||
? 'User UUID'
|
||||
: 'Paste ID or User UUID'}
|
||||
</label>
|
||||
<input
|
||||
id="report-target-id"
|
||||
type="text"
|
||||
class="rounded border border-neutral-700 bg-neutral-800 p-2"
|
||||
placeholder={target === 'pastes'
|
||||
? 'Paste ID'
|
||||
: target === 'users'
|
||||
? 'User UUID'
|
||||
: 'Paste ID or User UUID'}
|
||||
value={target === 'pastes' ? pasteId : target === 'users' ? userUuid : mixedTarget}
|
||||
on:input={(e) => {
|
||||
if (e.currentTarget instanceof HTMLInputElement) {
|
||||
handleTargetInput(e.currentTarget.value);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if data.reports.reports.length > 0}
|
||||
<div class="space-y-3">
|
||||
{#each data.reports.reports as report (report.reportID)}
|
||||
<div
|
||||
class="flex cursor-pointer flex-col gap-2 rounded border border-neutral-700 bg-neutral-800 px-5 py-4 transition-colors duration-200 hover:bg-neutral-700 focus:ring-2 focus:ring-neutral-600 focus:outline-none"
|
||||
role="link"
|
||||
tabindex="0"
|
||||
on:click={() => goto(resolve(`/report/${report.reportID}`))}
|
||||
on:keydown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
goto(resolve(`/report/${report.reportID}`));
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||
<span class="text-lg font-semibold text-neutral-100">
|
||||
Report #{report.reportID}
|
||||
</span>
|
||||
<span class="text-sm text-neutral-300">
|
||||
{reportTypeLabels[report.type] ?? 'Other'}
|
||||
· {reportStatusLabels[report.status] ?? 'Open'}
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-3 text-sm text-neutral-400">
|
||||
<span>{reportTargetLabels[report.targetType] ?? 'Unknown'}</span>
|
||||
{#if report.pasteId}
|
||||
<a
|
||||
href={resolve(`/${report.pasteId}`)}
|
||||
class="text-neutral-300 hover:text-white"
|
||||
on:click|stopPropagation
|
||||
>
|
||||
{report.pasteTitle !== '' ? report.pasteTitle : report.pasteId}
|
||||
</a>
|
||||
{/if}
|
||||
{#if report.userUUID}
|
||||
{#if report.targetUsername}
|
||||
<a
|
||||
href={resolve(`/user/${report.targetUsername}`)}
|
||||
class="text-neutral-300 hover:text-white"
|
||||
use:tooltip={report.userUUID}
|
||||
on:click|stopPropagation
|
||||
>
|
||||
{report.targetDisplayName || report.targetUsername}
|
||||
</a>
|
||||
{:else}
|
||||
<span>{report.userUUID}</span>
|
||||
{/if}
|
||||
{/if}
|
||||
{#if report.reporterUsername}
|
||||
<a
|
||||
href={resolve(`/user/${report.reporterUsername}`)}
|
||||
class="text-neutral-300 hover:text-white"
|
||||
use:tooltip={report.reporterUUID}
|
||||
on:click|stopPropagation
|
||||
>
|
||||
{report.reporterDisplayName || report.reporterUsername}
|
||||
</a>
|
||||
{:else}
|
||||
<span>{report.reporterUUID}</span>
|
||||
{/if}
|
||||
<span>Created {new Date(report.createdAt * 1000).toLocaleString()}</span>
|
||||
</div>
|
||||
{#if report.description}
|
||||
<p class="text-sm text-neutral-300">{report.description}</p>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{:else}
|
||||
<p class="text-center text-neutral-400">No reports found.</p>
|
||||
{/if}
|
||||
|
||||
{#if data.reports.pagination.totalPages > 1}
|
||||
<div class="mt-6 flex items-center justify-center gap-4">
|
||||
<button
|
||||
class="rounded bg-neutral-700 px-3 py-1 disabled:opacity-50"
|
||||
on:click={() => applyFilters(data.reports.pagination.page - 1)}
|
||||
disabled={data.reports.pagination.page <= 1}
|
||||
>
|
||||
Prev
|
||||
</button>
|
||||
<span class="text-neutral-400">
|
||||
Page {data.reports.pagination.page} of {data.reports.pagination.totalPages}
|
||||
</span>
|
||||
<button
|
||||
class="rounded bg-neutral-700 px-3 py-1 disabled:opacity-50"
|
||||
on:click={() => applyFilters(data.reports.pagination.page + 1)}
|
||||
disabled={data.reports.pagination.page >= data.reports.pagination.totalPages}
|
||||
>
|
||||
Next
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</main>
|
||||
@@ -1,34 +1,97 @@
|
||||
import type { PageServerLoad } from './$types';
|
||||
import { error } from '@sveltejs/kit';
|
||||
import { env } from '$env/dynamic/private';
|
||||
import { getServerToken } from '$lib/utils/auth';
|
||||
import type { User } from '$lib/types/user';
|
||||
import type { Paste } from '$lib/types/paste';
|
||||
import type { Pagination } from '$lib/types/pagination';
|
||||
import type { Report, ReportListResponse } from '$lib/types/report';
|
||||
|
||||
const apiUrl = process.env.VITE_API_URL || 'http://localhost:5050';
|
||||
const API_URL = env.VITE_API_URL ?? 'http://localhost:5050';
|
||||
|
||||
export const load: PageServerLoad = async ({ params, fetch, cookies, url }) => {
|
||||
const { username } = params;
|
||||
const token = getServerToken(cookies);
|
||||
|
||||
const res = await fetch(`${apiUrl}/api/user/${username}`, {
|
||||
headers: {
|
||||
Authorization: token ? `Bearer ${token}` : ''
|
||||
function decodeJwtRoles(token?: string | null): number[] {
|
||||
try {
|
||||
if (!token) return [];
|
||||
const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString());
|
||||
const roles = payload?.role;
|
||||
if (Array.isArray(roles)) {
|
||||
return roles.map((r: string) => parseInt(r, 10)).filter((r: number) => !isNaN(r));
|
||||
}
|
||||
return [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function decodeJwtUuid(token?: string | null): string | null {
|
||||
try {
|
||||
if (!token) return null;
|
||||
const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString());
|
||||
const uuid = payload?.uuid;
|
||||
return typeof uuid === 'string' ? uuid : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export const load: PageServerLoad = async ({ params, fetch, cookies, url, parent }) => {
|
||||
const token = getServerToken(cookies);
|
||||
const { username } = params;
|
||||
const { options } = await parent();
|
||||
const jwtUuid = decodeJwtUuid(token);
|
||||
|
||||
const res = await fetch(`${API_URL}/api/user/${username}`, {
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : undefined
|
||||
});
|
||||
|
||||
if (res.status === 500) {
|
||||
return {
|
||||
status: 500,
|
||||
error: { message: 'Internal server error' }
|
||||
if (!res.ok) {
|
||||
const { message } = await res.json().catch(() => ({}));
|
||||
throw error(res.status, message ?? 'Request failed');
|
||||
}
|
||||
|
||||
const { user, pastes, pagination, reports, reportsPagination } = (await res.json()) as {
|
||||
user: User;
|
||||
pastes: Paste[];
|
||||
pagination: Pagination;
|
||||
reports?: Report[];
|
||||
reportsPagination?: Pagination;
|
||||
};
|
||||
|
||||
const isOwner = jwtUuid ? user.uuid === jwtUuid : false;
|
||||
let reportsTarget: ReportListResponse | null = null;
|
||||
let reportsSubmitted: ReportListResponse | null = null;
|
||||
const roles = token ? decodeJwtRoles(token) : [];
|
||||
const canModerate = roles.includes(255) || roles.includes(1);
|
||||
|
||||
if (isOwner && reports && reportsPagination) {
|
||||
reportsSubmitted = {
|
||||
reports,
|
||||
pagination: reportsPagination
|
||||
};
|
||||
}
|
||||
|
||||
const json = await res.json();
|
||||
|
||||
if (res.status !== 200) {
|
||||
return {
|
||||
status: res.status,
|
||||
error: { message: json.message || 'An error occurred' }
|
||||
};
|
||||
if (token && canModerate && (!reportsSubmitted || !isOwner)) {
|
||||
const submittedRes = await fetch(`${API_URL}/api/user/${user.uuid}/reports/submitted`, {
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
});
|
||||
if (submittedRes.ok) reportsSubmitted = await submittedRes.json();
|
||||
}
|
||||
const user = json as User;
|
||||
return { user, url: url.href };
|
||||
|
||||
if (token && !isOwner) {
|
||||
if (canModerate) {
|
||||
const r = await fetch(`${API_URL}/api/user/${user.uuid}/reports`, {
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
});
|
||||
if (r.ok) reportsTarget = await r.json();
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
user,
|
||||
pastes: { pastes, pagination },
|
||||
reportsTarget,
|
||||
reportsSubmitted,
|
||||
url: url.href,
|
||||
authOptions: options
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { resolve } from '$app/paths';
|
||||
import { goto } from '$app/navigation';
|
||||
import type { PageData } from './$types';
|
||||
import type { Pagination } from '$lib/types/pagination';
|
||||
import {
|
||||
@@ -12,44 +13,40 @@
|
||||
Pencil,
|
||||
Trash2,
|
||||
Clock,
|
||||
Hash
|
||||
Hash,
|
||||
Flag
|
||||
} from '@lucide/svelte';
|
||||
import { extractDateFromUUIDv7, tooltip, dateToRelativeString } from '$lib/utils/misc';
|
||||
import { roles } from '$lib/consts';
|
||||
import { getToken } from '$lib/utils/auth';
|
||||
import { needsAdminTotp } from '$lib/utils/totp';
|
||||
import Modal from '$lib/components/Modal.svelte';
|
||||
import { openModal } from '$lib/stores/modal';
|
||||
import { user } from '$lib/stores/user';
|
||||
import { onMount } from 'svelte';
|
||||
import { reportStatusLabels, reportTargetLabels, reportTypeLabels } from '$lib/types/report';
|
||||
|
||||
export let data: PageData;
|
||||
|
||||
let currentPage = data.user?.pagination?.page ?? 1;
|
||||
let pagination: Pagination = data.user?.pagination ?? {
|
||||
|
||||
let currentPage = data.pastes?.pagination?.page ?? 1;
|
||||
let pagination: Pagination = data.pastes?.pagination ?? {
|
||||
page: 1,
|
||||
pageSize: 50,
|
||||
totalCount: 0,
|
||||
totalPages: 1
|
||||
};
|
||||
let pastes = data.user?.pastes ?? [];
|
||||
let pastes = data.pastes?.pastes ?? [];
|
||||
let loading = false;
|
||||
let isOwner = false;
|
||||
let showEditModal = false;
|
||||
let showDeleteModal = false;
|
||||
let showRoleModal = false;
|
||||
let showTotpModal = false;
|
||||
let showRoleTotpModal = false;
|
||||
let showDeleteTotpModal = false;
|
||||
let modalError = '';
|
||||
let totpEnabled = false;
|
||||
let pendingRoles: number[] | null = null;
|
||||
let roleTotpCode = '';
|
||||
let deleteTotpCode = '';
|
||||
let now = new Date();
|
||||
let interval: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
$: isOwner = data.user && $user ? data.user?.uuid === $user.uuid : false;
|
||||
$: totpEnabled = Boolean($user?.totpEnabled);
|
||||
$: reportsSubmitted = data.reportsSubmitted;
|
||||
$: reportsTarget = data.reportsTarget;
|
||||
|
||||
const roleOptions = [
|
||||
{ label: 'Member', value: 0 },
|
||||
@@ -82,11 +79,22 @@
|
||||
const token = getToken();
|
||||
const currentRoles = data.user?.roles ?? [];
|
||||
const nextRoles = selectedRoles ?? currentRoles;
|
||||
if (needsAdminTotp(totpEnabled, currentRoles, nextRoles) && !roleTotpCode) {
|
||||
pendingRoles = nextRoles;
|
||||
showRoleTotpModal = true;
|
||||
loading = false;
|
||||
return;
|
||||
let totpcode = '';
|
||||
if (needsAdminTotp(totpEnabled, currentRoles, nextRoles)) {
|
||||
totpcode = String(
|
||||
await openModal<string>({
|
||||
mode: 'totp',
|
||||
title: 'Admin role requires TOTP',
|
||||
placeholder: 'Enter 6-digit code',
|
||||
inputType: 'text',
|
||||
confirmButtonText: 'Continue',
|
||||
cancelValue: ''
|
||||
})
|
||||
).trim();
|
||||
if (!totpcode) {
|
||||
loading = false;
|
||||
return;
|
||||
}
|
||||
}
|
||||
const res = await fetch(`/api/user/uuid/${data.user?.uuid}`, {
|
||||
method: 'PATCH',
|
||||
@@ -97,61 +105,70 @@
|
||||
body: JSON.stringify({
|
||||
...(displayName !== undefined ? { displayName: displayName.trim() } : {}),
|
||||
...(selectedRoles !== undefined ? { roles: selectedRoles } : {}),
|
||||
...(roleTotpCode ? { totpcode: roleTotpCode } : {})
|
||||
...(totpcode ? { totpcode } : {})
|
||||
})
|
||||
});
|
||||
loading = false;
|
||||
if (!res.ok) {
|
||||
const err = await res.json();
|
||||
modalError = err.message || 'Failed to update display name';
|
||||
await openModal({
|
||||
mode: 'confirm',
|
||||
title: 'Error',
|
||||
message: modalError,
|
||||
confirmButtonText: 'OK',
|
||||
cancelValue: true
|
||||
});
|
||||
return;
|
||||
}
|
||||
showEditModal = false;
|
||||
showRoleModal = false;
|
||||
data.user!.displayName = displayName || data.user!.displayName;
|
||||
if (selectedRoles !== undefined) {
|
||||
data.user!.roles = selectedRoles;
|
||||
}
|
||||
roleTotpCode = '';
|
||||
showRoleTotpModal = false;
|
||||
pendingRoles = null;
|
||||
modalError = '';
|
||||
}
|
||||
|
||||
function handleRoleTotpConfirm(value: unknown) {
|
||||
if (typeof value === 'string') {
|
||||
roleTotpCode = value.trim();
|
||||
}
|
||||
showRoleTotpModal = false;
|
||||
if (!roleTotpCode) return;
|
||||
handleUserUpdate(undefined, pendingRoles ?? data.user?.roles ?? []);
|
||||
}
|
||||
|
||||
async function handleDeleteAccount() {
|
||||
loading = true;
|
||||
modalError = '';
|
||||
const token = getToken();
|
||||
if (totpEnabled && !deleteTotpCode) {
|
||||
showDeleteTotpModal = true;
|
||||
loading = false;
|
||||
return;
|
||||
let totpcode = '';
|
||||
if (totpEnabled) {
|
||||
totpcode = String(
|
||||
await openModal<string>({
|
||||
mode: 'totp',
|
||||
title: 'Enter TOTP to delete',
|
||||
placeholder: 'Enter 6-digit code',
|
||||
inputType: 'text',
|
||||
confirmButtonText: 'Delete Account',
|
||||
cancelValue: ''
|
||||
})
|
||||
).trim();
|
||||
if (!totpcode) {
|
||||
loading = false;
|
||||
return;
|
||||
}
|
||||
}
|
||||
const res = await fetch(`/api/user/uuid/${data.user?.uuid}`, {
|
||||
method: 'DELETE',
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`
|
||||
},
|
||||
body: totpEnabled && deleteTotpCode ? JSON.stringify({ totpcode: deleteTotpCode }) : undefined
|
||||
body: totpEnabled && totpcode ? JSON.stringify({ totpcode }) : undefined
|
||||
});
|
||||
loading = false;
|
||||
if (!res.ok) {
|
||||
const err = await res.json();
|
||||
modalError = err.message || 'Failed to delete account';
|
||||
await openModal({
|
||||
mode: 'confirm',
|
||||
title: 'Error',
|
||||
message: modalError,
|
||||
confirmButtonText: 'OK',
|
||||
cancelValue: true
|
||||
});
|
||||
return;
|
||||
}
|
||||
showDeleteModal = false;
|
||||
showDeleteTotpModal = false;
|
||||
deleteTotpCode = '';
|
||||
window.location.href = '/';
|
||||
}
|
||||
|
||||
@@ -160,17 +177,57 @@
|
||||
totpEnabled = Boolean((value as { enabled?: boolean }).enabled);
|
||||
}
|
||||
user.update((u) => (u ? { ...u, totpEnabled } : u));
|
||||
showTotpModal = false;
|
||||
modalError = '';
|
||||
}
|
||||
|
||||
function handleDeleteTotpConfirm(value: unknown) {
|
||||
if (typeof value === 'string') {
|
||||
deleteTotpCode = value.trim();
|
||||
async function openEditDisplayName() {
|
||||
const value = String(
|
||||
await openModal<string>({
|
||||
mode: 'prompt',
|
||||
title: 'Edit Display Name',
|
||||
placeholder: 'New Display Name',
|
||||
error: modalError,
|
||||
cancelValue: ''
|
||||
})
|
||||
).trim();
|
||||
if (!value) return;
|
||||
await handleUserUpdate(value);
|
||||
}
|
||||
|
||||
async function openEditRoles() {
|
||||
const value = await openModal({
|
||||
mode: 'multiselect',
|
||||
title: 'Edit User Roles',
|
||||
items: roleOptions,
|
||||
initialValue: data.user?.roles,
|
||||
cancelValue: null
|
||||
});
|
||||
if (!Array.isArray(value)) return;
|
||||
await handleUserUpdate(undefined, value as number[]);
|
||||
}
|
||||
|
||||
async function openDeleteAccount() {
|
||||
const ok = await openModal<boolean>({
|
||||
mode: 'confirm',
|
||||
title: 'Delete Account',
|
||||
message: `This action cannot be undone. ${isOwner ? 'All your' : "This user's"} pastes and account data will be permanently deleted.`,
|
||||
confirmButtonText: 'Delete Account',
|
||||
cancelValue: false
|
||||
});
|
||||
if (!ok) return;
|
||||
await handleDeleteAccount();
|
||||
}
|
||||
|
||||
async function openTotpSetup() {
|
||||
const result = await openModal({
|
||||
mode: 'totpSetup',
|
||||
title: 'Two-Factor Authentication',
|
||||
totpActive: totpEnabled,
|
||||
cancelValue: null
|
||||
});
|
||||
if (result) {
|
||||
handleTotpConfirm(result);
|
||||
}
|
||||
showDeleteTotpModal = false;
|
||||
if (!deleteTotpCode) return;
|
||||
handleDeleteAccount();
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
@@ -181,6 +238,10 @@
|
||||
if (interval) clearInterval(interval);
|
||||
};
|
||||
});
|
||||
|
||||
$: reportSiteKey =
|
||||
(data as unknown as { authOptions?: { cf_turnstile_site_key?: string | null } }).authOptions
|
||||
?.cf_turnstile_site_key ?? null;
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
@@ -206,9 +267,9 @@
|
||||
<main
|
||||
class="flex min-h-[calc(100vh-60px)] w-full flex-col items-center justify-center pt-5 pb-5 text-white"
|
||||
>
|
||||
<div class="w-[95%] max-w-5xl rounded border-2 border-neutral-800 bg-neutral-900 p-6">
|
||||
<div class="relative w-[95%] max-w-5xl rounded border-2 border-neutral-800 bg-neutral-900 p-6">
|
||||
<h1 class="flex items-center justify-center gap-4 text-center text-4xl font-bold">
|
||||
{#if data.user?.roles.includes(403)}
|
||||
{#if data.user?.roles?.includes(403)}
|
||||
<span
|
||||
class="relative flex h-7 w-7 items-center justify-center overflow-hidden rounded-full"
|
||||
use:tooltip={roles[403]}
|
||||
@@ -216,7 +277,7 @@
|
||||
<User class="h-8 w-8 text-neutral-500" />
|
||||
<Ban class="absolute h-7 w-7 text-red-500" />
|
||||
</span>
|
||||
{:else if data.user?.roles.includes(1) || data.user?.roles.includes(255)}
|
||||
{:else if data.user?.roles?.includes(1) || data.user?.roles?.includes(255)}
|
||||
{#if data.user?.roles?.length}
|
||||
<span use:tooltip={roles[Math.max(...data.user.roles) as keyof typeof roles]}>
|
||||
<ShieldUser class="h-8 w-8 text-neutral-400" />
|
||||
@@ -253,6 +314,27 @@
|
||||
>{pagination.totalCount} paste{pagination.totalCount !== 1 ? 's' : ''}</span
|
||||
>
|
||||
</div>
|
||||
{#if reportsSubmitted}
|
||||
<div class="flex shrink-0 items-center">
|
||||
<Flag class="mr-2 h-6 w-6 text-neutral-400" />
|
||||
<span class="text-neutral-400"
|
||||
>{reportsSubmitted.pagination.totalCount} submitted report{reportsSubmitted.pagination
|
||||
.totalCount !== 1
|
||||
? 's'
|
||||
: ''}</span
|
||||
>
|
||||
</div>
|
||||
{/if}
|
||||
{#if reportsTarget}
|
||||
<div class="flex shrink-0 items-center">
|
||||
<Flag class="mr-2 h-6 w-6 text-neutral-400" />
|
||||
<span class="text-neutral-400"
|
||||
>{reportsTarget.pagination.totalCount} report{reportsTarget.pagination.totalCount !== 1
|
||||
? 's'
|
||||
: ''}</span
|
||||
>
|
||||
</div>
|
||||
{/if}
|
||||
<div class="flex shrink-0 items-center">
|
||||
<Hash class="mr-1 h-6 w-6 text-neutral-400" />
|
||||
<span class="text-neutral-400" use:tooltip={`User #${data.user?.uid}`}>
|
||||
@@ -271,13 +353,29 @@
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{#if isOwner || $user?.roles.some((r) => r === 255 || r === 1)}
|
||||
{#if !isOwner || !$user?.roles?.some((r) => r === 403)}
|
||||
<!-- svelte-ignore a11y_click_events_have_key_events -->
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class="absolute top-0 right-0"
|
||||
on:click={() =>
|
||||
openModal({
|
||||
mode: 'report',
|
||||
title: 'Report User',
|
||||
reportTarget: 'user',
|
||||
reportTargetId: data.user?.uuid || '',
|
||||
reportSiteKey: reportSiteKey,
|
||||
confirmButtonText: 'Submit Report',
|
||||
cancelValue: null
|
||||
})}
|
||||
>
|
||||
<Flag class="m-4 h-6 w-6 cursor-pointer text-neutral-400 hover:text-amber-400" />
|
||||
</div>
|
||||
{/if}
|
||||
{#if isOwner || $user?.roles?.some((r) => r === 255 || r === 1)}
|
||||
<div class="mt-4 flex flex-wrap justify-center gap-2">
|
||||
<button
|
||||
on:click={() => {
|
||||
showEditModal = true;
|
||||
modalError = '';
|
||||
}}
|
||||
on:click={openEditDisplayName}
|
||||
class="flex items-center gap-2 rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600"
|
||||
>
|
||||
<Pencil class="h-4 w-4" />
|
||||
@@ -285,34 +383,25 @@
|
||||
</button>
|
||||
{#if isOwner}
|
||||
<button
|
||||
on:click={() => {
|
||||
showTotpModal = true;
|
||||
modalError = '';
|
||||
}}
|
||||
on:click={openTotpSetup}
|
||||
class="flex items-center gap-2 rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600"
|
||||
>
|
||||
<ShieldUser class="h-4 w-4" />
|
||||
{totpEnabled ? 'Manage 2FA' : 'Enable 2FA'}
|
||||
</button>
|
||||
{/if}
|
||||
{#if $user?.roles.some((r) => r === 255)}
|
||||
{#if $user?.roles?.some((r) => r === 255)}
|
||||
<button
|
||||
on:click={() => {
|
||||
showRoleModal = true;
|
||||
modalError = '';
|
||||
}}
|
||||
on:click={openEditRoles}
|
||||
class="flex items-center gap-2 rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600"
|
||||
>
|
||||
<ShieldUser class="h-4 w-4" />
|
||||
Edit Roles
|
||||
</button>
|
||||
{/if}
|
||||
{#if isOwner || $user?.roles.some((r) => r === 255)}
|
||||
{#if isOwner || $user?.roles?.some((r) => r === 255)}
|
||||
<button
|
||||
on:click={() => {
|
||||
showDeleteModal = true;
|
||||
modalError = '';
|
||||
}}
|
||||
on:click={openDeleteAccount}
|
||||
class="flex items-center gap-2 rounded bg-red-900 px-4 py-2 text-sm font-medium transition-colors hover:bg-red-800"
|
||||
>
|
||||
<Trash2 class="h-4 w-4" />
|
||||
@@ -342,6 +431,156 @@
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
{#if reportsSubmitted || reportsTarget}
|
||||
<div class="mt-6 space-y-6">
|
||||
{#if reportsSubmitted}
|
||||
<div class="rounded border border-neutral-800 bg-neutral-900/60 p-4">
|
||||
<h2 class="mb-3 text-xl font-semibold text-neutral-200">Submitted Reports</h2>
|
||||
{#if reportsSubmitted.reports.length > 0}
|
||||
<div class="space-y-3">
|
||||
{#each reportsSubmitted.reports as report (report.reportID)}
|
||||
<div
|
||||
class="flex cursor-pointer flex-col gap-2 rounded border border-neutral-700 bg-neutral-800 px-5 py-4 transition-colors duration-200 hover:bg-neutral-700 focus:ring-2 focus:ring-neutral-600 focus:outline-none"
|
||||
role="link"
|
||||
tabindex="0"
|
||||
on:click={() => goto(resolve(`/report/${report.reportID}`))}
|
||||
on:keydown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
goto(resolve(`/report/${report.reportID}`));
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||
<span class="text-lg font-semibold text-neutral-100">
|
||||
Report #{report.reportID}
|
||||
</span>
|
||||
<span class="text-sm text-neutral-300">
|
||||
{reportTypeLabels[report.type] ?? 'Other'}
|
||||
· {reportStatusLabels[report.status] ?? 'Open'}
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-3 text-sm text-neutral-400">
|
||||
<span>{reportTargetLabels[report.targetType] ?? 'Unknown'}</span>
|
||||
{#if report.pasteId}
|
||||
<a
|
||||
href={resolve(`/${report.pasteId}`)}
|
||||
class="text-neutral-300 hover:text-white"
|
||||
on:click|stopPropagation
|
||||
>
|
||||
{report.pasteTitle !== '' ? report.pasteTitle : report.pasteId}
|
||||
</a>
|
||||
{/if}
|
||||
{#if report.userUUID}
|
||||
{#if report.targetUsername}
|
||||
<a
|
||||
href={resolve(`/user/${report.targetUsername}`)}
|
||||
class="text-neutral-300 hover:text-white"
|
||||
use:tooltip={report.userUUID}
|
||||
on:click|stopPropagation
|
||||
>
|
||||
{report.targetDisplayName || report.targetUsername}
|
||||
</a>
|
||||
{:else}
|
||||
<span>{report.userUUID}</span>
|
||||
{/if}
|
||||
{/if}
|
||||
<span>
|
||||
Created {new Date(report.createdAt * 1000).toLocaleString()}
|
||||
</span>
|
||||
</div>
|
||||
{#if report.description}
|
||||
<p class="text-sm text-neutral-300">{report.description}</p>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{:else}
|
||||
<p class="text-center text-neutral-400">No submitted reports to show.</p>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
{#if reportsTarget}
|
||||
<div class="rounded border border-neutral-800 bg-neutral-900/60 p-4">
|
||||
<h2 class="mb-3 text-xl font-semibold text-neutral-200">Reports About This User</h2>
|
||||
{#if reportsTarget.reports.length > 0}
|
||||
<div class="space-y-3">
|
||||
{#each reportsTarget.reports as report (report.reportID)}
|
||||
<div
|
||||
class="flex flex-col gap-2 rounded border border-neutral-700 bg-neutral-800 px-5 py-4 transition-colors duration-200 hover:bg-neutral-700 focus:ring-2 focus:ring-neutral-600 focus:outline-none"
|
||||
role="link"
|
||||
tabindex="0"
|
||||
on:click={() => goto(resolve(`/report/${report.reportID}`))}
|
||||
on:keydown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
goto(resolve(`/report/${report.reportID}`));
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||
<span class="text-lg font-semibold text-neutral-100">
|
||||
Report #{report.reportID}
|
||||
</span>
|
||||
<span class="text-sm text-neutral-300">
|
||||
{reportTypeLabels[report.type] ?? 'Other'}
|
||||
· {reportStatusLabels[report.status] ?? 'Open'}
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-3 text-sm text-neutral-400">
|
||||
<span>{reportTargetLabels[report.targetType] ?? 'Unknown'}</span>
|
||||
{#if report.reporterUsername}
|
||||
<a
|
||||
href={resolve(`/user/${report.reporterUsername}`)}
|
||||
class="text-neutral-300 hover:text-white"
|
||||
use:tooltip={report.reporterUUID}
|
||||
on:click|stopPropagation
|
||||
>
|
||||
{report.reporterDisplayName || report.reporterUsername}
|
||||
</a>
|
||||
{:else}
|
||||
<span>{report.reporterUUID}</span>
|
||||
{/if}
|
||||
{#if report.pastePID}
|
||||
<a
|
||||
href={resolve(`/${report.pasteId ?? report.pastePID}`)}
|
||||
class="text-neutral-300 hover:text-white"
|
||||
on:click|stopPropagation
|
||||
>
|
||||
{report.pasteTitle ? report.pasteTitle : `Paste #${report.pastePID}`}
|
||||
</a>
|
||||
{/if}
|
||||
{#if report.userUUID}
|
||||
{#if report.targetUsername}
|
||||
<a
|
||||
href={resolve(`/user/${report.targetUsername}`)}
|
||||
class="text-neutral-300 hover:text-white"
|
||||
use:tooltip={report.userUUID}
|
||||
on:click|stopPropagation
|
||||
>
|
||||
{report.targetDisplayName || report.targetUsername}
|
||||
</a>
|
||||
{:else}
|
||||
<span>{report.userUUID}</span>
|
||||
{/if}
|
||||
{/if}
|
||||
<span>
|
||||
Created {new Date(report.createdAt * 1000).toLocaleString()}
|
||||
</span>
|
||||
</div>
|
||||
{#if report.description}
|
||||
<p class="text-sm text-neutral-300">{report.description}</p>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{:else}
|
||||
<p class="text-center text-neutral-400">No reports to show.</p>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
{#if pagination.totalPages && pagination.totalPages > 1}
|
||||
<div class="mt-4 flex items-center justify-center gap-4">
|
||||
<button
|
||||
@@ -366,92 +605,6 @@
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<Modal
|
||||
show={showEditModal}
|
||||
mode="prompt"
|
||||
title="Edit Display Name "
|
||||
placeholder="New Display Name"
|
||||
bind:error={modalError}
|
||||
onConfirm={(value) => handleUserUpdate(value as string)}
|
||||
onCancel={() => {
|
||||
showEditModal = false;
|
||||
modalError = '';
|
||||
}}
|
||||
/>
|
||||
|
||||
<Modal
|
||||
show={showDeleteModal}
|
||||
mode="confirm"
|
||||
title="Delete Account"
|
||||
message={`This action cannot be undone. ${isOwner ? 'All your' : "This user's"} pastes and account data will be permanently deleted.`}
|
||||
confirmButtonText="Delete Account"
|
||||
error={modalError}
|
||||
onConfirm={() => handleDeleteAccount()}
|
||||
onCancel={() => {
|
||||
showDeleteModal = false;
|
||||
modalError = '';
|
||||
}}
|
||||
/>
|
||||
|
||||
<Modal
|
||||
show={showDeleteTotpModal}
|
||||
mode="totp"
|
||||
title="Enter TOTP to delete"
|
||||
placeholder="Enter 6-digit code"
|
||||
inputType="text"
|
||||
error={modalError}
|
||||
confirmButtonText="Delete Account"
|
||||
onConfirm={(value) => handleDeleteTotpConfirm(value)}
|
||||
onCancel={() => {
|
||||
showDeleteTotpModal = false;
|
||||
deleteTotpCode = '';
|
||||
modalError = '';
|
||||
}}
|
||||
/>
|
||||
|
||||
<Modal
|
||||
show={showRoleModal}
|
||||
mode="multiselect"
|
||||
title="Edit User Roles"
|
||||
items={roleOptions}
|
||||
initialValue={data.user?.roles}
|
||||
error={modalError}
|
||||
onConfirm={(value) => handleUserUpdate(undefined, value as number[])}
|
||||
onCancel={() => {
|
||||
showRoleModal = false;
|
||||
modalError = '';
|
||||
}}
|
||||
/>
|
||||
|
||||
<Modal
|
||||
show={showTotpModal}
|
||||
mode="totpSetup"
|
||||
title="Two-Factor Authentication"
|
||||
error={modalError}
|
||||
totpActive={totpEnabled}
|
||||
onConfirm={(value) => handleTotpConfirm(value)}
|
||||
onCancel={() => {
|
||||
showTotpModal = false;
|
||||
modalError = '';
|
||||
}}
|
||||
/>
|
||||
<Modal
|
||||
show={showRoleTotpModal}
|
||||
mode="totp"
|
||||
title="Admin role requires TOTP"
|
||||
placeholder="Enter 6-digit code"
|
||||
inputType="text"
|
||||
error={modalError}
|
||||
confirmButtonText="Continue"
|
||||
onConfirm={(value) => handleRoleTotpConfirm(value)}
|
||||
onCancel={() => {
|
||||
showRoleTotpModal = false;
|
||||
roleTotpCode = '';
|
||||
pendingRoles = null;
|
||||
modalError = '';
|
||||
}}
|
||||
/>
|
||||
|
||||
<style>
|
||||
button {
|
||||
cursor: pointer;
|
||||
|
||||
Reference in New Issue
Block a user