mirror of
https://github.com/whoswhip/Sharpbin.git
synced 2026-12-06 02:48:43 +00:00
feat: paste compression & verification enforcement settings; enforce 2fa on admins setting; increase paste validation; anonymous uploads
fix: minor styling issue on main elements; resolve lint issue refactor: remove 2FA badge on user pages; enhance paste creation flow; body background color always neutral-950; improve paste creation paste info (lines, cchars etc) for mobile
This commit is contained in:
@@ -1,16 +1,16 @@
|
|||||||
export function formatBytes(bytes: number, decimals = 2): string {
|
export function formatBytes(bytes: number, decimals = 2): string {
|
||||||
if (bytes === 0) return '0 Bytes';
|
if (bytes === 0) return '0 Bytes';
|
||||||
|
|
||||||
const unit = 1024;
|
const unit = 1024;
|
||||||
const units = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
|
const units = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
|
||||||
|
|
||||||
const exponent = Math.floor(Math.log(bytes) / Math.log(unit));
|
const exponent = Math.floor(Math.log(bytes) / Math.log(unit));
|
||||||
const value = bytes / Math.pow(unit, exponent);
|
const value = bytes / Math.pow(unit, exponent);
|
||||||
|
|
||||||
const unitLabel = value === 1 && exponent === 0 ? 'Byte' : units[exponent];
|
const unitLabel = value === 1 && exponent === 0 ? 'Byte' : units[exponent];
|
||||||
const formattedValue = Number.isInteger(value) ? value : value.toFixed(decimals);
|
const formattedValue = Number.isInteger(value) ? value : value.toFixed(decimals);
|
||||||
|
|
||||||
return `${formattedValue} ${unitLabel}`;
|
return `${formattedValue} ${unitLabel}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function formatNumber(num: number): string {
|
export function formatNumber(num: number): string {
|
||||||
|
|||||||
@@ -38,7 +38,7 @@
|
|||||||
|
|
||||||
<svelte:head>
|
<svelte:head>
|
||||||
<link rel="icon" href={favicon} />
|
<link rel="icon" href={favicon} />
|
||||||
{#if data.options?.cf_turnstile_site_key && (page.url.pathname === '/login' || page.url.pathname === '/register')}
|
{#if data.options?.cf_turnstile_site_key && (page.url.pathname === '/login' || page.url.pathname === '/register' || page.url.pathname === '/')}
|
||||||
<script
|
<script
|
||||||
src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit&onload=turnstileLoaded"
|
src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit&onload=turnstileLoaded"
|
||||||
async
|
async
|
||||||
|
|||||||
@@ -2,9 +2,11 @@ import type { PageServerLoad } from './$types';
|
|||||||
|
|
||||||
export const load: PageServerLoad = async ({ fetch, url }) => {
|
export const load: PageServerLoad = async ({ fetch, url }) => {
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/api/paste/create/options');
|
const optionsRes = await fetch('/api/paste/create/options');
|
||||||
const options = await res.json();
|
const authInfo = await fetch('/api/auth/info');
|
||||||
return { options, url: url.href };
|
const options = await optionsRes.json();
|
||||||
|
const auth = await authInfo.json();
|
||||||
|
return { options, auth, url: url.href };
|
||||||
} catch {
|
} catch {
|
||||||
return { options: null, url: url.href };
|
return { options: null, url: url.href };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,10 +3,12 @@
|
|||||||
import { displayNames } from '$lib/consts';
|
import { displayNames } from '$lib/consts';
|
||||||
import { user } from '$lib/stores/user';
|
import { user } from '$lib/stores/user';
|
||||||
import { getToken } from '$lib/utils/auth';
|
import { getToken } from '$lib/utils/auth';
|
||||||
|
import { onMount } from 'svelte';
|
||||||
import { fly } from 'svelte/transition';
|
import { fly } from 'svelte/transition';
|
||||||
import { encryptAES } from '$lib/utils/encryption';
|
import { encryptAES } from '$lib/utils/encryption';
|
||||||
import { formatBytes } from '$lib/utils/misc';
|
import { formatBytes, formatNumber } from '$lib/utils/misc';
|
||||||
import Dropdown from '$lib/components/Dropdown.svelte';
|
import Dropdown from '$lib/components/Dropdown.svelte';
|
||||||
|
import { SvelteURLSearchParams } from 'svelte/reactivity';
|
||||||
|
|
||||||
export let data: PageData;
|
export let data: PageData;
|
||||||
|
|
||||||
@@ -17,6 +19,32 @@
|
|||||||
let expiresIn: number = 0;
|
let expiresIn: number = 0;
|
||||||
let selectedVisibility = data.options?.visibilities?.[0]?.value;
|
let selectedVisibility = data.options?.visibilities?.[0]?.value;
|
||||||
let password = '';
|
let password = '';
|
||||||
|
let anonymousUpload = false;
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
const render = () => {
|
||||||
|
if (
|
||||||
|
window.turnstile &&
|
||||||
|
data.options?.requiresVerification &&
|
||||||
|
data.auth?.cf_turnstile_site_key
|
||||||
|
) {
|
||||||
|
window.turnstile.render('.cf-turnstile', {
|
||||||
|
sitekey: data.auth.cf_turnstile_site_key,
|
||||||
|
theme: 'dark'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (window.turnstile) {
|
||||||
|
render();
|
||||||
|
} else {
|
||||||
|
window.addEventListener('turnstile:loaded', render, { once: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('turnstile:loaded', render);
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
const syntaxOptions =
|
const syntaxOptions =
|
||||||
data.options?.syntaxes?.map((lang: string) => ({
|
data.options?.syntaxes?.map((lang: string) => ({
|
||||||
@@ -48,12 +76,24 @@
|
|||||||
|
|
||||||
async function handleSubmit(event: Event) {
|
async function handleSubmit(event: Event) {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
const params = new URLSearchParams({
|
const params = new SvelteURLSearchParams({
|
||||||
title: title.trim(),
|
title: title.trim(),
|
||||||
syntax: selectedSyntax,
|
syntax: selectedSyntax,
|
||||||
visibility: selectedVisibility.toString(),
|
visibility: selectedVisibility.toString(),
|
||||||
expiresAt: expiresIn > 0 ? (Date.now() + Number(expiresIn)).toString() : '0'
|
expiresAt: expiresIn > 0 ? (Date.now() + Number(expiresIn)).toString() : '0'
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (
|
||||||
|
data.options?.requiresVerification &&
|
||||||
|
data.auth?.cf_turnstile_site_key &&
|
||||||
|
window.turnstile
|
||||||
|
) {
|
||||||
|
const token = window.turnstile.getResponse();
|
||||||
|
if (token) {
|
||||||
|
params.append('token', token);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let body = content;
|
let body = content;
|
||||||
if (selectedVisibility === 2) {
|
if (selectedVisibility === 2) {
|
||||||
body = await encryptAES(content, password);
|
body = await encryptAES(content, password);
|
||||||
@@ -64,7 +104,7 @@
|
|||||||
headers: { 'Content-Type': 'text/plain' },
|
headers: { 'Content-Type': 'text/plain' },
|
||||||
body
|
body
|
||||||
};
|
};
|
||||||
if ($user) {
|
if ($user && !anonymousUpload) {
|
||||||
const token = getToken();
|
const token = getToken();
|
||||||
if (token) {
|
if (token) {
|
||||||
options.headers = {
|
options.headers = {
|
||||||
@@ -83,10 +123,24 @@
|
|||||||
}
|
}
|
||||||
window.location.href = `/${result.id}`;
|
window.location.href = `/${result.id}`;
|
||||||
} else {
|
} else {
|
||||||
|
if (window.turnstile) {
|
||||||
|
window.turnstile.reset();
|
||||||
|
}
|
||||||
if (response.status === 403) {
|
if (response.status === 403) {
|
||||||
error = 'You are banned from creating new pastes.';
|
error = 'You are banned from creating new pastes.';
|
||||||
} else {
|
} else {
|
||||||
error = 'Failed to create paste. Please try again.';
|
const resData = await response.json();
|
||||||
|
if (resData.errors) {
|
||||||
|
const messages = Object.values(resData.errors).flat();
|
||||||
|
error = messages.join('\n');
|
||||||
|
} else {
|
||||||
|
if (resData.message === 'Verification failed.') {
|
||||||
|
if (window.turnstile) {
|
||||||
|
window.turnstile.reset();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
error = resData.message || 'Registration failed. Please try again.';
|
||||||
|
}
|
||||||
}
|
}
|
||||||
setInterval(() => {
|
setInterval(() => {
|
||||||
error = '';
|
error = '';
|
||||||
@@ -105,7 +159,7 @@
|
|||||||
</svelte:head>
|
</svelte:head>
|
||||||
|
|
||||||
<main
|
<main
|
||||||
class="flex min-h-[calc(100vh-60px)] w-full flex-col items-center justify-center bg-neutral-950 pt-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-7xl rounded border-2 border-neutral-800 bg-neutral-900 p-6">
|
<div class="w-[95%] max-w-7xl rounded border-2 border-neutral-800 bg-neutral-900 p-6">
|
||||||
<h1 class="mb-6 text-center text-4xl font-bold">Create a Paste</h1>
|
<h1 class="mb-6 text-center text-4xl font-bold">Create a Paste</h1>
|
||||||
@@ -138,51 +192,75 @@
|
|||||||
}}
|
}}
|
||||||
></textarea>
|
></textarea>
|
||||||
<div
|
<div
|
||||||
class="mb-4 flex items-center h-8 justify-between rounded-b border border-neutral-700 bg-neutral-800 p-1 pl-2 pr-2 text-sm text-neutral-400 monospace"
|
class="monospace mb-4 flex h-12 items-center justify-between rounded-b border border-neutral-700 bg-neutral-800 p-1 pr-2 pl-2 text-sm text-neutral-400 md:h-8"
|
||||||
>
|
>
|
||||||
<div>
|
<div class="flex flex-col md:flex-row md:gap-2">
|
||||||
{content.split('\n').length} line{content.split('\n').length !== 1 ? 's' : ''}, {content.length}
|
<span>
|
||||||
character{content.length !== 1 ? 's' : ''}
|
{content.split('\n').length} line{content.split('\n').length !== 1 ? 's' : ''}
|
||||||
|
</span>
|
||||||
|
<span class="hidden text-neutral-600 md:block">•</span>
|
||||||
|
<span>{formatNumber(content.length)} char{content.length !== 1 ? 's' : ''}</span>
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-col text-center md:flex-row md:gap-2">
|
||||||
|
<span class="border-b border-neutral-600 md:border-0">
|
||||||
|
{formatBytes(new TextEncoder().encode(content).length)}
|
||||||
|
</span>
|
||||||
|
<span class="hidden md:block">/</span>
|
||||||
|
{formatBytes(data.options?.maxPasteSize ?? 0)}
|
||||||
</div>
|
</div>
|
||||||
{#if data.options?.maxPasteSize}
|
|
||||||
{formatBytes(new TextEncoder().encode(content).length)} / {formatBytes(
|
|
||||||
data.options.maxPasteSize
|
|
||||||
)}
|
|
||||||
{:else}
|
|
||||||
{formatBytes(new TextEncoder().encode(content).length)}
|
|
||||||
{/if}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<Dropdown
|
<div class="grid grid-cols-1 md:grid-cols-3 md:gap-2">
|
||||||
options={syntaxOptions}
|
<Dropdown
|
||||||
bind:value={selectedSyntax}
|
options={syntaxOptions}
|
||||||
placeholder="Select syntax..."
|
bind:value={selectedSyntax}
|
||||||
searchable={true}
|
placeholder="Select syntax..."
|
||||||
/>
|
searchable={true}
|
||||||
<Dropdown
|
/>
|
||||||
options={expiresOptions}
|
<Dropdown
|
||||||
bind:value={expiresIn}
|
options={expiresOptions}
|
||||||
placeholder="Select expiration..."
|
bind:value={expiresIn}
|
||||||
/>
|
placeholder="Select expiration..."
|
||||||
<Dropdown
|
/>
|
||||||
options={visibilityOptions}
|
<Dropdown
|
||||||
bind:value={selectedVisibility}
|
options={visibilityOptions}
|
||||||
placeholder="Select visibility..."
|
bind:value={selectedVisibility}
|
||||||
/>
|
placeholder="Select visibility..."
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
{#if selectedVisibility === 2}
|
{#if selectedVisibility === 2}
|
||||||
<input
|
<input
|
||||||
type="password"
|
type="password"
|
||||||
placeholder="Password for private paste"
|
placeholder="Password for private paste"
|
||||||
class="mb-4 w-full rounded border border-neutral-700 bg-neutral-800 p-2"
|
class="w-full rounded border border-neutral-700 bg-neutral-800 p-2"
|
||||||
spellcheck="false"
|
spellcheck="false"
|
||||||
autocomplete="off"
|
autocomplete="off"
|
||||||
bind:value={password}
|
bind:value={password}
|
||||||
/>
|
/>
|
||||||
{/if}
|
{/if}
|
||||||
|
{#if $user}
|
||||||
|
<label
|
||||||
|
class="flex w-full items-center gap-2 rounded border border-neutral-700 bg-neutral-800 p-2"
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
bind:checked={anonymousUpload}
|
||||||
|
class="h-4 w-4 rounded border-neutral-600 bg-neutral-700 text-neutral-500"
|
||||||
|
/>
|
||||||
|
<span>Upload anonymously</span>
|
||||||
|
</label>
|
||||||
|
{/if}
|
||||||
|
{#if data.options?.requiresVerification && data.auth?.cf_turnstile_site_key}
|
||||||
|
<div
|
||||||
|
class="mt-2 flex w-auto items-center justify-center rounded border border-neutral-700 bg-neutral-800 p-2 pb-1"
|
||||||
|
>
|
||||||
|
<div class="cf-turnstile" data-sitekey={data.auth.cf_turnstile_site_key}></div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
<button
|
<button
|
||||||
type="submit"
|
type="submit"
|
||||||
disabled={$user?.roles && $user.roles.includes(403)}
|
disabled={$user?.roles && $user.roles.includes(403)}
|
||||||
class="w-full cursor-pointer rounded bg-neutral-700 px-4 py-2 font-semibold text-white transition-colors duration-200 hover:bg-neutral-800 active:bg-neutral-900 disabled:cursor-not-allowed disabled:bg-neutral-950/50 disabled:text-neutral-400"
|
class="mt-2 w-full cursor-pointer rounded bg-neutral-700 px-4 py-2 font-semibold text-white transition-colors duration-200 hover:bg-neutral-800 active:bg-neutral-900 disabled:cursor-not-allowed disabled:bg-neutral-950/50 disabled:text-neutral-400"
|
||||||
>Create Paste</button
|
>Create Paste</button
|
||||||
>
|
>
|
||||||
{#if error}
|
{#if error}
|
||||||
|
|||||||
@@ -318,7 +318,7 @@
|
|||||||
</svelte:head>
|
</svelte:head>
|
||||||
|
|
||||||
<main
|
<main
|
||||||
class="flex min-h-[calc(100vh-60px)] w-full flex-col items-center justify-center bg-neutral-950 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
|
<div
|
||||||
class="max-h-[90vh] w-[95%] max-w-7xl rounded border-2 border-neutral-800 bg-neutral-900 p-4"
|
class="max-h-[90vh] w-[95%] max-w-7xl rounded border-2 border-neutral-800 bg-neutral-900 p-4"
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
body {
|
body {
|
||||||
background-color: black;
|
background-color: var(--color-neutral-950);
|
||||||
}
|
}
|
||||||
|
|
||||||
body,
|
body,
|
||||||
|
|||||||
@@ -88,7 +88,7 @@
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<main
|
<main
|
||||||
class="flex min-h-[calc(100vh-60px)] w-full flex-col items-center justify-center bg-neutral-950 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-full max-w-md rounded border-2 border-neutral-800 bg-neutral-900 p-6">
|
<div class="w-full max-w-md rounded border-2 border-neutral-800 bg-neutral-900 p-6">
|
||||||
<h1 class="mb-6 text-center text-3xl font-bold">Login</h1>
|
<h1 class="mb-6 text-center text-3xl font-bold">Login</h1>
|
||||||
|
|||||||
@@ -113,7 +113,7 @@
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<main
|
<main
|
||||||
class="flex min-h-[calc(100vh-60px)] w-full flex-col items-center justify-center bg-neutral-950 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-full max-w-md rounded border-2 border-neutral-800 bg-neutral-900 p-6">
|
<div class="w-full max-w-md rounded border-2 border-neutral-800 bg-neutral-900 p-6">
|
||||||
<h1 class="mb-6 text-center text-3xl font-bold">Register</h1>
|
<h1 class="mb-6 text-center text-3xl font-bold">Register</h1>
|
||||||
|
|||||||
@@ -204,7 +204,7 @@
|
|||||||
</svelte:head>
|
</svelte:head>
|
||||||
|
|
||||||
<main
|
<main
|
||||||
class="flex min-h-[calc(100vh-60px)] w-full flex-col items-center justify-center bg-neutral-950 pt-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="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">
|
||||||
@@ -259,12 +259,6 @@
|
|||||||
{data.user?.uid}
|
{data.user?.uid}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
{#if isOwner}
|
|
||||||
<div class="flex shrink-0 items-center">
|
|
||||||
<ShieldUser class="mr-2 h-6 w-6 text-neutral-400" />
|
|
||||||
<span class="text-neutral-400">2FA {totpEnabled ? 'enabled' : 'disabled'}</span>
|
|
||||||
</div>
|
|
||||||
{/if}
|
|
||||||
{#if isOwner && data.user?.lastLogin}
|
{#if isOwner && data.user?.lastLogin}
|
||||||
<div class="flex shrink-0 items-center">
|
<div class="flex shrink-0 items-center">
|
||||||
<Clock class="mr-2 h-6 w-6 text-neutral-400" />
|
<Clock class="mr-2 h-6 w-6 text-neutral-400" />
|
||||||
@@ -433,9 +427,6 @@
|
|||||||
show={showTotpModal}
|
show={showTotpModal}
|
||||||
mode="totpSetup"
|
mode="totpSetup"
|
||||||
title="Two-Factor Authentication"
|
title="Two-Factor Authentication"
|
||||||
message={totpEnabled
|
|
||||||
? 'Two-factor authentication is currently enabled.'
|
|
||||||
: 'Enable two-factor authentication with an authenticator app.'}
|
|
||||||
error={modalError}
|
error={modalError}
|
||||||
totpActive={totpEnabled}
|
totpActive={totpEnabled}
|
||||||
onConfirm={(value) => handleTotpConfirm(value)}
|
onConfirm={(value) => handleTotpConfirm(value)}
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
{
|
{
|
||||||
[ApiController]
|
[ApiController]
|
||||||
[Route("api/[controller]")]
|
[Route("api/[controller]")]
|
||||||
public class AuthController(UserService userService, AuthService authService, IOptions<AuthSettings> options,
|
public class AuthController(UserService userService, AuthService authService, IOptions<AuthSettings> options,
|
||||||
VerificationService verification, TotpVerificationProvider totp, AppDbContext db) : ControllerBase
|
VerificationService verification, TotpVerificationProvider totp, AppDbContext db) : ControllerBase
|
||||||
{
|
{
|
||||||
private readonly AuthService _authService = authService;
|
private readonly AuthService _authService = authService;
|
||||||
|
|||||||
@@ -5,23 +5,25 @@ using SharpbinV3.Server.Data.Entities;
|
|||||||
using SharpbinV3.Server.DTOs.Paste;
|
using SharpbinV3.Server.DTOs.Paste;
|
||||||
using SharpbinV3.Server.Extensions;
|
using SharpbinV3.Server.Extensions;
|
||||||
using SharpbinV3.Server.Services;
|
using SharpbinV3.Server.Services;
|
||||||
|
using SharpbinV3.Server.Services.Verification;
|
||||||
using SharpbinV3.Server.Settings;
|
using SharpbinV3.Server.Settings;
|
||||||
|
|
||||||
namespace SharpbinV3.Server.Controllers
|
namespace SharpbinV3.Server.Controllers
|
||||||
{
|
{
|
||||||
[Route("api/[controller]")]
|
[Route("api/[controller]")]
|
||||||
[ApiController]
|
[ApiController]
|
||||||
public class PasteController(PasteService pasteService, UserService userService, AuthService authService, IOptions<PasteSettings> options) : ControllerBase
|
public class PasteController(PasteService pasteService, VerificationService verificationService, AuthService authService, IOptions<PasteSettings> options, IOptions<AuthSettings> authSettings) : ControllerBase
|
||||||
{
|
{
|
||||||
private readonly PasteService _pasteService = pasteService;
|
private readonly PasteService _pasteService = pasteService;
|
||||||
private readonly UserService _userService = userService;
|
private readonly VerificationService _verificationService = verificationService;
|
||||||
private readonly AuthService _authService = authService;
|
private readonly AuthService _authService = authService;
|
||||||
private readonly PasteSettings _pasteSettings = options.Value;
|
private readonly PasteSettings _pasteSettings = options.Value;
|
||||||
|
private readonly AuthSettings _authSettings = authSettings.Value;
|
||||||
|
|
||||||
[HttpPost]
|
[HttpPost]
|
||||||
[Route("create")]
|
[Route("create")]
|
||||||
[Authorize(Policy = "NotBanned")]
|
[Authorize(Policy = "NotBanned")]
|
||||||
public async Task<IActionResult> CreatePaste(string title = "", string syntax = "plaintext", int visibility = 0, long expiresAt = 0)
|
public async Task<IActionResult> CreatePaste(string title = "", string syntax = "plaintext", int visibility = 0, long expiresAt = 0, string? token = null)
|
||||||
{
|
{
|
||||||
if (!await _pasteService.ValidateExpiresAt(expiresAt))
|
if (!await _pasteService.ValidateExpiresAt(expiresAt))
|
||||||
return BadRequest(new { message = "Invalid expiration time." });
|
return BadRequest(new { message = "Invalid expiration time." });
|
||||||
@@ -33,10 +35,20 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
return BadRequest(new { message = $"Invalid title. Must be less than {_pasteSettings.MaxTitleLength} characters." });
|
return BadRequest(new { message = $"Invalid title. Must be less than {_pasteSettings.MaxTitleLength} characters." });
|
||||||
|
|
||||||
string content = await new StreamReader(Request.Body).ReadToEndAsync();
|
string content = await new StreamReader(Request.Body).ReadToEndAsync();
|
||||||
|
if (content.Length == 0)
|
||||||
|
return BadRequest(new { message = "Paste content cannot be empty." });
|
||||||
if (System.Text.Encoding.UTF8.GetByteCount(content) > _pasteSettings.MaxPasteSizeInBytes)
|
if (System.Text.Encoding.UTF8.GetByteCount(content) > _pasteSettings.MaxPasteSizeInBytes)
|
||||||
return BadRequest(new { message = $"Paste size exceeds the maximum allowed size of {_pasteSettings.MaxPasteSizeInBytes} bytes." });
|
return BadRequest(new { message = $"Paste size exceeds the maximum allowed size of {_pasteSettings.MaxPasteSizeInBytes} bytes." });
|
||||||
|
|
||||||
|
if (_pasteSettings.RequiresVerfication && !await _verificationService.VerifyAsync(new VerificationContext
|
||||||
|
{
|
||||||
|
Token = token,
|
||||||
|
Ip = HttpContext.GetRequestIP()
|
||||||
|
}))
|
||||||
|
return BadRequest(new { message = "Verification failed." });
|
||||||
|
|
||||||
var user = await _authService.GetUserFromHttpContext(HttpContext);
|
var user = await _authService.GetUserFromHttpContext(HttpContext);
|
||||||
Paste paste = await _pasteService.Create(user, content, title, syntax, visibility, expiresAt);
|
Paste paste = await _pasteService.Create(user, content, title, syntax, visibility, expiresAt, _pasteSettings.EnablePasteCompression);
|
||||||
return Ok(new
|
return Ok(new
|
||||||
{
|
{
|
||||||
paste.ID,
|
paste.ID,
|
||||||
@@ -102,11 +114,16 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
if (content == null || id == null) return NotFound();
|
if (content == null || id == null) return NotFound();
|
||||||
var paste = await _pasteService.Get(id);
|
var paste = await _pasteService.Get(id);
|
||||||
if (paste == null) return NotFound();
|
if (paste == null) return NotFound();
|
||||||
|
|
||||||
var user = HttpContext.GetJwtUser();
|
var user = HttpContext.GetJwtUser();
|
||||||
if (user == null) return Forbid();
|
if (user == null) return Forbid();
|
||||||
|
|
||||||
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
|
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
|
||||||
if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
|
if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
|
||||||
return Forbid();
|
return Forbid();
|
||||||
|
if (user.Roles.Contains(255) && !user.TotpEnabled && _authSettings.Admins_Require_2FA)
|
||||||
|
return Forbid();
|
||||||
|
|
||||||
bool result = await _pasteService.EditText(paste, content);
|
bool result = await _pasteService.EditText(paste, content);
|
||||||
if (!result) return NotFound();
|
if (!result) return NotFound();
|
||||||
return Ok(new { message = "Paste edited successfully." });
|
return Ok(new { message = "Paste edited successfully." });
|
||||||
@@ -119,11 +136,16 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
{
|
{
|
||||||
var paste = await _pasteService.Get(id);
|
var paste = await _pasteService.Get(id);
|
||||||
if (paste == null) return NotFound();
|
if (paste == null) return NotFound();
|
||||||
|
|
||||||
var user = HttpContext.GetJwtUser();
|
var user = HttpContext.GetJwtUser();
|
||||||
if (user == null) return Forbid();
|
if (user == null) return Forbid();
|
||||||
|
|
||||||
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
|
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
|
||||||
|
|
||||||
if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
|
if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
|
||||||
return Forbid();
|
return Forbid();
|
||||||
|
if (user.Roles.Contains(255) && !user.TotpEnabled && _authSettings.Admins_Require_2FA)
|
||||||
|
return Forbid();
|
||||||
if (request.Title != null)
|
if (request.Title != null)
|
||||||
paste.Title = request.Title;
|
paste.Title = request.Title;
|
||||||
if (request.Syntax != null)
|
if (request.Syntax != null)
|
||||||
@@ -168,11 +190,16 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
{
|
{
|
||||||
var paste = await _pasteService.Get(id);
|
var paste = await _pasteService.Get(id);
|
||||||
if (paste == null) return NotFound();
|
if (paste == null) return NotFound();
|
||||||
|
|
||||||
var user = HttpContext.GetJwtUser();
|
var user = HttpContext.GetJwtUser();
|
||||||
if (user == null) return Forbid();
|
if (user == null) return Forbid();
|
||||||
|
|
||||||
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
|
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
|
||||||
if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
|
if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
|
||||||
return Forbid();
|
return Forbid();
|
||||||
|
if (user.Roles.Contains(255) && !user.TotpEnabled && _authSettings.Admins_Require_2FA)
|
||||||
|
return Forbid();
|
||||||
|
|
||||||
bool result = await _pasteService.Delete(paste);
|
bool result = await _pasteService.Delete(paste);
|
||||||
if (!result) return NotFound();
|
if (!result) return NotFound();
|
||||||
return Ok(new { message = "Paste deleted successfully." });
|
return Ok(new { message = "Paste deleted successfully." });
|
||||||
@@ -192,7 +219,8 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
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
|
||||||
};
|
};
|
||||||
return Ok(options);
|
return Ok(options);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
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;
|
||||||
@@ -9,18 +10,19 @@ using SharpbinV3.Server.Extensions;
|
|||||||
using SharpbinV3.Server.Services;
|
using SharpbinV3.Server.Services;
|
||||||
using SharpbinV3.Server.Services.Verification;
|
using SharpbinV3.Server.Services.Verification;
|
||||||
using SharpbinV3.Server.Services.Verification.Providers;
|
using SharpbinV3.Server.Services.Verification.Providers;
|
||||||
|
using SharpbinV3.Server.Settings;
|
||||||
|
|
||||||
namespace SharpbinV3.Server.Controllers
|
namespace SharpbinV3.Server.Controllers
|
||||||
{
|
{
|
||||||
[ApiController]
|
[ApiController]
|
||||||
[Route("api/[controller]")]
|
[Route("api/[controller]")]
|
||||||
public class UserController(UserService userService, AppDbContext db, AuthService authService, TotpVerificationProvider totp, VerificationService verificationService) : ControllerBase
|
public class UserController(UserService userService, AppDbContext db, TotpVerificationProvider totp, VerificationService verificationService, IOptions<AuthSettings> authSettings) : ControllerBase
|
||||||
{
|
{
|
||||||
private readonly UserService _userService = userService;
|
private readonly UserService _userService = userService;
|
||||||
private readonly AppDbContext _db = db;
|
private readonly AppDbContext _db = db;
|
||||||
private readonly AuthService _authService = authService;
|
|
||||||
private readonly TotpVerificationProvider _totp = totp;
|
private readonly TotpVerificationProvider _totp = totp;
|
||||||
private readonly VerificationService _verificationService = verificationService;
|
private readonly VerificationService _verificationService = verificationService;
|
||||||
|
private readonly AuthSettings _authSettings = authSettings.Value;
|
||||||
|
|
||||||
[HttpGet("{username}")]
|
[HttpGet("{username}")]
|
||||||
public async Task<IActionResult> GetByUsername(string username, [FromQuery] int page = 1)
|
public async Task<IActionResult> GetByUsername(string username, [FromQuery] int page = 1)
|
||||||
@@ -63,6 +65,8 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
return Forbid();
|
return Forbid();
|
||||||
if (user.Roles.Contains(255) && !jwtUser.Roles.Contains(255))
|
if (user.Roles.Contains(255) && !jwtUser.Roles.Contains(255))
|
||||||
return Forbid();
|
return Forbid();
|
||||||
|
if (jwtUser.Roles.Contains(255) && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA)
|
||||||
|
return Forbid();
|
||||||
|
|
||||||
user.DisplayName = updatedUser.DisplayName ?? user.DisplayName;
|
user.DisplayName = updatedUser.DisplayName ?? user.DisplayName;
|
||||||
if (jwtUser.Roles.Any(r => r == 255) || user.UUID == jwtUser.UUID) // only admins or self
|
if (jwtUser.Roles.Any(r => r == 255) || user.UUID == jwtUser.UUID) // only admins or self
|
||||||
@@ -100,6 +104,8 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
if (user == null) return Forbid();
|
if (user == null) return Forbid();
|
||||||
if (!jwtUser.Roles.Any(r => r == 255) && user.UUID != jwtUser.UUID)
|
if (!jwtUser.Roles.Any(r => r == 255) && user.UUID != jwtUser.UUID)
|
||||||
return Forbid();
|
return Forbid();
|
||||||
|
if (jwtUser.Roles.Contains(255) && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA)
|
||||||
|
return Forbid();
|
||||||
|
|
||||||
if (jwtUser.TotpEnabled)
|
if (jwtUser.TotpEnabled)
|
||||||
{
|
{
|
||||||
@@ -123,7 +129,7 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
return Unauthorized(new { message = "Invalid verification token." });
|
return Unauthorized(new { message = "Invalid verification token." });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
_db.Users.Remove(user);
|
_db.Users.Remove(user);
|
||||||
await _db.SaveChangesAsync();
|
await _db.SaveChangesAsync();
|
||||||
return Ok(new { message = "User deleted successfully." });
|
return Ok(new { message = "User deleted successfully." });
|
||||||
|
|||||||
@@ -13,9 +13,12 @@ namespace SharpbinV3.Server.Services
|
|||||||
private readonly ICompressionService _cs = cs;
|
private readonly ICompressionService _cs = cs;
|
||||||
private readonly PasteSettings _pasteSettings = options.Value;
|
private readonly PasteSettings _pasteSettings = options.Value;
|
||||||
|
|
||||||
public async Task<Paste> Create(User? author, string content, string title, string syntax, int visibility, long expiresAt)
|
public async Task<Paste> Create(User? author, string content, string title, string syntax, int visibility, long expiresAt, bool shouldCompress)
|
||||||
{
|
{
|
||||||
var compressedData = _cs.Compress(content);
|
var data = Encoding.UTF8.GetBytes(content);
|
||||||
|
if (shouldCompress)
|
||||||
|
data = _cs.Compress(content);
|
||||||
|
|
||||||
var paste = new Paste
|
var paste = new Paste
|
||||||
{
|
{
|
||||||
UUID = Guid.CreateVersion7(),
|
UUID = Guid.CreateVersion7(),
|
||||||
@@ -23,10 +26,10 @@ namespace SharpbinV3.Server.Services
|
|||||||
Title = title,
|
Title = title,
|
||||||
AuthorUUID = author?.UUID,
|
AuthorUUID = author?.UUID,
|
||||||
User = author,
|
User = author,
|
||||||
Content = compressedData,
|
Content = data,
|
||||||
Size = compressedData.Length,
|
Size = data.Length,
|
||||||
TrueSize = Encoding.UTF8.GetByteCount(content),
|
TrueSize = Encoding.UTF8.GetByteCount(content),
|
||||||
IsCompressed = compressedData.Length < Encoding.UTF8.GetByteCount(content),
|
IsCompressed = data.Length < Encoding.UTF8.GetByteCount(content),
|
||||||
Syntax = syntax,
|
Syntax = syntax,
|
||||||
Visibility = visibility,
|
Visibility = visibility,
|
||||||
ExpiresAt = expiresAt,
|
ExpiresAt = expiresAt,
|
||||||
|
|||||||
@@ -6,5 +6,6 @@
|
|||||||
public string CF_Turnstile_SecretKey { get; set; } = string.Empty;
|
public string CF_Turnstile_SecretKey { get; set; } = string.Empty;
|
||||||
public bool Registration_Enabled { get; set; } = true;
|
public bool Registration_Enabled { get; set; } = true;
|
||||||
public bool First_User_Admin { get; set; } = true;
|
public bool First_User_Admin { get; set; } = true;
|
||||||
|
public bool Admins_Require_2FA { get; set; } = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
{
|
{
|
||||||
public class JWTSettings
|
public class JWTSettings
|
||||||
{
|
{
|
||||||
public string Secret { get; set; } = Utilities.GenerateRandomString(64);
|
public string Secret { get; set; } = string.Empty;
|
||||||
public string Issuer { get; set; } = "SharpbinApi";
|
public string Issuer { get; set; } = "SharpbinApi";
|
||||||
public string Audience { get; set; } = "SharpbinClient";
|
public string Audience { get; set; } = "SharpbinClient";
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,5 +5,7 @@
|
|||||||
public string[] ValidSyntaxLanguages { get; set; } = [];
|
public string[] ValidSyntaxLanguages { get; set; } = [];
|
||||||
public int MaxTitleLength { get; set; } = 500;
|
public int MaxTitleLength { get; set; } = 500;
|
||||||
public int MaxPasteSizeInBytes { get; set; } = 1_048_576; // 1 MB
|
public int MaxPasteSizeInBytes { get; set; } = 1_048_576; // 1 MB
|
||||||
|
public bool EnablePasteCompression { get; set; } = true;
|
||||||
|
public bool RequiresVerfication { get; set; } = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user