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:
@@ -2,6 +2,8 @@
|
|||||||
import QRCode from 'qrcode';
|
import QRCode from 'qrcode';
|
||||||
import { getRefreshToken, getToken, setTokens } from '$lib/utils/auth';
|
import { getRefreshToken, getToken, setTokens } from '$lib/utils/auth';
|
||||||
import { parseTotpEnabled } from '$lib/utils/totp';
|
import { parseTotpEnabled } from '$lib/utils/totp';
|
||||||
|
import { tick } from 'svelte';
|
||||||
|
import { extractError } from '$lib/utils/misc';
|
||||||
|
|
||||||
export let show = false;
|
export let show = false;
|
||||||
export let mode:
|
export let mode:
|
||||||
@@ -11,7 +13,8 @@
|
|||||||
| 'prompt'
|
| 'prompt'
|
||||||
| 'multiselect'
|
| 'multiselect'
|
||||||
| 'totp'
|
| 'totp'
|
||||||
| 'totpSetup' = 'decrypt';
|
| 'totpSetup'
|
||||||
|
| 'report' = 'decrypt';
|
||||||
export let title = '';
|
export let title = '';
|
||||||
export let message = '';
|
export let message = '';
|
||||||
export let error = '';
|
export let error = '';
|
||||||
@@ -20,6 +23,9 @@
|
|||||||
export let items: { label: string; value: unknown }[] = [];
|
export let items: { label: string; value: unknown }[] = [];
|
||||||
export let initialValue: unknown = null;
|
export let initialValue: unknown = null;
|
||||||
export let totpActive: boolean | null = null;
|
export let totpActive: boolean | null = null;
|
||||||
|
export let reportTarget: 'user' | 'paste' | null = null;
|
||||||
|
export let reportTargetId: string | number | null = null;
|
||||||
|
export let reportSiteKey: string | null = null;
|
||||||
export let onConfirm: (value: unknown) => void;
|
export let onConfirm: (value: unknown) => void;
|
||||||
export let onCancel: () => void;
|
export let onCancel: () => void;
|
||||||
export let confirmButtonText = '';
|
export let confirmButtonText = '';
|
||||||
@@ -32,6 +38,34 @@
|
|||||||
let totpLoading = false;
|
let totpLoading = false;
|
||||||
let totpError = '';
|
let totpError = '';
|
||||||
let displayError = '';
|
let displayError = '';
|
||||||
|
let reportTypes: string[] = [];
|
||||||
|
let reportType = '';
|
||||||
|
let reportInitialized = false;
|
||||||
|
let reportLoading = false;
|
||||||
|
let turnstileEl: HTMLDivElement | null = null;
|
||||||
|
let turnstileWidgetId: string | null = null;
|
||||||
|
|
||||||
|
const titleMap = {
|
||||||
|
decrypt: 'Enter password to decrypt',
|
||||||
|
encrypt: 'Enter password to encrypt',
|
||||||
|
confirm: 'Confirm action',
|
||||||
|
multiselect: 'Select items',
|
||||||
|
totpSetup: 'Set up two-factor authentication',
|
||||||
|
totp: 'Enter TOTP code',
|
||||||
|
report: 'Create Report',
|
||||||
|
prompt: 'Input Required'
|
||||||
|
};
|
||||||
|
|
||||||
|
const confirmLabelMap = {
|
||||||
|
decrypt: 'Decrypt',
|
||||||
|
encrypt: 'Encrypt',
|
||||||
|
confirm: 'Confirm',
|
||||||
|
multiselect: 'Confirm',
|
||||||
|
totpSetup: totpEnabled ? 'Disable' : 'Enable',
|
||||||
|
totp: 'Verify',
|
||||||
|
report: 'Submit Report',
|
||||||
|
prompt: 'Submit'
|
||||||
|
};
|
||||||
|
|
||||||
$: displayError = error || totpError;
|
$: displayError = error || totpError;
|
||||||
|
|
||||||
@@ -45,6 +79,11 @@
|
|||||||
initializeTotp();
|
initializeTotp();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$: if (show && mode === 'report' && !reportInitialized) {
|
||||||
|
reportInitialized = true;
|
||||||
|
initializeReport();
|
||||||
|
}
|
||||||
|
|
||||||
function resetModal() {
|
function resetModal() {
|
||||||
inputValue =
|
inputValue =
|
||||||
initialValue !== null
|
initialValue !== null
|
||||||
@@ -58,6 +97,15 @@
|
|||||||
totpInitialized = false;
|
totpInitialized = false;
|
||||||
totpLoading = false;
|
totpLoading = false;
|
||||||
totpError = '';
|
totpError = '';
|
||||||
|
reportTypes = [];
|
||||||
|
reportType = '';
|
||||||
|
reportInitialized = false;
|
||||||
|
reportLoading = false;
|
||||||
|
if (turnstileWidgetId && typeof window !== 'undefined' && window.turnstile?.remove) {
|
||||||
|
window.turnstile.remove(turnstileWidgetId);
|
||||||
|
}
|
||||||
|
turnstileEl = null;
|
||||||
|
turnstileWidgetId = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function getCodeOrError(message: string) {
|
function getCodeOrError(message: string) {
|
||||||
@@ -99,7 +147,7 @@
|
|||||||
});
|
});
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const data = await res.json().catch(() => null);
|
const data = await res.json().catch(() => null);
|
||||||
totpError = data?.message || 'Failed to start TOTP enrollment.';
|
totpError = extractError(data) || 'Failed to start TOTP enrollment.';
|
||||||
totpLoading = false;
|
totpLoading = false;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -111,6 +159,31 @@
|
|||||||
totpLoading = false;
|
totpLoading = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function initializeReport() {
|
||||||
|
reportLoading = true;
|
||||||
|
error = '';
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/report/options');
|
||||||
|
if (!res.ok) {
|
||||||
|
reportLoading = false;
|
||||||
|
error = 'Failed to load report options.';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const data = (await res.json().catch(() => null)) || {};
|
||||||
|
const types = data.types || data.Types || [];
|
||||||
|
reportTypes = Array.isArray(types) ? types : [];
|
||||||
|
reportType = reportTypes.includes(reportType) ? reportType : reportTypes[0] || '';
|
||||||
|
reportLoading = false;
|
||||||
|
if (reportSiteKey) {
|
||||||
|
await tick();
|
||||||
|
renderTurnstile();
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
reportLoading = false;
|
||||||
|
error = 'Failed to load report options.';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function refreshTokens() {
|
async function refreshTokens() {
|
||||||
const token = getToken();
|
const token = getToken();
|
||||||
const refreshToken = getRefreshToken();
|
const refreshToken = getRefreshToken();
|
||||||
@@ -132,6 +205,10 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function handleSubmit() {
|
async function handleSubmit() {
|
||||||
|
if (mode === 'report') {
|
||||||
|
await submitReport();
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (mode === 'totp') {
|
if (mode === 'totp') {
|
||||||
if (!inputValue || typeof inputValue !== 'string') return;
|
if (!inputValue || typeof inputValue !== 'string') return;
|
||||||
onConfirm(inputValue.trim());
|
onConfirm(inputValue.trim());
|
||||||
@@ -144,6 +221,106 @@
|
|||||||
onConfirm(mode === 'confirm' ? true : inputValue);
|
onConfirm(mode === 'confirm' ? true : inputValue);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function renderTurnstile() {
|
||||||
|
if (!reportSiteKey || typeof window === 'undefined') return;
|
||||||
|
const mount = () => {
|
||||||
|
if (!turnstileEl || !window.turnstile) return;
|
||||||
|
if (turnstileWidgetId && window.turnstile.remove) {
|
||||||
|
window.turnstile.remove(turnstileWidgetId);
|
||||||
|
}
|
||||||
|
turnstileWidgetId = window.turnstile.render(turnstileEl, {
|
||||||
|
sitekey: reportSiteKey,
|
||||||
|
theme: 'dark'
|
||||||
|
});
|
||||||
|
};
|
||||||
|
if (window.turnstile) {
|
||||||
|
mount();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const existing = document.querySelector('script[data-turnstile="true"]');
|
||||||
|
if (!existing) {
|
||||||
|
const script = document.createElement('script');
|
||||||
|
script.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit';
|
||||||
|
script.async = true;
|
||||||
|
script.defer = true;
|
||||||
|
script.dataset.turnstile = 'true';
|
||||||
|
script.onload = () => window.dispatchEvent(new Event('turnstile:loaded'));
|
||||||
|
document.body.appendChild(script);
|
||||||
|
}
|
||||||
|
const handler = () => {
|
||||||
|
mount();
|
||||||
|
window.removeEventListener('turnstile:loaded', handler);
|
||||||
|
};
|
||||||
|
window.addEventListener('turnstile:loaded', handler, { once: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submitReport() {
|
||||||
|
error = '';
|
||||||
|
if (!reportTarget || reportTargetId === null) {
|
||||||
|
error = 'Missing report target.';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (typeof inputValue !== 'string') inputValue = '';
|
||||||
|
const description = inputValue.trim();
|
||||||
|
if (!description) {
|
||||||
|
error = 'Description is required.';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (description.length < 12) {
|
||||||
|
error = 'Description must be at least 12 characters.';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (description.length > 1000) {
|
||||||
|
error = 'Description must be 1000 characters or less.';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const type = reportType || reportTypes[0] || '';
|
||||||
|
if (!type) {
|
||||||
|
error = 'Select a report type.';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const token = getToken();
|
||||||
|
if (!token) {
|
||||||
|
error = 'You need to be logged in to report.';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const body: Record<string, unknown> = { description, reportType: type };
|
||||||
|
if (reportSiteKey) {
|
||||||
|
if (typeof window === 'undefined' || !window.turnstile) {
|
||||||
|
error = 'Verification unavailable.';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const verification = window.turnstile.getResponse();
|
||||||
|
if (!verification) {
|
||||||
|
error = 'Complete verification.';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
body.VerificationToken = verification;
|
||||||
|
}
|
||||||
|
const targetId = encodeURIComponent(String(reportTargetId));
|
||||||
|
const res = await fetch(`/api/${reportTarget}/${targetId}/report`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
Authorization: `Bearer ${token}`
|
||||||
|
},
|
||||||
|
body: JSON.stringify(body)
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
const data = await res.json().catch(() => null);
|
||||||
|
error = extractError(data) || 'Failed to submit report.';
|
||||||
|
if (reportSiteKey && typeof window !== 'undefined' && window.turnstile) {
|
||||||
|
window.turnstile.reset();
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const data = await res.json().catch(() => null);
|
||||||
|
if (reportSiteKey && typeof window !== 'undefined' && window.turnstile) {
|
||||||
|
window.turnstile.reset();
|
||||||
|
}
|
||||||
|
onConfirm(data || { description, reportType: type });
|
||||||
|
}
|
||||||
|
|
||||||
async function submitTotp() {
|
async function submitTotp() {
|
||||||
if (totpEnabled) {
|
if (totpEnabled) {
|
||||||
await disableTotp();
|
await disableTotp();
|
||||||
@@ -207,36 +384,11 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$: displayTitle =
|
$: displayTitle = title || titleMap[mode];
|
||||||
title ||
|
|
||||||
(mode === 'decrypt'
|
|
||||||
? 'Enter password to decrypt'
|
|
||||||
: mode === 'encrypt'
|
|
||||||
? 'Enter password to encrypt'
|
|
||||||
: mode === 'confirm'
|
|
||||||
? 'Confirm action'
|
|
||||||
: mode === 'multiselect'
|
|
||||||
? 'Select items'
|
|
||||||
: mode === 'totpSetup'
|
|
||||||
? 'Set up two-factor authentication'
|
|
||||||
: mode === 'totp'
|
|
||||||
? 'Enter TOTP code'
|
|
||||||
: 'Enter value');
|
|
||||||
|
|
||||||
$: confirmLabel =
|
$: confirmLabel = confirmButtonText || confirmLabelMap[mode];
|
||||||
confirmButtonText ||
|
$: shouldShowInput =
|
||||||
(mode === 'decrypt'
|
mode !== 'confirm' && mode !== 'multiselect' && mode !== 'totpSetup' && mode !== 'report';
|
||||||
? 'Decrypt'
|
|
||||||
: mode === 'encrypt'
|
|
||||||
? 'Encrypt'
|
|
||||||
: mode === 'confirm'
|
|
||||||
? 'Delete'
|
|
||||||
: mode === 'totpSetup'
|
|
||||||
? totpEnabled
|
|
||||||
? 'Disable'
|
|
||||||
: 'Enable'
|
|
||||||
: 'Confirm');
|
|
||||||
$: shouldShowInput = mode !== 'confirm' && mode !== 'multiselect' && mode !== 'totpSetup';
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
{#if show}
|
{#if show}
|
||||||
@@ -306,6 +458,34 @@
|
|||||||
/>
|
/>
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
|
{:else if mode === 'report'}
|
||||||
|
<div class="mb-4 space-y-3">
|
||||||
|
{#if reportLoading}
|
||||||
|
<p class="text-neutral-300">Loading report options...</p>
|
||||||
|
{:else}
|
||||||
|
{#if reportTypes.length}
|
||||||
|
<select
|
||||||
|
bind:value={reportType}
|
||||||
|
class="w-full rounded border border-neutral-700 bg-neutral-800 p-2 text-white outline-none"
|
||||||
|
>
|
||||||
|
{#each reportTypes as type, i (i)}
|
||||||
|
<option value={type}>{type.replace(/([A-Z])/g, ' $1').trim()}</option>
|
||||||
|
{/each}
|
||||||
|
</select>
|
||||||
|
{/if}
|
||||||
|
<textarea
|
||||||
|
bind:value={inputValue}
|
||||||
|
maxlength="1000"
|
||||||
|
placeholder={placeholder || 'Describe the issue'}
|
||||||
|
class="h-28 w-full resize-none rounded border border-neutral-700 bg-neutral-800 p-2 text-white outline-none"
|
||||||
|
></textarea>
|
||||||
|
{#if reportSiteKey}
|
||||||
|
<div class="flex justify-center">
|
||||||
|
<div class="cf-turnstile" bind:this={turnstileEl}></div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
{:else if shouldShowInput}
|
{:else if shouldShowInput}
|
||||||
<input
|
<input
|
||||||
type={inputType}
|
type={inputType}
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import Modal from '$lib/components/Modal.svelte';
|
||||||
|
import { cancelModal, confirmModal, modal } from '$lib/stores/modal';
|
||||||
|
|
||||||
|
$: state = $modal;
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<Modal
|
||||||
|
show={state.show}
|
||||||
|
mode={state.mode}
|
||||||
|
title={state.title}
|
||||||
|
message={state.message}
|
||||||
|
error={state.error}
|
||||||
|
placeholder={state.placeholder}
|
||||||
|
inputType={state.inputType}
|
||||||
|
items={state.items}
|
||||||
|
initialValue={state.initialValue}
|
||||||
|
totpActive={state.totpActive}
|
||||||
|
reportTarget={state.reportTarget}
|
||||||
|
reportTargetId={state.reportTargetId}
|
||||||
|
reportSiteKey={state.reportSiteKey}
|
||||||
|
confirmButtonText={state.confirmButtonText}
|
||||||
|
onConfirm={(value) => confirmModal(value)}
|
||||||
|
onCancel={() => cancelModal()}
|
||||||
|
/>
|
||||||
@@ -25,6 +25,12 @@
|
|||||||
<a href={resolve('/')} class="text-xl font-bold text-white hover:text-neutral-300">Sharpbin</a>
|
<a href={resolve('/')} class="text-xl font-bold text-white hover:text-neutral-300">Sharpbin</a>
|
||||||
{#if $user}
|
{#if $user}
|
||||||
<div class="ml-auto flex items-center space-x-4">
|
<div class="ml-auto flex items-center space-x-4">
|
||||||
|
{#if $user.roles.includes(1) || $user.roles.includes(255)}
|
||||||
|
<a
|
||||||
|
href={resolve('/reports')}
|
||||||
|
class="rounded bg-neutral-700 px-3 py-1 text-white hover:bg-neutral-800">Reports</a
|
||||||
|
>
|
||||||
|
{/if}
|
||||||
<a
|
<a
|
||||||
href={resolve(`/user/${$user.username}`)}
|
href={resolve(`/user/${$user.username}`)}
|
||||||
class="rounded bg-neutral-700 px-3 py-1 text-white hover:bg-neutral-800">Profile</a
|
class="rounded bg-neutral-700 px-3 py-1 text-white hover:bg-neutral-800">Profile</a
|
||||||
|
|||||||
@@ -0,0 +1,83 @@
|
|||||||
|
import { writable } from 'svelte/store';
|
||||||
|
|
||||||
|
type ModalMode =
|
||||||
|
| 'decrypt'
|
||||||
|
| 'encrypt'
|
||||||
|
| 'confirm'
|
||||||
|
| 'prompt'
|
||||||
|
| 'multiselect'
|
||||||
|
| 'totp'
|
||||||
|
| 'totpSetup'
|
||||||
|
| 'report';
|
||||||
|
|
||||||
|
type ModalItem = { label: string; value: unknown };
|
||||||
|
|
||||||
|
type ModalState = {
|
||||||
|
show: boolean;
|
||||||
|
mode: ModalMode;
|
||||||
|
title: string;
|
||||||
|
message: string;
|
||||||
|
error: string;
|
||||||
|
placeholder: string;
|
||||||
|
inputType: string;
|
||||||
|
items: ModalItem[];
|
||||||
|
initialValue: unknown;
|
||||||
|
totpActive: boolean | null;
|
||||||
|
reportTarget: 'user' | 'paste' | null;
|
||||||
|
reportTargetId: string | number | null;
|
||||||
|
reportSiteKey: string | null;
|
||||||
|
confirmButtonText: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type ModalOpenOptions = Partial<Omit<ModalState, 'show'>> & {
|
||||||
|
mode: ModalMode;
|
||||||
|
cancelValue?: unknown;
|
||||||
|
};
|
||||||
|
|
||||||
|
const initialState: ModalState = {
|
||||||
|
show: false,
|
||||||
|
mode: 'confirm',
|
||||||
|
title: '',
|
||||||
|
message: '',
|
||||||
|
error: '',
|
||||||
|
placeholder: '',
|
||||||
|
inputType: 'text',
|
||||||
|
items: [],
|
||||||
|
initialValue: null,
|
||||||
|
totpActive: null,
|
||||||
|
reportTarget: null,
|
||||||
|
reportTargetId: null,
|
||||||
|
reportSiteKey: null,
|
||||||
|
confirmButtonText: ''
|
||||||
|
};
|
||||||
|
|
||||||
|
let resolver: ((value: unknown) => void) | null = null;
|
||||||
|
let cancelValue: unknown = '';
|
||||||
|
|
||||||
|
export const modal = writable<ModalState>(initialState);
|
||||||
|
|
||||||
|
export function openModal<T = unknown>(options: ModalOpenOptions): Promise<T> {
|
||||||
|
cancelValue = options.cancelValue ?? '';
|
||||||
|
return new Promise<T>((resolve) => {
|
||||||
|
resolver = resolve as (value: unknown) => void;
|
||||||
|
modal.set({
|
||||||
|
...initialState,
|
||||||
|
...options,
|
||||||
|
show: true
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function confirmModal(value: unknown) {
|
||||||
|
const resolve = resolver;
|
||||||
|
resolver = null;
|
||||||
|
modal.set(initialState);
|
||||||
|
resolve?.(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function cancelModal() {
|
||||||
|
const resolve = resolver;
|
||||||
|
resolver = null;
|
||||||
|
modal.set(initialState);
|
||||||
|
resolve?.(cancelValue);
|
||||||
|
}
|
||||||
@@ -1,4 +1,31 @@
|
|||||||
import { writable } from 'svelte/store';
|
import { writable } from 'svelte/store';
|
||||||
|
import { browser } from '$app/environment';
|
||||||
import type { AuthUser } from '$lib/types/user';
|
import type { AuthUser } from '$lib/types/user';
|
||||||
|
|
||||||
export const user = writable<AuthUser | null>(null);
|
let initial: AuthUser | null = null;
|
||||||
|
|
||||||
|
if (browser) {
|
||||||
|
try {
|
||||||
|
const stored = localStorage.getItem('user');
|
||||||
|
if (stored) {
|
||||||
|
const parsed = JSON.parse(stored);
|
||||||
|
if (parsed && 'user' in parsed && typeof parsed.user === 'object') {
|
||||||
|
const { user: nestedUser, ...rest } = parsed;
|
||||||
|
initial = { ...rest, ...nestedUser };
|
||||||
|
} else {
|
||||||
|
initial = parsed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* empty */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const user = writable<AuthUser | null>(initial);
|
||||||
|
|
||||||
|
if (browser) {
|
||||||
|
user.subscribe((val) => {
|
||||||
|
if (val) localStorage.setItem('user', JSON.stringify(val));
|
||||||
|
else localStorage.removeItem('user');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|||||||
@@ -12,5 +12,6 @@ export interface Paste {
|
|||||||
visibility: 0 | 1 | 2;
|
visibility: 0 | 1 | 2;
|
||||||
expiresAt: number;
|
expiresAt: number;
|
||||||
editedAt: number | null;
|
editedAt: number | null;
|
||||||
|
reportCount: number | null;
|
||||||
author: Author | null;
|
author: Author | null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import type { Pagination } from './pagination';
|
||||||
|
|
||||||
|
export interface Report {
|
||||||
|
reportID: number;
|
||||||
|
type: number;
|
||||||
|
status: number;
|
||||||
|
description: string | null;
|
||||||
|
createdAt: number;
|
||||||
|
updatedAt: number | null;
|
||||||
|
reporterUUID: string;
|
||||||
|
reporterUsername?: string | null;
|
||||||
|
reporterDisplayName?: string | null;
|
||||||
|
targetType: number;
|
||||||
|
pastePID: number | null;
|
||||||
|
pasteId?: string | null;
|
||||||
|
pasteTitle?: string | null;
|
||||||
|
userUUID: string | null;
|
||||||
|
targetUsername?: string | null;
|
||||||
|
targetDisplayName?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ReportListResponse {
|
||||||
|
reports: Report[];
|
||||||
|
pagination: Pagination;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const reportTypeLabels = [
|
||||||
|
'Spam',
|
||||||
|
'Abuse',
|
||||||
|
'InappropriateContent',
|
||||||
|
'CopyrightViolation',
|
||||||
|
'Fraud',
|
||||||
|
'Other'
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
export const reportStatusLabels = ['Open', 'InProgress', 'Resolved', 'Closed'] as const;
|
||||||
|
|
||||||
|
export const reportTargetLabels = ['Paste', 'User'] as const;
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { browser } from '$app/environment';
|
import { browser } from '$app/environment';
|
||||||
import type { Cookies } from '@sveltejs/kit';
|
import type { Cookies } from '@sveltejs/kit';
|
||||||
|
import { user } from '$lib/stores/user';
|
||||||
|
|
||||||
const TOKEN_KEY = 'token';
|
const TOKEN_KEY = 'token';
|
||||||
const REFRESH_TOKEN_KEY = 'refreshToken';
|
const REFRESH_TOKEN_KEY = 'refreshToken';
|
||||||
@@ -36,6 +37,7 @@ export function clearTokens() {
|
|||||||
console.log('Clearing tokens');
|
console.log('Clearing tokens');
|
||||||
document.cookie = `${TOKEN_KEY}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
|
document.cookie = `${TOKEN_KEY}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
|
||||||
document.cookie = `${REFRESH_TOKEN_KEY}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
|
document.cookie = `${REFRESH_TOKEN_KEY}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
|
||||||
|
user.set(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function refreshTokenIfNeeded() {
|
export async function refreshTokenIfNeeded() {
|
||||||
|
|||||||
@@ -24,6 +24,25 @@ export function extractDateFromUUIDv7(uuid?: string): Date | null {
|
|||||||
return new Date(parseInt(timestampHex, 16));
|
return new Date(parseInt(timestampHex, 16));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function extractError(resData: unknown): string | null {
|
||||||
|
if (!resData || typeof resData !== 'object') return null;
|
||||||
|
|
||||||
|
const data = resData as { errors?: unknown; message?: unknown };
|
||||||
|
|
||||||
|
if (data.errors && typeof data.errors === 'object') {
|
||||||
|
return Object.values(data.errors as Record<string, unknown>)
|
||||||
|
.flat()
|
||||||
|
.filter((v) => typeof v === 'string')
|
||||||
|
.join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof data.message === 'string') {
|
||||||
|
return data.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
export function dateToRelativeString(
|
export function dateToRelativeString(
|
||||||
date: Date,
|
date: Date,
|
||||||
useSuffix = true,
|
useSuffix = true,
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ export function parseTotpEnabled(tokenValue: string | null) {
|
|||||||
if (!tokenValue) return false;
|
if (!tokenValue) return false;
|
||||||
try {
|
try {
|
||||||
const payload = JSON.parse(atob(tokenValue.split('.')[1]));
|
const payload = JSON.parse(atob(tokenValue.split('.')[1]));
|
||||||
const flag = payload?.TOTP_Enabled ?? payload?.totp_enabled ?? payload?.totpEnabled;
|
const flag = payload?.totp;
|
||||||
if (typeof flag === 'string') return flag.toLowerCase() === 'true';
|
if (typeof flag === 'string') return flag.toLowerCase() === 'true';
|
||||||
return Boolean(flag);
|
return Boolean(flag);
|
||||||
} catch {
|
} catch {
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
import './layout.css';
|
import './layout.css';
|
||||||
import favicon from '$lib/assets/favicon.svg';
|
import favicon from '$lib/assets/favicon.svg';
|
||||||
import Navbar from '$lib/components/Navbar.svelte';
|
import Navbar from '$lib/components/Navbar.svelte';
|
||||||
|
import ModalHost from '$lib/components/ModalHost.svelte';
|
||||||
import { user } from '$lib/stores/user';
|
import { user } from '$lib/stores/user';
|
||||||
import { startTokenRefreshInterval, getToken, refreshTokenIfNeeded } from '$lib/utils/auth';
|
import { startTokenRefreshInterval, getToken, refreshTokenIfNeeded } from '$lib/utils/auth';
|
||||||
import { parseTotpEnabled } from '$lib/utils/totp';
|
import { parseTotpEnabled } from '$lib/utils/totp';
|
||||||
@@ -21,7 +22,10 @@
|
|||||||
onMount(async () => {
|
onMount(async () => {
|
||||||
await refreshTokenIfNeeded();
|
await refreshTokenIfNeeded();
|
||||||
const token = getToken();
|
const token = getToken();
|
||||||
if (!token) return;
|
if (!token) {
|
||||||
|
user.set(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const res = await fetch('/api/user/me', {
|
const res = await fetch('/api/user/me', {
|
||||||
headers: { Authorization: `Bearer ${token}` }
|
headers: { Authorization: `Bearer ${token}` }
|
||||||
@@ -29,7 +33,12 @@
|
|||||||
|
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
const me = await res.json();
|
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 {
|
} else {
|
||||||
user.set(null);
|
user.set(null);
|
||||||
}
|
}
|
||||||
@@ -50,3 +59,5 @@
|
|||||||
<Navbar {data} />
|
<Navbar {data} />
|
||||||
<div class="h-15 w-full"></div>
|
<div class="h-15 w-full"></div>
|
||||||
<slot />
|
<slot />
|
||||||
|
|
||||||
|
<ModalHost />
|
||||||
|
|||||||
@@ -4,11 +4,23 @@ import { getServerToken } from '$lib/utils/auth';
|
|||||||
import { env } from '$env/dynamic/private';
|
import { env } from '$env/dynamic/private';
|
||||||
|
|
||||||
const apiUrl = process.env.VITE_API_URL || 'http://localhost:5050';
|
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 { 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) {
|
if (pasteRes.status === 404) {
|
||||||
return {
|
return {
|
||||||
status: 404,
|
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`, {
|
const viewed = await fetch(`${apiUrl}/api/paste/${id}/view`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
@@ -51,5 +60,14 @@ export const load: PageServerLoad = async ({ params, fetch, url, cookies }) => {
|
|||||||
const options = await pasteOptions.json();
|
const options = await pasteOptions.json();
|
||||||
const content = await pasteContent.text();
|
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,
|
Download,
|
||||||
Copy,
|
Copy,
|
||||||
Check,
|
Check,
|
||||||
CalendarCog
|
CalendarCog,
|
||||||
|
Flag
|
||||||
} from '@lucide/svelte/icons/index';
|
} from '@lucide/svelte/icons/index';
|
||||||
import {
|
import {
|
||||||
formatBytes,
|
formatBytes,
|
||||||
@@ -34,13 +35,11 @@
|
|||||||
import { getToken } from '$lib/utils/auth';
|
import { getToken } from '$lib/utils/auth';
|
||||||
import { user } from '$lib/stores/user';
|
import { user } from '$lib/stores/user';
|
||||||
import Dropdown from '$lib/components/Dropdown.svelte';
|
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';
|
import type { Paste } from '$lib/types/paste';
|
||||||
export let data: PageData;
|
export let data: PageData;
|
||||||
|
|
||||||
let showModal = false;
|
let reportSiteKey: string | null = null;
|
||||||
let modalResolve: ((value: string) => void) | null = null;
|
|
||||||
let modalMode: 'decrypt' | 'encrypt' | 'confirm' = 'decrypt';
|
|
||||||
let editing = false;
|
let editing = false;
|
||||||
let editContent: string | null = null;
|
let editContent: string | null = null;
|
||||||
let editMetadata: Paste | null = data.paste ? { ...data.paste } : null;
|
let editMetadata: Paste | null = data.paste ? { ...data.paste } : null;
|
||||||
@@ -60,6 +59,7 @@
|
|||||||
: false;
|
: false;
|
||||||
|
|
||||||
let interval: ReturnType<typeof setInterval> | null = null;
|
let interval: ReturnType<typeof setInterval> | null = null;
|
||||||
|
|
||||||
const syntaxOptions =
|
const syntaxOptions =
|
||||||
data.options?.syntaxes?.map((lang: string) => ({
|
data.options?.syntaxes?.map((lang: string) => ({
|
||||||
value: lang,
|
value: lang,
|
||||||
@@ -86,6 +86,13 @@
|
|||||||
label: visibility.displayName
|
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(() => {
|
onMount(() => {
|
||||||
interval = setInterval(() => {
|
interval = setInterval(() => {
|
||||||
now = new Date();
|
now = new Date();
|
||||||
@@ -230,12 +237,26 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function promptUser(mode: 'decrypt' | 'encrypt' | 'confirm' = 'decrypt'): Promise<string> {
|
async function promptUser(mode: 'decrypt' | 'encrypt' | 'confirm' | 'report' = 'decrypt') {
|
||||||
return new Promise((resolve) => {
|
const title = modalTitleMap[mode];
|
||||||
showModal = true;
|
if (mode === 'confirm') {
|
||||||
modalResolve = resolve;
|
const ok = await openModal<boolean>({ mode, title, cancelValue: false });
|
||||||
modalMode = mode;
|
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 () => {
|
onMount(async () => {
|
||||||
@@ -280,6 +301,9 @@
|
|||||||
});
|
});
|
||||||
|
|
||||||
$: if (data?.paste && (data.paste.visibility !== 2 || decryptedContent !== null)) renderCode();
|
$: 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>
|
</script>
|
||||||
|
|
||||||
<svelte:head>
|
<svelte:head>
|
||||||
@@ -370,6 +394,17 @@
|
|||||||
>
|
>
|
||||||
</div>
|
</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">
|
<div class="flex shrink-0 items-center">
|
||||||
<CalendarDays class="mr-2 h-6 w-6 text-neutral-400" />
|
<CalendarDays class="mr-2 h-6 w-6 text-neutral-400" />
|
||||||
<span
|
<span
|
||||||
@@ -558,6 +593,18 @@
|
|||||||
|
|
||||||
<span class="text-neutral-300">Download</span>
|
<span class="text-neutral-300">Download</span>
|
||||||
</button>
|
</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 $user && ($user.uuid === data.paste?.author?.uuid || $user.roles.some((r) => r === 1 || r === 255))}
|
||||||
{#if !editing}
|
{#if !editing}
|
||||||
<button
|
<button
|
||||||
@@ -661,33 +708,6 @@
|
|||||||
{/if}
|
{/if}
|
||||||
</div>
|
</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>
|
<style>
|
||||||
.hljs {
|
.hljs {
|
||||||
background-color: var(--color-neutral-800) !important;
|
background-color: var(--color-neutral-800) !important;
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { resolve } from '$app/paths';
|
import { resolve } from '$app/paths';
|
||||||
import { setTokens, startTokenRefreshInterval } from '$lib/utils/auth';
|
import { setTokens, startTokenRefreshInterval } from '$lib/utils/auth';
|
||||||
|
import { extractError } from '$lib/utils/misc';
|
||||||
import { onMount } from 'svelte';
|
import { onMount } from 'svelte';
|
||||||
import type { PageData } from './$types';
|
import type { PageData } from './$types';
|
||||||
|
|
||||||
@@ -56,8 +57,8 @@
|
|||||||
});
|
});
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
if (data.result.token && data.result.refreshToken) {
|
if (data.token && data.refreshToken) {
|
||||||
setTokens(data.result.token, data.result.refreshToken);
|
setTokens(data.token, data.refreshToken);
|
||||||
startTokenRefreshInterval();
|
startTokenRefreshInterval();
|
||||||
}
|
}
|
||||||
const urlParams = new URLSearchParams(window.location.search);
|
const urlParams = new URLSearchParams(window.location.search);
|
||||||
@@ -72,19 +73,9 @@
|
|||||||
if (window.turnstile) {
|
if (window.turnstile) {
|
||||||
window.turnstile.reset();
|
window.turnstile.reset();
|
||||||
}
|
}
|
||||||
if (resData.errors) {
|
error = extractError(resData) || 'Login failed. Please try again.';
|
||||||
const messages = Object.values(resData.errors).flat();
|
if (error === 'TOTP code is required.') {
|
||||||
error = messages.join('\n');
|
totpEnabled = true;
|
||||||
} 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.';
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { goto } from '$app/navigation';
|
import { goto } from '$app/navigation';
|
||||||
import { setTokens, startTokenRefreshInterval } from '$lib/utils/auth';
|
import { setTokens, startTokenRefreshInterval } from '$lib/utils/auth';
|
||||||
|
import { extractError } from '$lib/utils/misc';
|
||||||
import { Check, X } from '@lucide/svelte';
|
import { Check, X } from '@lucide/svelte';
|
||||||
import { slide, fade } from 'svelte/transition';
|
import { slide, fade } from 'svelte/transition';
|
||||||
import { resolve } from '$app/paths';
|
import { resolve } from '$app/paths';
|
||||||
@@ -103,12 +104,12 @@
|
|||||||
const messages = Object.values(resData.errors).flat();
|
const messages = Object.values(resData.errors).flat();
|
||||||
error = messages.join('\n');
|
error = messages.join('\n');
|
||||||
} else {
|
} else {
|
||||||
if (resData.message === 'Verification failed.') {
|
error = extractError(resData) || 'Registration failed. Please try again.';
|
||||||
|
if (error === 'Verification failed.') {
|
||||||
if (window.turnstile) {
|
if (window.turnstile) {
|
||||||
window.turnstile.reset();
|
window.turnstile.reset();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
error = resData.message || 'Registration failed. Please try again.';
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
loading = false;
|
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 type { PageServerLoad } from './$types';
|
||||||
|
import { error } from '@sveltejs/kit';
|
||||||
|
import { env } from '$env/dynamic/private';
|
||||||
import { getServerToken } from '$lib/utils/auth';
|
import { getServerToken } from '$lib/utils/auth';
|
||||||
import type { User } from '$lib/types/user';
|
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 }) => {
|
function decodeJwtRoles(token?: string | null): number[] {
|
||||||
const { username } = params;
|
try {
|
||||||
const token = getServerToken(cookies);
|
if (!token) return [];
|
||||||
|
const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString());
|
||||||
const res = await fetch(`${apiUrl}/api/user/${username}`, {
|
const roles = payload?.role;
|
||||||
headers: {
|
if (Array.isArray(roles)) {
|
||||||
Authorization: token ? `Bearer ${token}` : ''
|
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) {
|
if (!res.ok) {
|
||||||
return {
|
const { message } = await res.json().catch(() => ({}));
|
||||||
status: 500,
|
throw error(res.status, message ?? 'Request failed');
|
||||||
error: { message: 'Internal server error' }
|
}
|
||||||
|
|
||||||
|
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 (token && canModerate && (!reportsSubmitted || !isOwner)) {
|
||||||
|
const submittedRes = await fetch(`${API_URL}/api/user/${user.uuid}/reports/submitted`, {
|
||||||
if (res.status !== 200) {
|
headers: { Authorization: `Bearer ${token}` }
|
||||||
return {
|
});
|
||||||
status: res.status,
|
if (submittedRes.ok) reportsSubmitted = await submittedRes.json();
|
||||||
error: { message: json.message || 'An error occurred' }
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
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">
|
<script lang="ts">
|
||||||
import { resolve } from '$app/paths';
|
import { resolve } from '$app/paths';
|
||||||
|
import { goto } from '$app/navigation';
|
||||||
import type { PageData } from './$types';
|
import type { PageData } from './$types';
|
||||||
import type { Pagination } from '$lib/types/pagination';
|
import type { Pagination } from '$lib/types/pagination';
|
||||||
import {
|
import {
|
||||||
@@ -12,44 +13,40 @@
|
|||||||
Pencil,
|
Pencil,
|
||||||
Trash2,
|
Trash2,
|
||||||
Clock,
|
Clock,
|
||||||
Hash
|
Hash,
|
||||||
|
Flag
|
||||||
} from '@lucide/svelte';
|
} from '@lucide/svelte';
|
||||||
import { extractDateFromUUIDv7, tooltip, dateToRelativeString } from '$lib/utils/misc';
|
import { extractDateFromUUIDv7, tooltip, dateToRelativeString } from '$lib/utils/misc';
|
||||||
import { roles } from '$lib/consts';
|
import { roles } from '$lib/consts';
|
||||||
import { getToken } from '$lib/utils/auth';
|
import { getToken } from '$lib/utils/auth';
|
||||||
import { needsAdminTotp } from '$lib/utils/totp';
|
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 { user } from '$lib/stores/user';
|
||||||
import { onMount } from 'svelte';
|
import { onMount } from 'svelte';
|
||||||
|
import { reportStatusLabels, reportTargetLabels, reportTypeLabels } from '$lib/types/report';
|
||||||
|
|
||||||
export let data: PageData;
|
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,
|
page: 1,
|
||||||
pageSize: 50,
|
pageSize: 50,
|
||||||
totalCount: 0,
|
totalCount: 0,
|
||||||
totalPages: 1
|
totalPages: 1
|
||||||
};
|
};
|
||||||
let pastes = data.user?.pastes ?? [];
|
let pastes = data.pastes?.pastes ?? [];
|
||||||
let loading = false;
|
let loading = false;
|
||||||
let isOwner = 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 modalError = '';
|
||||||
let totpEnabled = false;
|
let totpEnabled = false;
|
||||||
let pendingRoles: number[] | null = null;
|
|
||||||
let roleTotpCode = '';
|
|
||||||
let deleteTotpCode = '';
|
|
||||||
let now = new Date();
|
let now = new Date();
|
||||||
let interval: ReturnType<typeof setInterval> | null = null;
|
let interval: ReturnType<typeof setInterval> | null = null;
|
||||||
|
|
||||||
$: isOwner = data.user && $user ? data.user?.uuid === $user.uuid : false;
|
$: isOwner = data.user && $user ? data.user?.uuid === $user.uuid : false;
|
||||||
$: totpEnabled = Boolean($user?.totpEnabled);
|
$: totpEnabled = Boolean($user?.totpEnabled);
|
||||||
|
$: reportsSubmitted = data.reportsSubmitted;
|
||||||
|
$: reportsTarget = data.reportsTarget;
|
||||||
|
|
||||||
const roleOptions = [
|
const roleOptions = [
|
||||||
{ label: 'Member', value: 0 },
|
{ label: 'Member', value: 0 },
|
||||||
@@ -82,11 +79,22 @@
|
|||||||
const token = getToken();
|
const token = getToken();
|
||||||
const currentRoles = data.user?.roles ?? [];
|
const currentRoles = data.user?.roles ?? [];
|
||||||
const nextRoles = selectedRoles ?? currentRoles;
|
const nextRoles = selectedRoles ?? currentRoles;
|
||||||
if (needsAdminTotp(totpEnabled, currentRoles, nextRoles) && !roleTotpCode) {
|
let totpcode = '';
|
||||||
pendingRoles = nextRoles;
|
if (needsAdminTotp(totpEnabled, currentRoles, nextRoles)) {
|
||||||
showRoleTotpModal = true;
|
totpcode = String(
|
||||||
loading = false;
|
await openModal<string>({
|
||||||
return;
|
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}`, {
|
const res = await fetch(`/api/user/uuid/${data.user?.uuid}`, {
|
||||||
method: 'PATCH',
|
method: 'PATCH',
|
||||||
@@ -97,61 +105,70 @@
|
|||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
...(displayName !== undefined ? { displayName: displayName.trim() } : {}),
|
...(displayName !== undefined ? { displayName: displayName.trim() } : {}),
|
||||||
...(selectedRoles !== undefined ? { roles: selectedRoles } : {}),
|
...(selectedRoles !== undefined ? { roles: selectedRoles } : {}),
|
||||||
...(roleTotpCode ? { totpcode: roleTotpCode } : {})
|
...(totpcode ? { totpcode } : {})
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
loading = false;
|
loading = false;
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const err = await res.json();
|
const err = await res.json();
|
||||||
modalError = err.message || 'Failed to update display name';
|
modalError = err.message || 'Failed to update display name';
|
||||||
|
await openModal({
|
||||||
|
mode: 'confirm',
|
||||||
|
title: 'Error',
|
||||||
|
message: modalError,
|
||||||
|
confirmButtonText: 'OK',
|
||||||
|
cancelValue: true
|
||||||
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
showEditModal = false;
|
|
||||||
showRoleModal = false;
|
|
||||||
data.user!.displayName = displayName || data.user!.displayName;
|
data.user!.displayName = displayName || data.user!.displayName;
|
||||||
if (selectedRoles !== undefined) {
|
if (selectedRoles !== undefined) {
|
||||||
data.user!.roles = selectedRoles;
|
data.user!.roles = selectedRoles;
|
||||||
}
|
}
|
||||||
roleTotpCode = '';
|
|
||||||
showRoleTotpModal = false;
|
|
||||||
pendingRoles = null;
|
|
||||||
modalError = '';
|
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() {
|
async function handleDeleteAccount() {
|
||||||
loading = true;
|
loading = true;
|
||||||
modalError = '';
|
modalError = '';
|
||||||
const token = getToken();
|
const token = getToken();
|
||||||
if (totpEnabled && !deleteTotpCode) {
|
let totpcode = '';
|
||||||
showDeleteTotpModal = true;
|
if (totpEnabled) {
|
||||||
loading = false;
|
totpcode = String(
|
||||||
return;
|
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}`, {
|
const res = await fetch(`/api/user/uuid/${data.user?.uuid}`, {
|
||||||
method: 'DELETE',
|
method: 'DELETE',
|
||||||
headers: {
|
headers: {
|
||||||
Authorization: `Bearer ${token}`
|
Authorization: `Bearer ${token}`
|
||||||
},
|
},
|
||||||
body: totpEnabled && deleteTotpCode ? JSON.stringify({ totpcode: deleteTotpCode }) : undefined
|
body: totpEnabled && totpcode ? JSON.stringify({ totpcode }) : undefined
|
||||||
});
|
});
|
||||||
loading = false;
|
loading = false;
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const err = await res.json();
|
const err = await res.json();
|
||||||
modalError = err.message || 'Failed to delete account';
|
modalError = err.message || 'Failed to delete account';
|
||||||
|
await openModal({
|
||||||
|
mode: 'confirm',
|
||||||
|
title: 'Error',
|
||||||
|
message: modalError,
|
||||||
|
confirmButtonText: 'OK',
|
||||||
|
cancelValue: true
|
||||||
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
showDeleteModal = false;
|
|
||||||
showDeleteTotpModal = false;
|
|
||||||
deleteTotpCode = '';
|
|
||||||
window.location.href = '/';
|
window.location.href = '/';
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -160,17 +177,57 @@
|
|||||||
totpEnabled = Boolean((value as { enabled?: boolean }).enabled);
|
totpEnabled = Boolean((value as { enabled?: boolean }).enabled);
|
||||||
}
|
}
|
||||||
user.update((u) => (u ? { ...u, totpEnabled } : u));
|
user.update((u) => (u ? { ...u, totpEnabled } : u));
|
||||||
showTotpModal = false;
|
|
||||||
modalError = '';
|
modalError = '';
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleDeleteTotpConfirm(value: unknown) {
|
async function openEditDisplayName() {
|
||||||
if (typeof value === 'string') {
|
const value = String(
|
||||||
deleteTotpCode = value.trim();
|
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(() => {
|
onMount(() => {
|
||||||
@@ -181,6 +238,10 @@
|
|||||||
if (interval) clearInterval(interval);
|
if (interval) clearInterval(interval);
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
|
$: reportSiteKey =
|
||||||
|
(data as unknown as { authOptions?: { cf_turnstile_site_key?: string | null } }).authOptions
|
||||||
|
?.cf_turnstile_site_key ?? null;
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<svelte:head>
|
<svelte:head>
|
||||||
@@ -206,9 +267,9 @@
|
|||||||
<main
|
<main
|
||||||
class="flex min-h-[calc(100vh-60px)] w-full flex-col items-center justify-center pt-5 pb-5 text-white"
|
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">
|
<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
|
<span
|
||||||
class="relative flex h-7 w-7 items-center justify-center overflow-hidden rounded-full"
|
class="relative flex h-7 w-7 items-center justify-center overflow-hidden rounded-full"
|
||||||
use:tooltip={roles[403]}
|
use:tooltip={roles[403]}
|
||||||
@@ -216,7 +277,7 @@
|
|||||||
<User class="h-8 w-8 text-neutral-500" />
|
<User class="h-8 w-8 text-neutral-500" />
|
||||||
<Ban class="absolute h-7 w-7 text-red-500" />
|
<Ban class="absolute h-7 w-7 text-red-500" />
|
||||||
</span>
|
</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}
|
{#if data.user?.roles?.length}
|
||||||
<span use:tooltip={roles[Math.max(...data.user.roles) as keyof typeof roles]}>
|
<span use:tooltip={roles[Math.max(...data.user.roles) as keyof typeof roles]}>
|
||||||
<ShieldUser class="h-8 w-8 text-neutral-400" />
|
<ShieldUser class="h-8 w-8 text-neutral-400" />
|
||||||
@@ -253,6 +314,27 @@
|
|||||||
>{pagination.totalCount} paste{pagination.totalCount !== 1 ? 's' : ''}</span
|
>{pagination.totalCount} paste{pagination.totalCount !== 1 ? 's' : ''}</span
|
||||||
>
|
>
|
||||||
</div>
|
</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">
|
<div class="flex shrink-0 items-center">
|
||||||
<Hash class="mr-1 h-6 w-6 text-neutral-400" />
|
<Hash class="mr-1 h-6 w-6 text-neutral-400" />
|
||||||
<span class="text-neutral-400" use:tooltip={`User #${data.user?.uid}`}>
|
<span class="text-neutral-400" use:tooltip={`User #${data.user?.uid}`}>
|
||||||
@@ -271,13 +353,29 @@
|
|||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</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">
|
<div class="mt-4 flex flex-wrap justify-center gap-2">
|
||||||
<button
|
<button
|
||||||
on:click={() => {
|
on:click={openEditDisplayName}
|
||||||
showEditModal = true;
|
|
||||||
modalError = '';
|
|
||||||
}}
|
|
||||||
class="flex items-center gap-2 rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600"
|
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" />
|
<Pencil class="h-4 w-4" />
|
||||||
@@ -285,34 +383,25 @@
|
|||||||
</button>
|
</button>
|
||||||
{#if isOwner}
|
{#if isOwner}
|
||||||
<button
|
<button
|
||||||
on:click={() => {
|
on:click={openTotpSetup}
|
||||||
showTotpModal = true;
|
|
||||||
modalError = '';
|
|
||||||
}}
|
|
||||||
class="flex items-center gap-2 rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600"
|
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" />
|
<ShieldUser class="h-4 w-4" />
|
||||||
{totpEnabled ? 'Manage 2FA' : 'Enable 2FA'}
|
{totpEnabled ? 'Manage 2FA' : 'Enable 2FA'}
|
||||||
</button>
|
</button>
|
||||||
{/if}
|
{/if}
|
||||||
{#if $user?.roles.some((r) => r === 255)}
|
{#if $user?.roles?.some((r) => r === 255)}
|
||||||
<button
|
<button
|
||||||
on:click={() => {
|
on:click={openEditRoles}
|
||||||
showRoleModal = true;
|
|
||||||
modalError = '';
|
|
||||||
}}
|
|
||||||
class="flex items-center gap-2 rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600"
|
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" />
|
<ShieldUser class="h-4 w-4" />
|
||||||
Edit Roles
|
Edit Roles
|
||||||
</button>
|
</button>
|
||||||
{/if}
|
{/if}
|
||||||
{#if isOwner || $user?.roles.some((r) => r === 255)}
|
{#if isOwner || $user?.roles?.some((r) => r === 255)}
|
||||||
<button
|
<button
|
||||||
on:click={() => {
|
on:click={openDeleteAccount}
|
||||||
showDeleteModal = true;
|
|
||||||
modalError = '';
|
|
||||||
}}
|
|
||||||
class="flex items-center gap-2 rounded bg-red-900 px-4 py-2 text-sm font-medium transition-colors hover:bg-red-800"
|
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" />
|
<Trash2 class="h-4 w-4" />
|
||||||
@@ -342,6 +431,156 @@
|
|||||||
</p>
|
</p>
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</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}
|
{#if pagination.totalPages && pagination.totalPages > 1}
|
||||||
<div class="mt-4 flex items-center justify-center gap-4">
|
<div class="mt-4 flex items-center justify-center gap-4">
|
||||||
<button
|
<button
|
||||||
@@ -366,92 +605,6 @@
|
|||||||
</div>
|
</div>
|
||||||
</main>
|
</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>
|
<style>
|
||||||
button {
|
button {
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
|
|||||||
@@ -60,14 +60,16 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
return Ok(new
|
return Ok(new
|
||||||
{
|
{
|
||||||
message = "User registered successfully.",
|
message = "User registered successfully.",
|
||||||
user = new
|
user = new UserResponseDto
|
||||||
{
|
{
|
||||||
user.UID,
|
UID = user.UID,
|
||||||
user.UUID,
|
UUID = user.UUID,
|
||||||
user.Username,
|
Username = user.Username,
|
||||||
user.Email,
|
DisplayName = user.DisplayName,
|
||||||
user.DisplayName,
|
Email = user.Email,
|
||||||
user.Roles
|
Roles = user.Roles,
|
||||||
|
Visibility = user.Visibility,
|
||||||
|
LastLogin = user.LastLogin
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
@@ -112,7 +114,13 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
}
|
}
|
||||||
var token = _authService.GenerateJWTToken(user);
|
var token = _authService.GenerateJWTToken(user);
|
||||||
await _authService.UpdateLoginTime(user);
|
await _authService.UpdateLoginTime(user);
|
||||||
return Ok(new { success = true, token.Result });
|
var result = await token;
|
||||||
|
return Ok(new LoginResponseDto
|
||||||
|
{
|
||||||
|
Success = true,
|
||||||
|
Token = result.Token ?? string.Empty,
|
||||||
|
RefreshToken = result.RefreshToken ?? string.Empty
|
||||||
|
});
|
||||||
}
|
}
|
||||||
[HttpPost]
|
[HttpPost]
|
||||||
[Route("refresh")]
|
[Route("refresh")]
|
||||||
@@ -122,15 +130,15 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
var jwtResult = await _authService.RefreshJWTToken(request.Token, request.RefreshToken);
|
var jwtResult = await _authService.RefreshJWTToken(request.Token, request.RefreshToken);
|
||||||
return Ok(new
|
return Ok(new TokenRefreshResponseDto
|
||||||
{
|
{
|
||||||
success = jwtResult?.Success,
|
Success = jwtResult?.Success ?? false,
|
||||||
message = jwtResult?.Errors != null && jwtResult.Errors.Count > 0 ? string.Join("; ", jwtResult.Errors) : "Token refreshed successfully.",
|
Message = jwtResult?.Errors != null && jwtResult.Errors.Count > 0 ? string.Join("; ", jwtResult.Errors) : "Token refreshed successfully.",
|
||||||
token = new
|
Token = jwtResult != null ? new TokenData
|
||||||
{
|
{
|
||||||
jwtResult?.Token,
|
Token = jwtResult.Token,
|
||||||
jwtResult?.RefreshToken
|
RefreshToken = jwtResult.RefreshToken
|
||||||
}
|
} : null
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
|
|||||||
@@ -3,8 +3,9 @@ using Microsoft.AspNetCore.Mvc;
|
|||||||
using Microsoft.AspNetCore.RateLimiting;
|
using Microsoft.AspNetCore.RateLimiting;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using SharpbinV3.Server.Data.Entities;
|
using SharpbinV3.Server.Data.Entities;
|
||||||
using SharpbinV3.Server.DTOs;
|
|
||||||
using SharpbinV3.Server.DTOs.Paste;
|
using SharpbinV3.Server.DTOs.Paste;
|
||||||
|
using SharpbinV3.Server.DTOs.Report;
|
||||||
|
using SharpbinV3.Server.DTOs.User;
|
||||||
using SharpbinV3.Server.Extensions;
|
using SharpbinV3.Server.Extensions;
|
||||||
using SharpbinV3.Server.Services;
|
using SharpbinV3.Server.Services;
|
||||||
using SharpbinV3.Server.Services.Verification;
|
using SharpbinV3.Server.Services.Verification;
|
||||||
@@ -54,14 +55,14 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
|
|
||||||
var user = await _authService.GetUserFromHttpContext(HttpContext);
|
var user = await _authService.GetUserFromHttpContext(HttpContext);
|
||||||
Paste paste = await _pasteService.Create(user, content, title, syntax, visibility, expiresAt, _pasteSettings.EnablePasteCompression);
|
Paste paste = await _pasteService.Create(user, content, title, syntax, visibility, expiresAt, _pasteSettings.EnablePasteCompression);
|
||||||
return Ok(new
|
return Ok(new PasteCreatedResponseDto
|
||||||
{
|
{
|
||||||
paste.ID,
|
ID = paste.ID,
|
||||||
paste.UUID,
|
UUID = paste.UUID,
|
||||||
paste.IsCompressed,
|
IsCompressed = paste.IsCompressed,
|
||||||
paste.Size,
|
Size = paste.Size,
|
||||||
paste.TrueSize,
|
TrueSize = paste.TrueSize,
|
||||||
paste.ExpiresAt
|
ExpiresAt = paste.ExpiresAt
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -71,33 +72,49 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
{
|
{
|
||||||
var paste = await _pasteService.Get(id);
|
var paste = await _pasteService.Get(id);
|
||||||
if (paste == null)
|
if (paste == null)
|
||||||
return NotFound(new { success = false, message = "Paste not found"});
|
return NotFound(new { success = false, message = "Paste not found" });
|
||||||
|
var jwtUser = HttpContext.GetJwtUser();
|
||||||
|
|
||||||
|
int? reportCount = null;
|
||||||
|
if (jwtUser != null && jwtUser.Roles.Any(r => r == 1 || r == 255))
|
||||||
|
{
|
||||||
|
var query = new ReportQuery
|
||||||
|
{
|
||||||
|
PastePID = paste.PID
|
||||||
|
};
|
||||||
|
reportCount = await _reportService.GetReportCount(query);
|
||||||
|
}
|
||||||
|
|
||||||
return Ok(new
|
return Ok(new
|
||||||
{
|
{
|
||||||
success = true,
|
success = true,
|
||||||
paste = new {
|
paste = new PasteResponseDto
|
||||||
paste.ID,
|
{
|
||||||
paste.UUID,
|
ID = paste.ID,
|
||||||
paste.Title,
|
UUID = paste.UUID,
|
||||||
paste.Size,
|
Title = paste.Title,
|
||||||
paste.TrueSize,
|
Size = paste.Size,
|
||||||
paste.IsCompressed,
|
TrueSize = paste.TrueSize,
|
||||||
paste.Views,
|
IsCompressed = paste.IsCompressed,
|
||||||
paste.Syntax,
|
Views = paste.Views,
|
||||||
paste.Visibility,
|
Syntax = paste.Syntax,
|
||||||
paste.ExpiresAt,
|
Visibility = paste.Visibility,
|
||||||
paste.EditedAt,
|
ExpiresAt = paste.ExpiresAt,
|
||||||
Author = paste.User != null && paste.User.Visibility == 0 ? new
|
EditedAt = paste.EditedAt,
|
||||||
|
ReportCount = reportCount,
|
||||||
|
Author = paste.User != null && paste.User.Visibility == 0 ? new UserSimpleDto
|
||||||
{
|
{
|
||||||
paste.User.UID,
|
UID = paste.User.UID,
|
||||||
paste.User.UUID,
|
UUID = paste.User.UUID,
|
||||||
paste.User.Username,
|
Username = paste.User.Username,
|
||||||
paste.User.DisplayName,
|
DisplayName = paste.User.DisplayName,
|
||||||
paste.User.Visibility
|
Visibility = paste.User.Visibility,
|
||||||
|
Roles = paste.User.Roles
|
||||||
} : null
|
} : null
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpGet]
|
[HttpGet]
|
||||||
[Route("{id}/raw")]
|
[Route("{id}/raw")]
|
||||||
public async Task<IActionResult> GetRawPasteByID(string id)
|
public async Task<IActionResult> GetRawPasteByID(string id)
|
||||||
@@ -180,18 +197,18 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
{
|
{
|
||||||
success = true,
|
success = true,
|
||||||
message = "Paste metadata updated successfully.",
|
message = "Paste metadata updated successfully.",
|
||||||
paste = new
|
paste = new PasteResponseDto
|
||||||
{
|
{
|
||||||
newPaste.ID,
|
ID = newPaste.ID,
|
||||||
newPaste.UUID,
|
UUID = newPaste.UUID,
|
||||||
newPaste.Title,
|
Title = newPaste.Title,
|
||||||
newPaste.Size,
|
Size = newPaste.Size,
|
||||||
newPaste.TrueSize,
|
TrueSize = newPaste.TrueSize,
|
||||||
newPaste.IsCompressed,
|
IsCompressed = newPaste.IsCompressed,
|
||||||
newPaste.Views,
|
Views = newPaste.Views,
|
||||||
newPaste.Syntax,
|
Syntax = newPaste.Syntax,
|
||||||
newPaste.Visibility,
|
Visibility = newPaste.Visibility,
|
||||||
newPaste.ExpiresAt
|
ExpiresAt = newPaste.ExpiresAt
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -273,11 +290,21 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
if (report == null)
|
if (report == null)
|
||||||
return StatusCode(500, new { success = false, message = "An error occurred while reporting the paste." });
|
return StatusCode(500, new { success = false, message = "An error occurred while reporting the paste." });
|
||||||
|
|
||||||
return Ok(new { success = true, message = "Paste reported successfully.", report = new
|
return Ok(new
|
||||||
|
{
|
||||||
|
success = true,
|
||||||
|
message = "Paste reported successfully.",
|
||||||
|
report = new ReportResponseDto
|
||||||
{
|
{
|
||||||
id = report.ReportID,
|
ReportID = report.ReportID,
|
||||||
reportType,
|
Type = report.Type,
|
||||||
description = report.Description
|
Status = report.Status,
|
||||||
|
Description = report.Description,
|
||||||
|
CreatedAt = report.CreatedAt,
|
||||||
|
UpdatedAt = report.UpdatedAt,
|
||||||
|
ReporterUUID = report.ReporterUUID,
|
||||||
|
TargetType = report.TargetType,
|
||||||
|
UserUUID = report.UserUUID
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -355,19 +382,19 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
public async Task<IActionResult> GetRecentPastes()
|
public async Task<IActionResult> GetRecentPastes()
|
||||||
{
|
{
|
||||||
var results = await _pasteService.GetList(0, 50, true);
|
var results = await _pasteService.GetList(0, 50, true);
|
||||||
return Ok(results.Select(p => new
|
return Ok(results.Select(p => new PasteResponseDto
|
||||||
{
|
{
|
||||||
p.ID,
|
ID = p.ID,
|
||||||
p.UUID,
|
UUID = p.UUID,
|
||||||
p.Title,
|
Title = p.Title,
|
||||||
p.Size,
|
Size = p.Size,
|
||||||
p.TrueSize,
|
TrueSize = p.TrueSize,
|
||||||
p.IsCompressed,
|
IsCompressed = p.IsCompressed,
|
||||||
p.Views,
|
Views = p.Views,
|
||||||
p.Syntax,
|
Syntax = p.Syntax,
|
||||||
p.Visibility,
|
Visibility = p.Visibility,
|
||||||
p.ExpiresAt,
|
ExpiresAt = p.ExpiresAt,
|
||||||
p.EditedAt
|
EditedAt = p.EditedAt
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -375,20 +402,19 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
[Route("info")]
|
[Route("info")]
|
||||||
public IActionResult GetCreatePasteOptions()
|
public IActionResult GetCreatePasteOptions()
|
||||||
{
|
{
|
||||||
var options = new
|
return Ok(new PasteOptionsDto
|
||||||
{
|
{
|
||||||
syntaxes = _pasteSettings.ValidSyntaxLanguages,
|
Syntaxes = _pasteSettings.ValidSyntaxLanguages,
|
||||||
visibilities = new[]
|
Visibilities =
|
||||||
{
|
[
|
||||||
new { value = 0, displayName = "Public" },
|
new() { Value = 0, DisplayName = "Public" },
|
||||||
new { value = 1, displayName = "Unlisted" },
|
new() { Value = 1, DisplayName = "Unlisted" },
|
||||||
new { value = 2, displayName = "Private" }
|
new() { Value = 2, DisplayName = "Private" }
|
||||||
},
|
],
|
||||||
maxTitleLength = _pasteSettings.MaxTitleLength,
|
MaxTitleLength = _pasteSettings.MaxTitleLength,
|
||||||
maxPasteSize = _pasteSettings.MaxPasteSizeInBytes,
|
MaxPasteSize = _pasteSettings.MaxPasteSizeInBytes,
|
||||||
requiresVerification = _pasteSettings.RequiresVerfication
|
RequiresVerification = _pasteSettings.RequiresVerfication
|
||||||
};
|
});
|
||||||
return Ok(options);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,238 @@
|
|||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.AspNetCore.RateLimiting;
|
||||||
|
using SharpbinV3.Server.Data.Entities;
|
||||||
|
using SharpbinV3.Server.DTOs.Report;
|
||||||
|
using SharpbinV3.Server.Extensions;
|
||||||
|
using SharpbinV3.Server.Services;
|
||||||
|
|
||||||
|
namespace SharpbinV3.Server.Controllers
|
||||||
|
{
|
||||||
|
[Route("api/[controller]")]
|
||||||
|
[ApiController]
|
||||||
|
public class ReportController(ReportService reportService) : Controller
|
||||||
|
{
|
||||||
|
[Route("{reportId:int}")]
|
||||||
|
[HttpGet]
|
||||||
|
[EnableRateLimiting("Sliding")]
|
||||||
|
[Authorize(Policy = "AuthAndNotBanned")]
|
||||||
|
public async Task<IActionResult> GetReportById(int reportId)
|
||||||
|
{
|
||||||
|
var user = HttpContext.GetJwtUser();
|
||||||
|
if (user is null)
|
||||||
|
return Unauthorized(new { success = false, message = "You must be logged in to view reports." });
|
||||||
|
|
||||||
|
var report = await reportService.GetReportByID(reportId);
|
||||||
|
if (report is null)
|
||||||
|
return NotFound(new { success = false, message = "Report not found." });
|
||||||
|
|
||||||
|
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
|
||||||
|
if (!hasPrivilegedRole && report.ReporterUUID != user.UUID)
|
||||||
|
return StatusCode(403, new { success = false, message = "You do not have permission to view this report." });
|
||||||
|
|
||||||
|
var (Username, DisplayName) = await reportService.GetReporterInfo(report.ReporterUUID);
|
||||||
|
|
||||||
|
return Ok(new ReportResponseDto
|
||||||
|
{
|
||||||
|
ReportID = report.ReportID,
|
||||||
|
Type = report.Type,
|
||||||
|
Status = report.Status,
|
||||||
|
Description = report.Description,
|
||||||
|
CreatedAt = report.CreatedAt,
|
||||||
|
UpdatedAt = report.UpdatedAt,
|
||||||
|
ReporterUUID = report.ReporterUUID,
|
||||||
|
ReporterUsername = Username,
|
||||||
|
ReporterDisplayName = DisplayName,
|
||||||
|
TargetType = report.TargetType,
|
||||||
|
PasteId = report.Paste?.ID,
|
||||||
|
PasteTitle = report.Paste?.Title,
|
||||||
|
UserUUID = report.UserUUID,
|
||||||
|
TargetUsername = report.User?.Username,
|
||||||
|
TargetDisplayName = report.User?.DisplayName
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
[Route("{reportId:int}")]
|
||||||
|
[HttpPatch]
|
||||||
|
[EnableRateLimiting("Sensitive")]
|
||||||
|
[Authorize(Policy = "AuthAndNotBanned")]
|
||||||
|
public async Task<IActionResult> UpdateReport(int reportId, [FromBody] ReportUpdateDto request)
|
||||||
|
{
|
||||||
|
var user = HttpContext.GetJwtUser();
|
||||||
|
if (user is null)
|
||||||
|
return Unauthorized(new { success = false, message = "You must be logged in to update reports." });
|
||||||
|
if (!user.Roles.Contains(1) && !user.Roles.Contains(255))
|
||||||
|
return StatusCode(403, new { success = false, message = "You do not have permission to update reports." });
|
||||||
|
|
||||||
|
var report = await reportService.GetReportByID(reportId);
|
||||||
|
if (report is null)
|
||||||
|
return NotFound(new { success = false, message = "Report not found." });
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(request.Type))
|
||||||
|
{
|
||||||
|
Enum.TryParse<ReportType>(request.Type, true, out var reportType);
|
||||||
|
if (!Enum.IsDefined(reportType))
|
||||||
|
return BadRequest(new { success = false, message = "Invalid report type." });
|
||||||
|
report.Type = reportType;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(request.Status))
|
||||||
|
{
|
||||||
|
Enum.TryParse<ReportStatus>(request.Status, true, out var reportStatus);
|
||||||
|
if (!Enum.IsDefined(reportStatus))
|
||||||
|
return BadRequest(new { success = false, message = "Invalid report status." });
|
||||||
|
report.Status = reportStatus;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.Description != null)
|
||||||
|
report.Description = request.Description;
|
||||||
|
|
||||||
|
report.UpdatedAt = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
|
||||||
|
var updated = await reportService.UpdateReport(report);
|
||||||
|
var (Username, DisplayName) = await reportService.GetReporterInfo(updated.ReporterUUID);
|
||||||
|
|
||||||
|
return Ok(new ReportResponseDto
|
||||||
|
{
|
||||||
|
ReportID = updated.ReportID,
|
||||||
|
Type = updated.Type,
|
||||||
|
Status = updated.Status,
|
||||||
|
Description = updated.Description,
|
||||||
|
CreatedAt = updated.CreatedAt,
|
||||||
|
UpdatedAt = updated.UpdatedAt,
|
||||||
|
ReporterUUID = updated.ReporterUUID,
|
||||||
|
ReporterUsername = Username,
|
||||||
|
ReporterDisplayName = DisplayName,
|
||||||
|
TargetType = updated.TargetType,
|
||||||
|
PasteId = updated.Paste?.ID,
|
||||||
|
PasteTitle = updated.Paste?.Title,
|
||||||
|
UserUUID = updated.UserUUID,
|
||||||
|
TargetUsername = updated.User?.Username,
|
||||||
|
TargetDisplayName = updated.User?.DisplayName
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
[Route("options")]
|
||||||
|
[HttpGet]
|
||||||
|
public IActionResult GetReportOptions()
|
||||||
|
{
|
||||||
|
var validTypes = Enum.GetNames<ReportType>();
|
||||||
|
var statuses = Enum.GetNames<ReportStatus>();
|
||||||
|
return Ok(new ReportOptionsDto { Types = validTypes, Statuses = statuses });
|
||||||
|
}
|
||||||
|
|
||||||
|
[Route("pastes")]
|
||||||
|
[HttpGet]
|
||||||
|
[EnableRateLimiting("Sliding")]
|
||||||
|
[Authorize(Policy = "AuthAndNotBanned")]
|
||||||
|
public async Task<IActionResult> GetReportsForPastes([FromQuery] ReportQuery request)
|
||||||
|
{
|
||||||
|
var user = HttpContext.GetJwtUser();
|
||||||
|
if (user is null)
|
||||||
|
return Unauthorized(new { success = false, message = "You must be logged in to view reports." });
|
||||||
|
if (!user.Roles.Contains(1) && !user.Roles.Contains(255))
|
||||||
|
return StatusCode(403, new { success = false, message = "You do not have permission to view pastes." });
|
||||||
|
|
||||||
|
var query = request with
|
||||||
|
{
|
||||||
|
Page = Math.Max(request.Page, 1),
|
||||||
|
PageSize = Math.Clamp(request.PageSize, 1, 100),
|
||||||
|
UserUUID = null
|
||||||
|
};
|
||||||
|
|
||||||
|
var reports = await reportService.GetPasteReports(query);
|
||||||
|
var totalCount = await reportService.GetReportCount(query);
|
||||||
|
var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize);
|
||||||
|
return Ok(new
|
||||||
|
{
|
||||||
|
Reports = reports,
|
||||||
|
Pagination = new
|
||||||
|
{
|
||||||
|
query.Page,
|
||||||
|
query.PageSize,
|
||||||
|
TotalCount = totalCount,
|
||||||
|
TotalPages = totalPages
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
[Route("users")]
|
||||||
|
[HttpGet]
|
||||||
|
[EnableRateLimiting("Sliding")]
|
||||||
|
[Authorize(Policy = "AuthAndNotBanned")]
|
||||||
|
public async Task<IActionResult> GetReportsForUsers([FromQuery] ReportQuery request)
|
||||||
|
{
|
||||||
|
var user = HttpContext.GetJwtUser();
|
||||||
|
if (user is null)
|
||||||
|
return Unauthorized(new { success = false, message = "You must be logged in to view reports." });
|
||||||
|
if (!user.Roles.Contains(1) && !user.Roles.Contains(255))
|
||||||
|
return StatusCode(403, new { success = false, message = "You do not have permission to view users." });
|
||||||
|
|
||||||
|
var query = request with
|
||||||
|
{
|
||||||
|
Page = Math.Max(request.Page, 1),
|
||||||
|
PageSize = Math.Clamp(request.PageSize, 1, 100),
|
||||||
|
PastePID = null,
|
||||||
|
PasteId = null
|
||||||
|
};
|
||||||
|
|
||||||
|
var reports = await reportService.GetUserReports(query);
|
||||||
|
var totalCount = await reportService.GetReportCount(query);
|
||||||
|
var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize);
|
||||||
|
return Ok(new
|
||||||
|
{
|
||||||
|
Reports = reports,
|
||||||
|
Pagination = new
|
||||||
|
{
|
||||||
|
query.Page,
|
||||||
|
query.PageSize,
|
||||||
|
TotalCount = totalCount,
|
||||||
|
TotalPages = totalPages
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
[Route("all")]
|
||||||
|
[HttpGet]
|
||||||
|
[EnableRateLimiting("Sliding")]
|
||||||
|
[Authorize(Policy = "AuthAndNotBanned")]
|
||||||
|
public async Task<IActionResult> GetAllReports(
|
||||||
|
[FromQuery] Guid? reporterUuid,
|
||||||
|
[FromQuery] ReportTargetType? targetType,
|
||||||
|
[FromQuery] ReportType? type,
|
||||||
|
[FromQuery] ReportStatus? status,
|
||||||
|
[FromQuery] int page = 1,
|
||||||
|
[FromQuery] int pageSize = 20)
|
||||||
|
{
|
||||||
|
var user = HttpContext.GetJwtUser();
|
||||||
|
if (user is null)
|
||||||
|
return Unauthorized(new { success = false, message = "You must be logged in to view reports." });
|
||||||
|
if (!user.Roles.Contains(1) && !user.Roles.Contains(255))
|
||||||
|
return StatusCode(403, new { success = false, message = "You do not have permission to view reports." });
|
||||||
|
|
||||||
|
var query = new ReportQuery
|
||||||
|
{
|
||||||
|
ReporterUUID = reporterUuid,
|
||||||
|
TargetType = targetType,
|
||||||
|
Type = type,
|
||||||
|
Status = status,
|
||||||
|
Page = Math.Max(page, 1),
|
||||||
|
PageSize = Math.Clamp(pageSize, 1, 100)
|
||||||
|
};
|
||||||
|
|
||||||
|
var reports = await reportService.GetReports(query);
|
||||||
|
var totalCount = await reportService.GetReportCount(query);
|
||||||
|
var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize);
|
||||||
|
return Ok(new
|
||||||
|
{
|
||||||
|
Reports = reports,
|
||||||
|
Pagination = new
|
||||||
|
{
|
||||||
|
query.Page,
|
||||||
|
query.PageSize,
|
||||||
|
TotalCount = totalCount,
|
||||||
|
TotalPages = totalPages
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,6 +6,8 @@ using Microsoft.Extensions.Options;
|
|||||||
using SharpbinV3.Server.Data;
|
using SharpbinV3.Server.Data;
|
||||||
using SharpbinV3.Server.Data.Entities;
|
using SharpbinV3.Server.Data.Entities;
|
||||||
using SharpbinV3.Server.DTOs;
|
using SharpbinV3.Server.DTOs;
|
||||||
|
using SharpbinV3.Server.DTOs.Paste;
|
||||||
|
using SharpbinV3.Server.DTOs.Report;
|
||||||
using SharpbinV3.Server.DTOs.User;
|
using SharpbinV3.Server.DTOs.User;
|
||||||
using SharpbinV3.Server.Extensions;
|
using SharpbinV3.Server.Extensions;
|
||||||
using SharpbinV3.Server.Services;
|
using SharpbinV3.Server.Services;
|
||||||
@@ -31,26 +33,26 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
public async Task<IActionResult> GetByUsername(string username, [FromQuery] int page = 1)
|
public async Task<IActionResult> GetByUsername(string username, [FromQuery] int page = 1)
|
||||||
{
|
{
|
||||||
var user = await _userService.GetByUsername(username, withPastes: true);
|
var user = await _userService.GetByUsername(username, withPastes: true);
|
||||||
return user == null ? NotFound(new { success = false, message = "User not found." }) : Ok(await BuildUserResponse(user, page));
|
return user == null ? NotFound(new { success = false, message = "User not found." }) : await BuildUserResponse(user, page);
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpGet("uuid/{uuid}")]
|
[HttpGet("uuid/{uuid}")]
|
||||||
public async Task<IActionResult> GetByUUID(Guid uuid, [FromQuery] int page = 1)
|
public async Task<IActionResult> GetByUUID(Guid uuid, [FromQuery] int page = 1)
|
||||||
{
|
{
|
||||||
var user = await _userService.GetByUUID(uuid, withPastes: true);
|
var user = await _userService.GetByUUID(uuid, withPastes: true);
|
||||||
return user == null ? NotFound(new { success = false, message = "User not found."}) : Ok(await BuildUserResponse(user, page));
|
return user == null ? NotFound(new { success = false, message = "User not found." }) : await BuildUserResponse(user, page);
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpGet("me")]
|
[HttpGet("me")]
|
||||||
[Authorize]
|
[Authorize]
|
||||||
public async Task<IActionResult> GetMe([FromQuery] int page = 1)
|
public async Task<IActionResult> GetMe([FromQuery] int page = 1)
|
||||||
{
|
{
|
||||||
var userUUID = HttpContext.User?.FindFirst("UUID")?.Value;
|
var userUUID = HttpContext.User?.FindFirst("uuid")?.Value;
|
||||||
if (userUUID is null)
|
if (userUUID is null)
|
||||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
return Unauthorized(new { success = false, message = "Invalid token." });
|
||||||
|
|
||||||
var user = await _userService.GetByUUID(Guid.Parse(userUUID), withPastes: true);
|
var user = await _userService.GetByUUID(Guid.Parse(userUUID), withPastes: true);
|
||||||
return user == null ? NotFound(new { success = false, message = "User not found."}) : Ok(await BuildUserResponse(user, page));
|
return user == null ? NotFound(new { success = false, message = "User not found." }) : await BuildUserResponse(user, page);
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpPatch("uuid/{uuid}")]
|
[HttpPatch("uuid/{uuid}")]
|
||||||
@@ -180,12 +182,18 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
return Ok(new
|
return Ok(new
|
||||||
{
|
{
|
||||||
success = true,
|
success = true,
|
||||||
message = "Paste reported successfully.",
|
message = "User reported successfully.",
|
||||||
report = new
|
report = new ReportResponseDto
|
||||||
{
|
{
|
||||||
id = report.ReportID,
|
ReportID = report.ReportID,
|
||||||
reportType,
|
Type = report.Type,
|
||||||
description = report.Description
|
Status = report.Status,
|
||||||
|
Description = report.Description,
|
||||||
|
CreatedAt = report.CreatedAt,
|
||||||
|
UpdatedAt = report.UpdatedAt,
|
||||||
|
ReporterUUID = report.ReporterUUID,
|
||||||
|
TargetType = report.TargetType,
|
||||||
|
UserUUID = report.UserUUID
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -244,9 +252,89 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
return Ok(new { success = true, message = "Report deleted successfully." });
|
return Ok(new { success = true, message = "Report deleted successfully." });
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<object> BuildUserResponse(User user, int page = 1)
|
[HttpGet]
|
||||||
|
[Authorize]
|
||||||
|
[Route("{uuid}/reports")]
|
||||||
|
public async Task<IActionResult> GetUserReports(Guid uuid, [FromQuery] ReportQuery request)
|
||||||
{
|
{
|
||||||
var isAuthenticatedUser = HttpContext.User?.FindFirst("UUID")?.Value == user.UUID.ToString();
|
var jwtUser = HttpContext.GetJwtUser();
|
||||||
|
if (jwtUser == null)
|
||||||
|
return Unauthorized(new { success = false, message = "Invalid token." });
|
||||||
|
|
||||||
|
var user = await _userService.GetByUUID(uuid);
|
||||||
|
if (user == null)
|
||||||
|
return NotFound(new { success = false, message = "User not found." });
|
||||||
|
|
||||||
|
if (!jwtUser.Roles.Any(r => r == 1 || r == 255))
|
||||||
|
return StatusCode(403, new { success = false, message = "You do not have permission to view this user's reports." });
|
||||||
|
|
||||||
|
var query = request with
|
||||||
|
{
|
||||||
|
UserUUID = user.UUID,
|
||||||
|
Page = Math.Max(request.Page, 1),
|
||||||
|
PageSize = Math.Clamp(request.PageSize, 1, 100)
|
||||||
|
};
|
||||||
|
var reports = await _reportService.GetUserReports(query);
|
||||||
|
var totalCount = await _reportService.GetReportCount(query);
|
||||||
|
var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize);
|
||||||
|
return Ok(new
|
||||||
|
{
|
||||||
|
Reports = reports,
|
||||||
|
Pagination = new
|
||||||
|
{
|
||||||
|
query.Page,
|
||||||
|
query.PageSize,
|
||||||
|
TotalCount = totalCount,
|
||||||
|
TotalPages = totalPages
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet]
|
||||||
|
[Authorize]
|
||||||
|
[Route("{uuid}/reports/submitted")]
|
||||||
|
public async Task<IActionResult> GetUserSubmittedReports(Guid uuid, [FromQuery] ReportQuery request)
|
||||||
|
{
|
||||||
|
var jwtUser = HttpContext.GetJwtUser();
|
||||||
|
if (jwtUser == null)
|
||||||
|
return Unauthorized(new { success = false, message = "Invalid token." });
|
||||||
|
|
||||||
|
var user = await _userService.GetByUUID(uuid);
|
||||||
|
if (user == null)
|
||||||
|
return NotFound(new { success = false, message = "User not found." });
|
||||||
|
|
||||||
|
var isOwner = user.UUID == jwtUser.UUID;
|
||||||
|
var hasPrivilegedRole = jwtUser.Roles.Any(r => r == 1 || r == 255);
|
||||||
|
if (!isOwner && !hasPrivilegedRole)
|
||||||
|
return StatusCode(403, new { success = false, message = "You do not have permission to view this user's submitted reports." });
|
||||||
|
|
||||||
|
var query = request with
|
||||||
|
{
|
||||||
|
ReporterUUID = user.UUID,
|
||||||
|
Page = Math.Max(request.Page, 1),
|
||||||
|
PageSize = Math.Clamp(request.PageSize, 1, 100)
|
||||||
|
};
|
||||||
|
|
||||||
|
var reports = await _reportService.GetReports(query);
|
||||||
|
var totalCount = await _reportService.GetReportCount(query);
|
||||||
|
var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize);
|
||||||
|
|
||||||
|
return Ok(new
|
||||||
|
{
|
||||||
|
Reports = reports,
|
||||||
|
Pagination = new
|
||||||
|
{
|
||||||
|
query.Page,
|
||||||
|
query.PageSize,
|
||||||
|
TotalCount = totalCount,
|
||||||
|
TotalPages = totalPages
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<IActionResult> BuildUserResponse(User user, int page = 1)
|
||||||
|
{
|
||||||
|
var isAuthenticatedUser = HttpContext.User?.FindFirst("uuid")?.Value == user.UUID.ToString();
|
||||||
var pasteQuery = _db.Pastes.AsNoTracking().Where(p => p.AuthorUUID == user.UUID);
|
var pasteQuery = _db.Pastes.AsNoTracking().Where(p => p.AuthorUUID == user.UUID);
|
||||||
if (!isAuthenticatedUser)
|
if (!isAuthenticatedUser)
|
||||||
{
|
{
|
||||||
@@ -268,18 +356,18 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
.ThenByDescending(p => p.ID)
|
.ThenByDescending(p => p.ID)
|
||||||
.Skip(skip)
|
.Skip(skip)
|
||||||
.Take(pageSize)
|
.Take(pageSize)
|
||||||
.Select(p => new
|
.Select(p => new PasteResponseDto
|
||||||
{
|
{
|
||||||
p.ID,
|
ID = p.ID,
|
||||||
p.UUID,
|
UUID = p.UUID,
|
||||||
p.Title,
|
Title = p.Title,
|
||||||
p.Syntax,
|
Syntax = p.Syntax,
|
||||||
p.Size,
|
Size = p.Size,
|
||||||
p.TrueSize,
|
TrueSize = p.TrueSize,
|
||||||
p.Views,
|
Views = p.Views,
|
||||||
p.Visibility,
|
Visibility = p.Visibility,
|
||||||
p.EditedAt,
|
EditedAt = p.EditedAt,
|
||||||
p.ExpiresAt
|
ExpiresAt = p.ExpiresAt
|
||||||
})
|
})
|
||||||
.ToListAsync();
|
.ToListAsync();
|
||||||
|
|
||||||
@@ -293,31 +381,54 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
|
|
||||||
if (isAuthenticatedUser)
|
if (isAuthenticatedUser)
|
||||||
{
|
{
|
||||||
return new
|
var reports = await _reportService.GetReports(new ReportQuery
|
||||||
{
|
{
|
||||||
user.UID,
|
ReporterUUID = user.UUID,
|
||||||
user.Username,
|
Page = page,
|
||||||
user.UUID,
|
PageSize = pageSize
|
||||||
user.DisplayName,
|
});
|
||||||
user.Email,
|
var reportsCount = await _reportService.GetReportCountByReporter(user.UUID);
|
||||||
user.LastLogin,
|
|
||||||
user.Roles,
|
return Ok(new
|
||||||
user.Visibility,
|
{
|
||||||
|
User = new UserResponseDto
|
||||||
|
{
|
||||||
|
UID = user.UID,
|
||||||
|
Username = user.Username,
|
||||||
|
UUID = user.UUID,
|
||||||
|
DisplayName = user.DisplayName,
|
||||||
|
Email = user.Email,
|
||||||
|
LastLogin = user.LastLogin,
|
||||||
|
Roles = user.Roles,
|
||||||
|
Visibility = user.Visibility
|
||||||
|
},
|
||||||
Pastes = pastes,
|
Pastes = pastes,
|
||||||
Pagination = pagination
|
Reports = reports,
|
||||||
};
|
Pagination = pagination,
|
||||||
|
ReportsPagination = new
|
||||||
|
{
|
||||||
|
Page = page,
|
||||||
|
PageSize = pageSize,
|
||||||
|
TotalCount = reportsCount,
|
||||||
|
TotalPages = (int)Math.Ceiling(reportsCount / (double)pageSize)
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return new
|
return Ok(new
|
||||||
{
|
{
|
||||||
user.UID,
|
User = new UserSimpleDto
|
||||||
user.Username,
|
{
|
||||||
user.UUID,
|
UID = user.UID,
|
||||||
user.DisplayName,
|
Username = user.Username,
|
||||||
user.Roles,
|
UUID = user.UUID,
|
||||||
|
DisplayName = user.DisplayName,
|
||||||
|
Roles = user.Roles,
|
||||||
|
Visibility = user.Visibility
|
||||||
|
},
|
||||||
Pastes = pastes,
|
Pastes = pastes,
|
||||||
Pagination = pagination
|
Pagination = pagination
|
||||||
};
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
namespace SharpbinV3.Server.DTOs.Auth
|
||||||
|
{
|
||||||
|
public class LoginResponseDto
|
||||||
|
{
|
||||||
|
public bool Success { get; set; }
|
||||||
|
public string Token { get; set; } = string.Empty;
|
||||||
|
public string RefreshToken { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
public class TokenRefreshResponseDto
|
||||||
|
{
|
||||||
|
public bool Success { get; set; }
|
||||||
|
public string? Message { get; set; }
|
||||||
|
public TokenData? Token { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class TokenData
|
||||||
|
{
|
||||||
|
public string? Token { get; set; }
|
||||||
|
public string? RefreshToken { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
using SharpbinV3.Server.DTOs.User;
|
||||||
|
|
||||||
|
namespace SharpbinV3.Server.DTOs.Paste
|
||||||
|
{
|
||||||
|
public class PasteResponseDto
|
||||||
|
{
|
||||||
|
public string ID { get; set; } = string.Empty;
|
||||||
|
public Guid UUID { get; set; }
|
||||||
|
public string? Title { get; set; }
|
||||||
|
public string? Syntax { get; set; }
|
||||||
|
public long Size { get; set; }
|
||||||
|
public long TrueSize { get; set; }
|
||||||
|
public bool IsCompressed { get; set; }
|
||||||
|
public int Views { get; set; }
|
||||||
|
public int Visibility { get; set; }
|
||||||
|
public long? EditedAt { get; set; }
|
||||||
|
public long ExpiresAt { get; set; }
|
||||||
|
public int? ReportCount { get; set; }
|
||||||
|
public UserSimpleDto? Author { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class PasteCreatedResponseDto
|
||||||
|
{
|
||||||
|
public string ID { get; set; } = string.Empty;
|
||||||
|
public Guid UUID { get; set; }
|
||||||
|
public bool IsCompressed { get; set; }
|
||||||
|
public long Size { get; set; }
|
||||||
|
public long TrueSize { get; set; }
|
||||||
|
public long ExpiresAt { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class PasteOptionsDto
|
||||||
|
{
|
||||||
|
public string[] Syntaxes { get; set; } = [];
|
||||||
|
public List<PasteVisibilityOptionDto> Visibilities { get; set; } = [];
|
||||||
|
public int MaxTitleLength { get; set; }
|
||||||
|
public long MaxPasteSize { get; set; }
|
||||||
|
public bool RequiresVerification { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class PasteVisibilityOptionDto
|
||||||
|
{
|
||||||
|
public int Value { get; set; }
|
||||||
|
public string DisplayName { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
using System.ComponentModel.DataAnnotations;
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
|
||||||
namespace SharpbinV3.Server.DTOs
|
namespace SharpbinV3.Server.DTOs.Report
|
||||||
{
|
{
|
||||||
public class ReportDto
|
public class ReportDto
|
||||||
{
|
{
|
||||||
[Required]
|
[Required]
|
||||||
[MaxLength(1000)]
|
[MinLength(12), MaxLength(1000)]
|
||||||
public string Description { get; set; } = string.Empty;
|
public string Description { get; set; } = string.Empty;
|
||||||
[Required]
|
[Required]
|
||||||
public string ReportType { get; set; } = string.Empty; // e.g., "Spam", "Abuse", etc.
|
public string ReportType { get; set; } = string.Empty; // e.g., "Spam", "Abuse", etc.
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
using SharpbinV3.Server.Data.Entities;
|
||||||
|
|
||||||
|
namespace SharpbinV3.Server.DTOs.Report
|
||||||
|
{
|
||||||
|
public sealed record ReportQuery
|
||||||
|
{
|
||||||
|
public Guid? ReporterUUID { get; init; }
|
||||||
|
public Guid? UserUUID { get; init; }
|
||||||
|
public int? PastePID { get; init; }
|
||||||
|
public string? PasteId { get; init; }
|
||||||
|
public ReportTargetType? TargetType { get; init; }
|
||||||
|
public ReportType? Type { get; init; }
|
||||||
|
public ReportStatus? Status { get; init; }
|
||||||
|
public int Page { get; init; } = 1;
|
||||||
|
public int PageSize { get; init; } = 20;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
using SharpbinV3.Server.Data.Entities;
|
||||||
|
|
||||||
|
namespace SharpbinV3.Server.DTOs.Report
|
||||||
|
{
|
||||||
|
public class ReportResponseDto
|
||||||
|
{
|
||||||
|
public int? ReportID { get; set; }
|
||||||
|
public ReportType Type { get; set; }
|
||||||
|
public ReportStatus Status { get; set; }
|
||||||
|
public string? Description { get; set; }
|
||||||
|
public long CreatedAt { get; set; }
|
||||||
|
public long? UpdatedAt { get; set; }
|
||||||
|
public Guid ReporterUUID { get; set; }
|
||||||
|
public string? ReporterUsername { get; set; }
|
||||||
|
public string? ReporterDisplayName { get; set; }
|
||||||
|
public ReportTargetType TargetType { get; set; }
|
||||||
|
public string? PasteId { get; set; }
|
||||||
|
public string? PasteTitle { get; set; }
|
||||||
|
public Guid? UserUUID { get; set; }
|
||||||
|
public string? TargetUsername { get; set; }
|
||||||
|
public string? TargetDisplayName { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class ReportOptionsDto
|
||||||
|
{
|
||||||
|
public string[] Types { get; set; } = [];
|
||||||
|
public string[] Statuses { get; set; } = [];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
|
||||||
|
namespace SharpbinV3.Server.DTOs.Report
|
||||||
|
{
|
||||||
|
public class ReportUpdateDto
|
||||||
|
{
|
||||||
|
public string? Status { get; set; }
|
||||||
|
public string? Type { get; set; }
|
||||||
|
[MaxLength(1000)]
|
||||||
|
public string? Description { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
namespace SharpbinV3.Server.DTOs.User
|
||||||
|
{
|
||||||
|
public class UserSimpleDto
|
||||||
|
{
|
||||||
|
public int? UID { get; set; }
|
||||||
|
public Guid UUID { get; set; }
|
||||||
|
public string Username { get; set; } = string.Empty;
|
||||||
|
public string? DisplayName { get; set; }
|
||||||
|
public int[] Roles { get; set; } = [];
|
||||||
|
public int Visibility { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class UserResponseDto : UserSimpleDto
|
||||||
|
{
|
||||||
|
public string? Email { get; set; }
|
||||||
|
public long? LastLogin { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,6 +10,7 @@ namespace SharpbinV3.Server.Data.Entities
|
|||||||
[Index(nameof(UserUUID))]
|
[Index(nameof(UserUUID))]
|
||||||
public class Report
|
public class Report
|
||||||
{
|
{
|
||||||
|
[Key]
|
||||||
public int? ReportID { get; set; }
|
public int? ReportID { get; set; }
|
||||||
|
|
||||||
public ReportType Type { get; set; }
|
public ReportType Type { get; set; }
|
||||||
|
|||||||
@@ -22,13 +22,13 @@ namespace SharpbinV3.Server.Extensions
|
|||||||
|
|
||||||
var claims = context.User.Claims;
|
var claims = context.User.Claims;
|
||||||
|
|
||||||
var uuidClaim = claims.FirstOrDefault(c => c.Type == "UUID")?.Value;
|
var uuidClaim = claims.FirstOrDefault(c => c.Type == "uuid")?.Value;
|
||||||
if (string.IsNullOrEmpty(uuidClaim) || !Guid.TryParse(uuidClaim, out var uuid))
|
if (string.IsNullOrEmpty(uuidClaim) || !Guid.TryParse(uuidClaim, out var uuid))
|
||||||
return null;
|
return null;
|
||||||
|
|
||||||
var username = claims.FirstOrDefault(c => c.Type == "Username")?.Value ?? "";
|
var username = claims.FirstOrDefault(c => c.Type == "username")?.Value ?? "";
|
||||||
var displayName = claims.FirstOrDefault(c => c.Type == "DisplayName")?.Value ?? "";
|
var displayName = claims.FirstOrDefault(c => c.Type == "displayname")?.Value ?? "";
|
||||||
var totpEnabled = claims.FirstOrDefault(c => c.Type == "TOTP_Enabled")?.Value == "True";
|
var totpEnabled = claims.FirstOrDefault(c => c.Type == "totp_enabled")?.Value == "True";
|
||||||
|
|
||||||
var roles = claims
|
var roles = claims
|
||||||
.Where(c => c.Type == ClaimTypes.Role)
|
.Where(c => c.Type == ClaimTypes.Role)
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
using System;
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
using Microsoft.EntityFrameworkCore.Migrations;
|
|
||||||
|
|
||||||
#nullable disable
|
#nullable disable
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.DataProtection;
|
using Microsoft.AspNetCore.DataProtection;
|
||||||
using Microsoft.AspNetCore.RateLimiting;
|
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using Microsoft.IdentityModel.Tokens;
|
using Microsoft.IdentityModel.Tokens;
|
||||||
@@ -13,6 +12,7 @@ using SharpbinV3.Server.Services.Verification;
|
|||||||
using SharpbinV3.Server.Services.Verification.Providers;
|
using SharpbinV3.Server.Services.Verification.Providers;
|
||||||
using SharpbinV3.Server.Settings;
|
using SharpbinV3.Server.Settings;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
using System.Threading.RateLimiting;
|
using System.Threading.RateLimiting;
|
||||||
|
|
||||||
namespace SharpbinV3.Server
|
namespace SharpbinV3.Server
|
||||||
@@ -25,7 +25,12 @@ namespace SharpbinV3.Server
|
|||||||
|
|
||||||
// Add services to the container.
|
// Add services to the container.
|
||||||
|
|
||||||
builder.Services.AddControllers();
|
builder.Services.AddControllers()
|
||||||
|
.AddJsonOptions(options =>
|
||||||
|
{
|
||||||
|
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
|
||||||
|
options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
|
||||||
|
});
|
||||||
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
|
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
|
||||||
builder.Services.AddOpenApi();
|
builder.Services.AddOpenApi();
|
||||||
builder.Services.AddDbContext<AppDbContext>(opt =>
|
builder.Services.AddDbContext<AppDbContext>(opt =>
|
||||||
|
|||||||
@@ -53,10 +53,10 @@ namespace SharpbinV3.Server.Services
|
|||||||
var totpEnabled = await _db.UserTotps.AnyAsync(t => t.UserUUID == user.UUID);
|
var totpEnabled = await _db.UserTotps.AnyAsync(t => t.UserUUID == user.UUID);
|
||||||
var claims = new List<Claim>
|
var claims = new List<Claim>
|
||||||
{
|
{
|
||||||
new("UUID", user.UUID.ToString()),
|
new("uuid", user.UUID.ToString()),
|
||||||
new("Username", user.Username),
|
new("username", user.Username),
|
||||||
new("DisplayName", user.DisplayName ?? ""),
|
new("displayname", user.DisplayName ?? ""),
|
||||||
new("TOTP_Enabled", totpEnabled.ToString()),
|
new("totp_enabled", totpEnabled.ToString()),
|
||||||
new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
|
new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -188,7 +188,7 @@ namespace SharpbinV3.Server.Services
|
|||||||
|
|
||||||
public async Task<User?> GetUserFromHttpContext(HttpContext context)
|
public async Task<User?> GetUserFromHttpContext(HttpContext context)
|
||||||
{
|
{
|
||||||
var uuidClaim = context.User.Claims.FirstOrDefault(c => c.Type == "UUID")?.Value;
|
var uuidClaim = context.User.Claims.FirstOrDefault(c => c.Type == "uuid")?.Value;
|
||||||
if (uuidClaim == null)
|
if (uuidClaim == null)
|
||||||
return null;
|
return null;
|
||||||
var userUUID = Guid.Parse(uuidClaim);
|
var userUUID = Guid.Parse(uuidClaim);
|
||||||
|
|||||||
@@ -1,12 +1,14 @@
|
|||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using SharpbinV3.Server.Data;
|
using SharpbinV3.Server.Data;
|
||||||
using SharpbinV3.Server.Data.Entities;
|
using SharpbinV3.Server.Data.Entities;
|
||||||
|
using SharpbinV3.Server.DTOs.Report;
|
||||||
|
|
||||||
namespace SharpbinV3.Server.Services
|
namespace SharpbinV3.Server.Services
|
||||||
{
|
{
|
||||||
public class ReportService(AppDbContext db)
|
public class ReportService(AppDbContext db)
|
||||||
{
|
{
|
||||||
private readonly AppDbContext _db = db;
|
private readonly AppDbContext _db = db;
|
||||||
|
private sealed record UserInfo(string Username, string? DisplayName);
|
||||||
public async Task<Report> CreateReport(Guid reporterUUID, ReportTargetType targetType, Guid userUUID, ReportType type, string description)
|
public async Task<Report> CreateReport(Guid reporterUUID, ReportTargetType targetType, Guid userUUID, ReportType type, string description)
|
||||||
{
|
{
|
||||||
var report = new Report
|
var report = new Report
|
||||||
@@ -36,22 +38,136 @@ namespace SharpbinV3.Server.Services
|
|||||||
return report;
|
return report;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<List<Report>> GetReports(Guid reporterUUID)
|
private IQueryable<Report> BuildReportQuery(ReportQuery query)
|
||||||
|
{
|
||||||
|
IQueryable<Report> q = _db.Reports;
|
||||||
|
|
||||||
|
if (query.ReporterUUID != null)
|
||||||
|
q = q.Where(r => r.ReporterUUID == query.ReporterUUID);
|
||||||
|
|
||||||
|
if (query.UserUUID != null)
|
||||||
|
q = q.Where(r => r.UserUUID == query.UserUUID);
|
||||||
|
|
||||||
|
if (query.PastePID != null)
|
||||||
|
q = q.Where(r => r.PastePID == query.PastePID);
|
||||||
|
|
||||||
|
if (query.PasteId != null)
|
||||||
|
{
|
||||||
|
q = q.Where(r => _db.Pastes
|
||||||
|
.Where(p => p.ID == query.PasteId)
|
||||||
|
.Select(p => (int?)p.PID)
|
||||||
|
.Contains(r.PastePID));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (query.TargetType != null)
|
||||||
|
q = q.Where(r => r.TargetType == query.TargetType);
|
||||||
|
|
||||||
|
if (query.Type != null)
|
||||||
|
q = q.Where(r => r.Type == query.Type);
|
||||||
|
|
||||||
|
if (query.Status != null)
|
||||||
|
q = q.Where(r => r.Status == query.Status);
|
||||||
|
|
||||||
|
return q;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public async Task<List<ReportResponseDto>> GetPasteReports(ReportQuery query)
|
||||||
|
{
|
||||||
|
query = query with
|
||||||
|
{
|
||||||
|
TargetType = ReportTargetType.Paste,
|
||||||
|
UserUUID = null
|
||||||
|
};
|
||||||
|
|
||||||
|
return await GetReports(query);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<List<ReportResponseDto>> GetUserReports(ReportQuery query)
|
||||||
|
{
|
||||||
|
query = query with
|
||||||
|
{
|
||||||
|
TargetType = ReportTargetType.User,
|
||||||
|
PastePID = null
|
||||||
|
};
|
||||||
|
|
||||||
|
return await GetReports(query);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<List<ReportResponseDto>> GetReports(ReportQuery query)
|
||||||
|
{
|
||||||
|
return await BuildReportQuery(query)
|
||||||
|
.OrderByDescending(r => r.CreatedAt)
|
||||||
|
.Skip((query.Page - 1) * query.PageSize)
|
||||||
|
.Take(query.PageSize)
|
||||||
|
.Select(r => new ReportResponseDto
|
||||||
|
{
|
||||||
|
ReportID = r.ReportID,
|
||||||
|
Type = r.Type,
|
||||||
|
Status = r.Status,
|
||||||
|
Description = r.Description,
|
||||||
|
CreatedAt = r.CreatedAt,
|
||||||
|
UpdatedAt = r.UpdatedAt,
|
||||||
|
ReporterUUID = r.ReporterUUID,
|
||||||
|
ReporterUsername = _db.Users
|
||||||
|
.Where(u => u.UUID == r.ReporterUUID)
|
||||||
|
.Select(u => u.Username)
|
||||||
|
.FirstOrDefault(),
|
||||||
|
ReporterDisplayName = _db.Users
|
||||||
|
.Where(u => u.UUID == r.ReporterUUID)
|
||||||
|
.Select(u => u.DisplayName)
|
||||||
|
.FirstOrDefault(),
|
||||||
|
TargetType = r.TargetType,
|
||||||
|
PasteId = r.Paste != null ? r.Paste.ID : null,
|
||||||
|
PasteTitle = r.Paste != null ? r.Paste.Title : null,
|
||||||
|
UserUUID = r.UserUUID,
|
||||||
|
TargetUsername = r.User != null ? r.User.Username : null,
|
||||||
|
TargetDisplayName = r.User != null ? r.User.DisplayName : null
|
||||||
|
})
|
||||||
|
.ToListAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<(string? Username, string? DisplayName)> GetReporterInfo(Guid reporterUUID)
|
||||||
|
{
|
||||||
|
var info = await _db.Users.AsNoTracking()
|
||||||
|
.Where(u => u.UUID == reporterUUID)
|
||||||
|
.Select(u => new UserInfo(u.Username, u.DisplayName))
|
||||||
|
.FirstOrDefaultAsync();
|
||||||
|
|
||||||
|
return info is null ? (null, null) : (info.Username, info.DisplayName);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public async Task<int> GetReportCount(ReportTargetType targetType)
|
||||||
|
{
|
||||||
|
return await _db.Reports
|
||||||
|
.Where(r => r.TargetType == targetType)
|
||||||
|
.CountAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<int> GetReportCountByReporter(Guid reporterUUID)
|
||||||
{
|
{
|
||||||
return await _db.Reports
|
return await _db.Reports
|
||||||
.Where(r => r.ReporterUUID == reporterUUID)
|
.Where(r => r.ReporterUUID == reporterUUID)
|
||||||
.ToListAsync();
|
.CountAsync();
|
||||||
}
|
}
|
||||||
public async Task<List<Report>> GetReports(ReportTargetType targetType, int? pastePID)
|
|
||||||
|
public async Task<int> GetReportCount()
|
||||||
{
|
{
|
||||||
return await _db.Reports
|
return await _db.Reports
|
||||||
.Where(r => r.TargetType == targetType && r.PastePID == pastePID)
|
.CountAsync();
|
||||||
.ToListAsync();
|
}
|
||||||
|
|
||||||
|
public async Task<int> GetReportCount(ReportQuery query)
|
||||||
|
{
|
||||||
|
return await BuildReportQuery(query).CountAsync();
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<Report?> GetReportByID(int reportID)
|
public async Task<Report?> GetReportByID(int reportID)
|
||||||
{
|
{
|
||||||
return await _db.Reports
|
return await _db.Reports
|
||||||
|
.Include(r => r.User)
|
||||||
|
.Include(r => r.Paste)
|
||||||
.FirstOrDefaultAsync(r => r.ReportID == reportID);
|
.FirstOrDefaultAsync(r => r.ReportID == reportID);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -15,7 +15,7 @@
|
|||||||
"Audience": "SharpbinClient"
|
"Audience": "SharpbinClient"
|
||||||
},
|
},
|
||||||
"PasteSettings": {
|
"PasteSettings": {
|
||||||
"View_HMAC_Secret": "1341551a3f1ae93b98dc690b50dd514ed99da49459fda56d7b8c739d754b6e05cbd05ad820cbd2b77c246289d022e311a2e07df9bacb5a17caea38e125b97667",
|
"View_HMAC_Secret": "e73433ba62483b5a97e2017f3ee784ed672c9888ec385dda24c6d77285764038640b1bcb8cf6a662568f31199c9096e10ed4eb5013b6658763a2ee0594a6278",
|
||||||
"View_HMAC_Internal_API_Key": "1fabd25116c87818550b11448ef609c572dd60b2aac2af9d893eb16b754f6dac"
|
"View_Internal_API_Key": "cccdd42d9f2f648493e402f1da7c855ea798ad510e6bb9ea712dd7bed838e58"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user