Compare commits

...
16 Commits
Author SHA1 Message Date
whoswhip 012690f507 chore: bump version and generate change log 2026-02-14 18:36:17 -05:00
whoswhip 5017e73bb5 fix(backend): use GenerateSecureRandomString for api-keys, paste ids, and refresh tokens 2026-02-14 18:31:40 -05:00
whoswhip 809b513e7a feat(backend:utilities): implement GenerateSecureRandomString function that uses RandomNumberGenerator 2026-02-14 18:30:58 -05:00
whoswhip 3374eadb56 feat(backend:authentication): implement API key authentication scheme and update authorization policies 2026-02-14 05:05:33 -05:00
whoswhip 7d09870ad2 fix(frontend:user): resolve lint errors 2026-02-13 22:08:00 -05:00
whoswhip fd1cb3998c style: format via prettier 2026-02-13 21:59:33 -05:00
whoswhip 3dc8070efe feat(frontend:api-keys): display the count of API keys in the header and adjust empty state condition 2026-02-13 21:58:31 -05:00
whoswhip 78f4ae181e fix(frontend:api-keys): add flag to track successful API key fetch
this prevents the api from being spammed when the api keys have been successfully fetched but there are no keys
2026-02-13 21:12:13 -05:00
whoswhip ee45deb439 feat(frontend:api-keys): implement API key management features including creation, deletion, and fetching
this also fixed a few layout issues and lint issues
2026-02-13 21:05:48 -05:00
whoswhip 3b2801a655 feat(frontend:modal): decrease modal background opacity and blur 2026-02-13 20:37:49 -05:00
whoswhip cac34423d9 feat(frontend:stats): enhance tooltip for total storage used to show uncompressed size 2026-02-13 18:49:31 -05:00
whoswhip 5052bbdb13 feat(frontend:user): improve UX; move user settings to settings tab 2026-02-13 18:11:55 -05:00
whoswhip 0283d987d0 docs: api-key hmac secret; show default in :**value**: format instead of the description 2026-02-13 02:45:24 -05:00
whoswhip ff706d8777 feat(frontend): improve user page UX 2026-02-13 02:35:05 -05:00
whoswhip 53d0f33ff0 feat(backend): implement api keys; rename token -> verificationToken in paste creation api
api keys can bypass authentication and captchas/verification
2026-02-13 01:47:50 -05:00
whoswhip db363f0211 feat: add dotnet-ef tool configuration to dotnet-tools.json 2026-02-13 01:45:28 -05:00
33 changed files with 1757 additions and 350 deletions
+25
View File
@@ -1,3 +1,28 @@
## [3.0.4](https://github.com/whoswhip/Sharpbin/compare/v3.0.3...v3.0.4) (2026-02-14)
### Bug Fixes
* **backend:** use GenerateSecureRandomString for api-keys, paste ids, and refresh tokens ([5017e73](https://github.com/whoswhip/Sharpbin/commit/5017e73bb54e626d4dc060fd553c972663eec45f))
* **frontend:api-keys:** add flag to track successful API key fetch ([78f4ae1](https://github.com/whoswhip/Sharpbin/commit/78f4ae181eb18a98ed9964d8e651d84319fa8d2c))
* **frontend:user:** resolve lint errors ([7d09870](https://github.com/whoswhip/Sharpbin/commit/7d09870ad25472ff17a1acc22d5724e199f2c931))
### Features
* add dotnet-ef tool configuration to dotnet-tools.json ([db363f0](https://github.com/whoswhip/Sharpbin/commit/db363f0211972a06b622770ca522d3ef0bba12c8))
* **backend:authentication:** implement API key authentication scheme and update authorization policies ([3374ead](https://github.com/whoswhip/Sharpbin/commit/3374eadb5654fa349a636c4a41a53df1ddf2edfe))
* **backend:utilities:** implement GenerateSecureRandomString function that uses RandomNumberGenerator ([809b513](https://github.com/whoswhip/Sharpbin/commit/809b513e7a3f5a4f7faf64b02d9ed83e81c540b8))
* **backend:** implement api keys; rename token -> verificationToken in paste creation api ([53d0f33](https://github.com/whoswhip/Sharpbin/commit/53d0f33ff026d6e5a188d80585e6a3bb633d9fa8))
* **frontend:api-keys:** display the count of API keys in the header and adjust empty state condition ([3dc8070](https://github.com/whoswhip/Sharpbin/commit/3dc8070efeb19538c4ff120d2a681c4167c716f3))
* **frontend:api-keys:** implement API key management features including creation, deletion, and fetching ([ee45deb](https://github.com/whoswhip/Sharpbin/commit/ee45deb43937cbf3996c3c379461110a484bd086))
* **frontend:modal:** decrease modal background opacity and blur ([3b2801a](https://github.com/whoswhip/Sharpbin/commit/3b2801a65509d3a894c701f03028b2cd4599b456))
* **frontend:stats:** enhance tooltip for total storage used to show uncompressed size ([cac3442](https://github.com/whoswhip/Sharpbin/commit/cac34423d99d1228f426be903da53bafca5f50e7))
* **frontend:user:** improve UX; move user settings to settings tab ([5052bbd](https://github.com/whoswhip/Sharpbin/commit/5052bbdb135dc2df08db94874de5bf2bf738364c))
* **frontend:** improve user page UX ([ff706d8](https://github.com/whoswhip/Sharpbin/commit/ff706d877742317cb8f4ccf72ba5f0791a6d2b88))
## [3.0.3](https://github.com/whoswhip/Sharpbin/compare/v3.0.2...v3.0.3) (2026-02-10) ## [3.0.3](https://github.com/whoswhip/Sharpbin/compare/v3.0.2...v3.0.3) (2026-02-10)
+5 -5
View File
@@ -50,16 +50,16 @@ You can configure Sharpbin using environment variables or `appsettings.json`. Wh
- `JwtSettings__Secret`: A secure string used for signing JWT tokens. - `JwtSettings__Secret`: A secure string used for signing JWT tokens.
- `AuthSettings__CF_Turnstile_SecretKey`: Your Cloudflare Turnstile secret key. - `AuthSettings__CF_Turnstile_SecretKey`: Your Cloudflare Turnstile secret key.
- `AuthSettings__CF_Turnstile_SiteKey`: Your Cloudflare Turnstile site key. - `AuthSettings__CF_Turnstile_SiteKey`: Your Cloudflare Turnstile site key.
- `AuthSettings__Registration_Enabled`: Set to `true` by default, enables/disables registration. - `AuthSettings__Registration_Enabled`:**true**: Enables/disables registration.
- `AuthSettings__First_User_Admin`: Gives the first user the admin role, it is recommended to disable this after use. - `AuthSettings__First_User_Admin`: Gives the first user the admin role, it is recommended to disable this after use.
- `AuthSettings__Admins_Require_2FA`: Enforces Admins to have 2FA when trying to do certain actions. - `AuthSettings__Admins_Require_2FA`: Enforces Admins to have 2FA when trying to do certain actions.
- `AuthSettings__API_Key_HMAC_Secret`: Recommended to securely hash API keys, but is not required.
- `PasteSettings__MaxTitleLength`: Max title length in characters. - `PasteSettings__MaxTitleLength`: Max title length in characters.
- `PasteSettings__MaxPasteSizeInBytes`: Max Paste Size set in bytes, the default is `1_048_576` (1MB) - `PasteSettings__MaxPasteSizeInBytes`:**1_048_576** (1MB): Max Paste Size set in bytes.
- `PasteSettings__EnablePasteCompression`: Enables/Disables server-side paste compression, `true` by default. - `PasteSettings__EnablePasteCompression`:**true**: Enables/Disables server-side paste compression.
- `PasteSettings__RequiresVerification`: Enables/Disables CAPTCHA verification when creating pastes, `true` by default. - `PasteSettings__RequiresVerification`:**true**: Enables/Disables CAPTCHA verification when creating pastes.
- `PasteSettings__View_HMAC_Secret`: Required to securely hash viewer identifiers - `PasteSettings__View_HMAC_Secret`: Required to securely hash viewer identifiers
- `PasteSettings__View_Internal_API_Key`: Enforces views to be counted/recorded only by the frontend, if set it needs to be the same for both backend and frontend. - `PasteSettings__View_Internal_API_Key`: Enforces views to be counted/recorded only by the frontend, if set it needs to be the same for both backend and frontend.
- `ASPNETCORE_ENVIRONMENT`: Set to `Production` or `Development`.
#### Frontend (SharpbinV3.Client) #### Frontend (SharpbinV3.Client)
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "sharpbinv3.client", "name": "sharpbinv3.client",
"version": "3.0.3", "version": "3.0.4",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "sharpbinv3.client", "name": "sharpbinv3.client",
"version": "3.0.3", "version": "3.0.4",
"dependencies": { "dependencies": {
"@lucide/svelte": "^0.562.0", "@lucide/svelte": "^0.562.0",
"@sveltejs/adapter-node": "^5.4.0", "@sveltejs/adapter-node": "^5.4.0",
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "sharpbinv3.client", "name": "sharpbinv3.client",
"private": true, "private": true,
"version": "3.0.3", "version": "3.0.4",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite dev", "dev": "vite dev",
@@ -402,10 +402,10 @@
</script> </script>
{#if show} {#if show}
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm"> <div class="fixed inset-0 z-50 flex items-center justify-center bg-black/20 backdrop-blur-xs">
<form <form
on:submit|preventDefault={handleSubmit} on:submit|preventDefault={handleSubmit}
class="w-full max-w-md rounded bg-neutral-900 p-6" class="w-full max-w-md rounded border border-neutral-800 bg-neutral-900 p-6"
> >
<h2 class="mb-4 text-xl font-semibold text-white"> <h2 class="mb-4 text-xl font-semibold text-white">
{displayTitle} {displayTitle}
+3 -3
View File
@@ -132,9 +132,9 @@
data.auth?.cf_turnstile_site_key && data.auth?.cf_turnstile_site_key &&
window.turnstile window.turnstile
) { ) {
const token = window.turnstile.getResponse(); const verificationToken = window.turnstile.getResponse();
if (token) { if (verificationToken) {
params.append('token', token); params.append('verificationToken', verificationToken);
} }
} }
@@ -74,7 +74,10 @@
<p class="text-sm text-neutral-400">Total Storage Used</p> <p class="text-sm text-neutral-400">Total Storage Used</p>
<p <p
class="text-2xl font-bold" class="text-2xl font-bold"
use:tooltip={[formatBytes(stats.pastes.trueTotalSizeInBytes), true]} use:tooltip={[
`${stats.pastes.trueTotalSizeInBytes != stats.pastes.totalSizeInBytes ? `Uncompressed Size: ${formatBytes(stats.pastes.trueTotalSizeInBytes)}` : ''}`,
true
]}
> >
{formatBytes(stats.pastes.totalSizeInBytes)} {formatBytes(stats.pastes.totalSizeInBytes)}
</p> </p>
@@ -1,6 +1,7 @@
<script lang="ts"> <script lang="ts">
import { resolve } from '$app/paths'; import { resolve } from '$app/paths';
import { goto } from '$app/navigation'; import { goto, afterNavigate } from '$app/navigation';
import { page } from '$app/state';
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 {
@@ -8,13 +9,17 @@
CalendarDays, CalendarDays,
ShieldUser, ShieldUser,
Ban, Ban,
File,
AtSign, AtSign,
Pencil, Pencil,
Trash2, Trash2,
Clock, Clock,
Hash, Hash,
Flag Flag,
LoaderCircle,
Check,
X,
Plus,
Copy
} from '@lucide/svelte'; } from '@lucide/svelte';
import { import {
extractDateFromUUIDv7, extractDateFromUUIDv7,
@@ -30,6 +35,7 @@
import { onMount } from 'svelte'; import { onMount } from 'svelte';
import Paste from '$lib/components/Paste.svelte'; import Paste from '$lib/components/Paste.svelte';
import { reportStatusLabels, reportTargetLabels, reportTypeLabels } from '$lib/types/report'; import { reportStatusLabels, reportTargetLabels, reportTypeLabels } from '$lib/types/report';
import { fade } from 'svelte/transition';
export let data: PageData; export let data: PageData;
@@ -47,12 +53,75 @@
let totpEnabled = false; let totpEnabled = false;
let now = new Date(); let now = new Date();
let interval: ReturnType<typeof setInterval> | null = null; let interval: ReturnType<typeof setInterval> | null = null;
let isEditingDisplayName = false;
let editDisplayNameValue = '';
let apiKeys: { uuid: string; name: string; createdAt: string; lastUsedAt: string | null }[] = [];
let successfullyFetchedApiKeys = false;
let newApiKeyName = '';
let newApiKeyValue = '';
let isCreatingApiKey = false;
let apiKeyError = '';
let copiedApiKey = false;
$: 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; $: reportsSubmitted = data.reportsSubmitted;
$: reportsTarget = data.reportsTarget; $: reportsTarget = data.reportsTarget;
let activeTab: 'pastes' | 'reportsSubmitted' | 'reportsTarget' | 'settings' = isOwner
? 'settings'
: 'pastes';
async function updateTab(newPageTab: typeof activeTab) {
if (activeTab === newPageTab) return;
activeTab = newPageTab;
const url = new URL(page.url);
url.searchParams.set('tab', newPageTab);
// @ts-expect-error
// eslint-disable-next-line svelte/no-navigation-without-resolve
await goto(resolve(url.pathname) + url.search, {
replaceState: true,
noScroll: true,
keepFocus: true,
invalidateAll: false
});
if (newPageTab === 'settings' && isOwner && apiKeys.length === 0) {
await fetchApiKeys();
}
}
$: {
const tab = page.url.searchParams.get('tab');
switch (tab) {
case 'pastes':
activeTab = 'pastes';
break;
case 'reportsSubmitted':
if (reportsSubmitted) activeTab = 'reportsSubmitted';
else activeTab = 'pastes';
break;
case 'reportsTarget':
if (reportsTarget) activeTab = 'reportsTarget';
else activeTab = 'pastes';
break;
case 'settings':
if (isOwner || $user?.roles?.some((r) => r === 255 || r === 1)) {
activeTab = 'settings';
} else activeTab = 'pastes';
break;
default:
if (isOwner) {
activeTab = 'settings';
} else {
activeTab = 'pastes';
}
}
}
const roleOptions = [ const roleOptions = [
{ label: 'Member', value: 0 }, { label: 'Member', value: 0 },
{ label: 'Moderator', value: 1 }, { label: 'Moderator', value: 1 },
@@ -185,19 +254,112 @@
modalError = ''; modalError = '';
} }
async function openEditDisplayName() { async function saveDisplayName() {
const value = String( const value = editDisplayNameValue.trim();
await openModal<string>({
mode: 'prompt',
title: 'Edit Display Name',
maxInputLength: 26,
placeholder: 'New Display Name',
error: modalError,
cancelValue: ''
})
).trim();
if (!value) return; if (!value) return;
await handleUserUpdate(value); await handleUserUpdate(value);
isEditingDisplayName = false;
}
function startEditDisplayName() {
editDisplayNameValue = data.user?.displayName || data.user?.username || '';
isEditingDisplayName = true;
}
function cancelEditDisplayName() {
isEditingDisplayName = false;
editDisplayNameValue = '';
}
async function fetchApiKeys() {
const token = getToken();
if (!token) return;
if (apiKeys.length > 0) return;
if (successfullyFetchedApiKeys) return;
loading = true;
try {
const res = await fetch('/api/auth/apikey/list', {
headers: { Authorization: `Bearer ${token}` }
});
if (res.ok) {
const json = await res.json();
apiKeys = Array.isArray(json.apiKeys) ? json.apiKeys : [];
successfullyFetchedApiKeys = json.successfullyFetchedApiKeys ?? true;
}
} catch (e) {
console.error('Failed to fetch API keys', e);
} finally {
loading = false;
}
}
async function createApiKey() {
if (!newApiKeyName.trim()) return;
loading = true;
apiKeyError = '';
const token = getToken();
try {
const res = await fetch('/api/auth/apikey/create', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
},
body: JSON.stringify({ name: newApiKeyName.trim() })
});
const json = await res.json();
if (res.ok) {
newApiKeyValue = json.apiKey.key;
apiKeys = [
...apiKeys,
{
uuid: json.apiKey.uuid,
name: json.apiKey.name,
createdAt: json.apiKey.createdAt,
lastUsedAt: null
}
];
newApiKeyName = '';
isCreatingApiKey = false;
} else {
apiKeyError = json.message || 'Failed to create API key';
}
} catch {
apiKeyError = 'Network error';
} finally {
loading = false;
}
}
async function deleteApiKey(uuid: string) {
const ok = await openModal<boolean>({
mode: 'confirm',
title: 'Delete API Key',
message: 'Are you sure you want to delete this API key? This action cannot be undone.',
confirmButtonText: 'Delete',
cancelValue: false
});
if (!ok) return;
loading = true;
apiKeyError = '';
const token = getToken();
try {
const res = await fetch(`/api/auth/apikey/${uuid}`, {
method: 'DELETE',
headers: { Authorization: `Bearer ${token}` }
});
if (res.ok) {
apiKeys = apiKeys.filter((k) => k.uuid !== uuid);
} else {
const json = await res.json();
apiKeyError = json.message || 'Failed to delete API key';
}
} catch {
apiKeyError = 'Network error';
} finally {
loading = false;
}
} }
async function openEditRoles() { async function openEditRoles() {
@@ -240,11 +402,24 @@
interval = setInterval(() => { interval = setInterval(() => {
now = new Date(); now = new Date();
}, 1000); }, 1000);
const tab = page.url.searchParams.get('tab');
if ((tab === 'settings' || !tab) && isOwner) {
fetchApiKeys();
}
return () => { return () => {
if (interval) clearInterval(interval); if (interval) clearInterval(interval);
}; };
}); });
afterNavigate(() => {
const tab = page.url.searchParams.get('tab');
if ((tab === 'settings' || !tab) && isOwner && apiKeys.length === 0) {
fetchApiKeys();
}
});
$: reportSiteKey = $: reportSiteKey =
(data as unknown as { authOptions?: { cf_turnstile_site_key?: string | null } }).authOptions (data as unknown as { authOptions?: { cf_turnstile_site_key?: string | null } }).authOptions
?.cf_turnstile_site_key ?? null; ?.cf_turnstile_site_key ?? null;
@@ -317,33 +492,7 @@
Joined {extractDateFromUUIDv7(data.user?.uuid)?.toLocaleDateString() ?? 'Unknown'} Joined {extractDateFromUUIDv7(data.user?.uuid)?.toLocaleDateString() ?? 'Unknown'}
</span> </span>
</div> </div>
<div class="flex shrink-0 items-center">
<File class="mr-2 h-6 w-6 text-neutral-400" />
<span class="text-neutral-400"
>{pagination.totalCount} paste{pagination.totalCount !== 1 ? 's' : ''}</span
>
</div>
{#if reportsSubmitted}
<div class="flex shrink-0 items-center">
<Flag class="mr-2 h-6 w-6 text-neutral-400" />
<span class="text-neutral-400"
>{reportsSubmitted.pagination.totalCount} submitted report{reportsSubmitted.pagination
.totalCount !== 1
? 's'
: ''}</span
>
</div>
{/if}
{#if reportsTarget}
<div class="flex shrink-0 items-center">
<Flag class="mr-2 h-6 w-6 text-neutral-400" />
<span class="text-neutral-400"
>{reportsTarget.pagination.totalCount} report{reportsTarget.pagination.totalCount !== 1
? 's'
: ''}</span
>
</div>
{/if}
<div class="flex shrink-0 items-center"> <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}`}>
@@ -381,47 +530,369 @@
<Flag class="m-4 h-6 w-6 cursor-pointer text-neutral-400 hover:text-amber-400" /> <Flag class="m-4 h-6 w-6 cursor-pointer text-neutral-400 hover:text-amber-400" />
</div> </div>
{/if} {/if}
<div class="mt-8 flex w-full border-b border-neutral-800">
{#if isOwner || $user?.roles?.some((r) => r === 255 || r === 1)} {#if isOwner || $user?.roles?.some((r) => r === 255 || r === 1)}
<div class="mt-4 flex flex-wrap justify-center gap-2">
<button <button
on:click={openEditDisplayName} class="border-b-2 px-4 py-2 font-medium transition-colors hover:text-white {activeTab ===
'settings'
? 'border-neutral-200 text-white'
: 'border-transparent text-neutral-400'}"
on:click={() => updateTab('settings')}
>
Settings
</button>
{/if}
<button
class="border-b-2 px-4 py-2 font-medium transition-colors hover:text-white {activeTab ===
'pastes'
? 'border-neutral-200 text-white'
: 'border-transparent text-neutral-400'}"
on:click={() => updateTab('pastes')}
>
Pastes
<span class="ml-2 rounded bg-neutral-800 px-2 py-0.5 text-xs text-neutral-300"
>{pagination.totalCount}</span
>
</button>
{#if reportsSubmitted}
<button
class="border-b-2 px-4 py-2 font-medium transition-colors hover:text-white {activeTab ===
'reportsSubmitted'
? 'border-neutral-200 text-white'
: 'border-transparent text-neutral-400'}"
on:click={() => updateTab('reportsSubmitted')}
>
Submitted Reports
<span class="ml-2 rounded bg-neutral-800 px-2 py-0.5 text-xs text-neutral-300"
>{reportsSubmitted.pagination.totalCount}</span
>
</button>
{/if}
{#if reportsTarget}
<button
class="border-b-2 px-4 py-2 font-medium transition-colors hover:text-white {activeTab ===
'reportsTarget'
? 'border-neutral-200 text-white'
: 'border-transparent text-neutral-400'}"
on:click={() => updateTab('reportsTarget')}
>
Reports Against User
<span class="ml-2 rounded bg-neutral-800 px-2 py-0.5 text-xs text-neutral-300"
>{reportsTarget.pagination.totalCount}</span
>
</button>
{/if}
</div>
<div class="relative mt-4 min-h-50 w-full">
{#if loading}
<div
class="absolute inset-0 z-10 flex items-center justify-center bg-neutral-900/50 backdrop-blur-sm"
>
<LoaderCircle class="h-8 w-8 animate-spin text-neutral-200" />
</div>
{/if}
{#if activeTab === 'settings'}
<div class="grid grid-cols-1 gap-6 md:grid-cols-2">
<div class="col-span-2">
<div class="rounded border border-neutral-800 bg-neutral-900/50 p-6">
<div class="mb-6 flex items-start">
<div>
<h2 class="text-xl font-semibold text-neutral-100">Display Name</h2>
<p class="mt-1 text-sm text-neutral-400">
{isOwner
? 'Your display name is shown publicly on your profile and pastes.'
: "This user's display name is shown publicly on their profile and pastes."}
</p>
</div>
</div>
<div class="flex items-center justify-between rounded bg-neutral-800/50 p-3">
{#if isEditingDisplayName}
<div class="flex w-full items-center gap-2">
<input
type="text"
bind:value={editDisplayNameValue}
class="w-full border-b border-neutral-600 bg-transparent px-2 py-1 font-mono text-neutral-300 outline-none focus:border-neutral-400"
maxlength="26"
on:keydown={(e) => {
if (e.key === 'Enter') saveDisplayName();
else if (e.key === 'Escape') cancelEditDisplayName();
}}
/>
<button
on:click={saveDisplayName}
class="flex items-center gap-1 rounded bg-green-900/50 px-3 py-2 text-xs font-medium text-green-400 transition-colors hover:bg-green-900"
>
<Check class="h-4 w-4" />
Save
</button>
<button
on:click={cancelEditDisplayName}
class="flex items-center gap-1 rounded bg-neutral-700 px-3 py-2 text-xs font-medium text-neutral-300 transition-colors hover:bg-neutral-600"
>
<X class="h-4 w-4" />
Cancel
</button>
</div>
{:else}
<span class="font-mono text-neutral-300"
>{data.user?.displayName || data.user?.username}</span
>
<button
on:click={startEditDisplayName}
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" />
Edit Display Name Edit
</button>
{#if isOwner}
<button
on:click={openTotpSetup}
class="flex items-center gap-2 rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600"
>
<ShieldUser class="h-4 w-4" />
{totpEnabled ? 'Manage 2FA' : 'Enable 2FA'}
</button> </button>
{/if} {/if}
</div>
</div>
</div>
{#if isOwner}
<div class="col-span-2 md:col-span-1">
<div class="h-full rounded border border-neutral-800 bg-neutral-900/50 p-6">
<div class="mb-6 flex items-start">
<div>
<h2 class="text-xl font-semibold text-neutral-100">Security</h2>
<p class="mt-1 text-sm text-neutral-400">
Manage your account security settings.
</p>
</div>
</div>
<div class="space-y-4">
<div class="flex items-center justify-between rounded bg-neutral-800/50 p-3">
<div class="flex flex-col">
<span class="text-sm font-medium text-neutral-200"
>Two-Factor Authentication</span
>
<span class="text-xs text-neutral-500"
>{totpEnabled ? 'Enabled' : 'Disabled'}</span
>
</div>
<button
on:click={openTotpSetup}
class="rounded bg-neutral-700 px-3 py-1.5 text-xs font-medium transition-colors hover:bg-neutral-600"
>
{totpEnabled ? 'Manage' : 'Enable'}
</button>
</div>
</div>
</div>
</div>
{/if}
{#if $user?.roles?.some((r) => r === 255)} {#if $user?.roles?.some((r) => r === 255)}
<div class="col-span-2 {isOwner ? 'md:col-span-1' : ''}">
<div class="h-full rounded border border-neutral-800 bg-neutral-900/50 p-6">
<div class="mb-6 flex items-start">
<div>
<h2 class="text-xl font-semibold text-neutral-100">Administration</h2>
<p class="mt-1 text-sm text-neutral-400">Manage user roles and permissions.</p>
</div>
</div>
<div class="space-y-4">
<div class="flex items-center justify-between rounded bg-neutral-800/50 p-3">
<div class="flex flex-col">
<span class="text-sm font-medium text-neutral-200">User Roles</span>
<span class="text-xs text-neutral-500"
>{data.user?.roles?.length ?? 0} roles assigned</span
>
</div>
<button <button
on:click={openEditRoles} on:click={openEditRoles}
class="flex items-center gap-2 rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600" class="flex items-center gap-2 rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600"
> >
<ShieldUser class="h-4 w-4" /> Edit
Edit Roles
</button> </button>
</div>
</div>
</div>
</div>
{/if} {/if}
{#if isOwner || $user?.roles?.some((r) => r === 255)}
<button {#if isOwner}
on:click={openDeleteAccount} <div class="col-span-2">
class="flex items-center gap-2 rounded bg-red-900 px-4 py-2 text-sm font-medium transition-colors hover:bg-red-800" <div class="rounded border border-neutral-800 bg-neutral-900/50 p-6">
<div class="mb-6 flex items-start justify-between">
<div>
<h2 class="text-xl font-semibold text-neutral-100">
API Keys ({apiKeys.length}/10)
</h2>
<p class="mt-1 text-sm text-neutral-400">
Manage API keys for accessing Sharpbin programmatically.
</p>
</div>
</div>
{#if apiKeyError}
<div
class="mb-4 rounded border border-red-900/50 bg-red-900/10 p-3 text-sm text-red-200"
> >
<Trash2 class="h-4 w-4" /> {apiKeyError}
Delete Account </div>
{/if}
<div class="mb-6">
{#if isCreatingApiKey}
<div class="flex items-center gap-2">
<input
type="text"
placeholder="Key Name"
bind:value={newApiKeyName}
class="flex-1 border-b border-neutral-600 bg-transparent px-3 py-2 font-mono text-neutral-300 outline-none focus:border-neutral-400"
maxlength="26"
/>
<button
on:click={createApiKey}
disabled={loading || !newApiKeyName}
class="flex items-center gap-2 rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600 disabled:opacity-50"
>
{#if loading}
<LoaderCircle class="h-4 w-4 animate-spin" />
{:else}
<Plus class="h-4 w-4" />
{/if}
Create
</button>
<button
on:click={() => {
isCreatingApiKey = false;
newApiKeyName = '';
}}
class="flex items-center gap-2 rounded bg-neutral-800 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-700"
>
Cancel
</button>
</div>
{:else}
<button
on:click={() => (isCreatingApiKey = true)}
class="flex items-center gap-2 rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600"
>
<Plus class="h-4 w-4" />
Create New Key
</button> </button>
{/if} {/if}
</div> </div>
{#if newApiKeyValue}
<div class="mb-6 rounded border border-green-900/50 bg-green-900/10 p-4">
<div class="mb-2 flex items-center justify-between">
<span class="text-sm font-medium text-green-400">API Key Created</span>
<button
on:click={() => (newApiKeyValue = '')}
class="text-green-400/70 hover:text-green-400"
>
<X class="h-4 w-4" />
</button>
</div>
<p class="mb-3 text-xs text-green-200/70">
Please copy your API key now. You won't be able to see it again.
</p>
<div class="flex items-center gap-2 rounded bg-neutral-900/50 p-2">
<code class="flex-1 font-mono text-sm break-all text-green-300"
>{newApiKeyValue}</code
>
<button
class="p-1 text-neutral-400 hover:text-white"
on:click={() => {
navigator.clipboard.writeText(newApiKeyValue);
copiedApiKey = true;
setTimeout(() => (copiedApiKey = false), 1000);
}}
use:tooltip={'Copy to clipboard'}
>
<div class="relative mr-1 h-5 w-5">
{#if copiedApiKey}
<span
transition:fade={{ duration: 200 }}
class="absolute inset-0 flex items-center justify-center"
><Check class="h-4 w-4 text-green-400" /></span
>
{:else}
<span
transition:fade={{ duration: 200 }}
class="absolute inset-0 flex items-center justify-center"
><Copy class="h-4 w-4 text-neutral-400" /></span
>
{/if} {/if}
</div>
</button>
</div>
</div>
{/if}
<div class="space-y-2">
{#if apiKeys.length !== 0}
{#each apiKeys as key (key.uuid)}
<div class="flex items-center justify-between rounded bg-neutral-800/50 p-3">
<div class="flex flex-col gap-1">
<span class="font-medium text-neutral-200">{key.name}</span>
<div class="flex gap-3 text-xs text-neutral-500">
<span>Created: {new Date(key.createdAt).toLocaleDateString()}</span>
<span
>Last used: {key.lastUsedAt
? dateToRelativeString(new Date(key.lastUsedAt), true, false, now)
: 'Never'}</span
>
</div>
</div>
<button
on:click={() => deleteApiKey(key.uuid)}
disabled={loading}
class="p-2 text-neutral-500 transition-colors hover:text-red-400"
title="Revoke Key"
>
<Trash2 class="h-4 w-4" />
</button>
</div>
{/each}
{/if}
</div>
</div>
</div>
{/if}
{#if isOwner || $user?.roles?.some((r) => r === 255)}
<div class="col-span-2">
<div class="rounded border border-red-900/30 bg-red-900/10 p-6">
<div class="flex items-start">
<div>
<h2 class="text-xl font-semibold text-red-400">Danger Zone</h2>
<p class="mt-1 text-sm text-red-200/70">
Irreversible actions related to this account.
</p>
</div>
</div>
<div class="mt-6 flex items-center justify-between rounded bg-red-900/20 p-4">
<div>
<h3 class="font-medium text-red-200">Delete Account</h3>
<p class="pr-0.5 text-sm text-red-200/60">
Permanently delete this account and all associated data.
</p>
</div>
<button
on:click={openDeleteAccount}
class="rounded border border-red-500/50 bg-red-500/10 px-4 py-2 text-sm font-medium whitespace-nowrap text-red-400 transition-colors hover:bg-red-500 hover:text-white"
>
Delete Account
</button>
</div>
</div>
</div>
{/if}
</div>
{:else if activeTab === 'pastes'}
<div class="mt-6 max-h-[60vh] space-y-4 overflow-y-auto"> <div class="mt-6 max-h-[60vh] space-y-4 overflow-y-auto">
{#if pastes && pastes.length > 0} {#if pastes && pastes.length > 0}
{#each pastes.slice().sort((a, b) => b.uuid.localeCompare(a.uuid)) as paste (paste.uuid)} {#each pastes
.slice()
.sort((a, b) => b.uuid.localeCompare(a.uuid)) as paste (paste.uuid)}
<Paste {paste} {now} showUser={false} compact={true} /> <Paste {paste} {now} showUser={false} compact={true} />
{/each} {/each}
{:else} {:else}
@@ -430,12 +901,29 @@
</p> </p>
{/if} {/if}
</div> </div>
{#if reportsSubmitted || reportsTarget} {#if pagination.totalPages && pagination.totalPages > 1}
<div class="mt-6 space-y-6"> <div class="mt-4 flex items-center justify-center gap-4">
{#if reportsSubmitted && reportsSubmitted.reports.length > 0} <button
<div class="rounded border border-neutral-800 bg-neutral-900/60 p-4"> class="rounded bg-neutral-700 px-3 py-1 disabled:opacity-50"
<h2 class="mb-3 text-xl font-semibold text-neutral-200">Submitted Reports</h2> on:click={() => fetchPage(currentPage - 1)}
<div class="space-y-3"> disabled={currentPage === 1 || loading}
>
Prev
</button>
<span class="text-neutral-400">
Page {currentPage} of {pagination.totalPages}
</span>
<button
class="rounded bg-neutral-700 px-3 py-1 disabled:opacity-50"
on:click={() => fetchPage(currentPage + 1)}
disabled={currentPage === pagination.totalPages || loading}
>
Next
</button>
</div>
{/if}
{:else if activeTab === 'reportsSubmitted' && reportsSubmitted && reportsSubmitted.reports.length > 0}
<div class="mt-6 space-y-3">
{#each reportsSubmitted.reports as report (report.reportID)} {#each reportsSubmitted.reports as report (report.reportID)}
<div <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" 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"
@@ -493,12 +981,8 @@
</div> </div>
{/each} {/each}
</div> </div>
</div> {:else if activeTab === 'reportsTarget' && reportsTarget && reportsTarget.reports.length > 0}
{/if} <div class="mt-6 space-y-3">
{#if reportsTarget && reportsTarget.reports.length > 0}
<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>
<div class="space-y-3">
{#each reportsTarget.reports as report (report.reportID)} {#each reportsTarget.reports as report (report.reportID)}
<div <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" 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"
@@ -568,31 +1052,18 @@
</div> </div>
{/each} {/each}
</div> </div>
</div> {:else}
<p class="mt-6 text-center text-neutral-400">
{#if activeTab === 'reportsSubmitted'}
{isOwner ? 'You have' : 'This user has'} not submitted any reports.
{:else if activeTab === 'reportsTarget'}
{isOwner ? 'You have' : 'This user has'} not been reported.
{:else}
No reports found.
{/if}
</p>
{/if} {/if}
</div> </div>
{/if}
{#if pagination.totalPages && pagination.totalPages > 1}
<div class="mt-4 flex items-center justify-center gap-4">
<button
class="rounded bg-neutral-700 px-3 py-1 disabled:opacity-50"
on:click={() => fetchPage(currentPage - 1)}
disabled={currentPage === 1 || loading}
>
Prev
</button>
<span class="text-neutral-400">
Page {currentPage} of {pagination.totalPages}
</span>
<button
class="rounded bg-neutral-700 px-3 py-1 disabled:opacity-50"
on:click={() => fetchPage(currentPage + 1)}
disabled={currentPage === pagination.totalPages || loading}
>
Next
</button>
</div>
{/if}
</div> </div>
</main> </main>
@@ -0,0 +1,50 @@
using System.Security.Claims;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Options;
using SharpbinV3.Server.Extensions;
using SharpbinV3.Server.Services;
namespace SharpbinV3.Server.Authentication
{
public sealed class ApiKeyAuthenticationHandler(
IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
ApiKeyService apiKeyService
) : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{
private readonly ApiKeyService _apiKeyService = apiKeyService;
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
var apiKeyString = Context.GetApiKey();
if (string.IsNullOrEmpty(apiKeyString))
return AuthenticateResult.NoResult();
var apiKey = await _apiKeyService.GetByKeyAsync(apiKeyString);
if (apiKey == null || apiKey.User == null)
return AuthenticateResult.Fail("Invalid API key.");
var claims = new List<Claim>
{
new("uuid", apiKey.User.UUID.ToString()),
new("username", apiKey.User.Username ?? ""),
new("displayname", apiKey.User.DisplayName ?? ""),
new("totp_enabled", (apiKey.User.Totp != null).ToString()),
};
if (apiKey.User.Roles != null)
claims.AddRange(apiKey.User.Roles.Select(r => new Claim(ClaimTypes.Role, r.ToString())));
var identity = new ClaimsIdentity(claims, AuthSchemes.ApiKey);
var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, AuthSchemes.ApiKey);
Context.SetApiKeyContext(apiKey);
await _apiKeyService.UpdateLastUsedAsync(apiKey.UUID);
return AuthenticateResult.Success(ticket);
}
}
}
@@ -0,0 +1,8 @@
namespace SharpbinV3.Server.Authentication
{
public static class AuthSchemes
{
public const string Combined = "Combined";
public const string ApiKey = "ApiKey";
}
}
@@ -1,5 +1,6 @@
using System.Security.Claims; using System.Security.Claims;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using SharpbinV3.Server.Extensions;
namespace SharpbinV3.Server.Authorization namespace SharpbinV3.Server.Authorization
{ {
@@ -9,13 +10,26 @@ namespace SharpbinV3.Server.Authorization
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, NotBannedRequirement requirement) protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, NotBannedRequirement requirement)
{ {
var httpContext = context.Resource as HttpContext;
var isAuthenticated = context.User.Identity?.IsAuthenticated ?? false; var isAuthenticated = context.User.Identity?.IsAuthenticated ?? false;
if (!isAuthenticated && httpContext != null)
{
var apiKey = httpContext.GetApiKeyFromContext();
if (apiKey != null)
{
isAuthenticated = true;
}
}
if (_requireAuth && !isAuthenticated) if (_requireAuth && !isAuthenticated)
return Task.CompletedTask; return Task.CompletedTask;
var isBanned = context.User.Claims.Any(c => (c.Type == ClaimTypes.Role || c.Type == "role") && c.Value == "403"); var isBanned = context.User.Claims.Any(c => (c.Type == ClaimTypes.Role || c.Type == "role") && c.Value == "403");
if (httpContext?.GetApiKeyFromContext()?.User?.Roles?.Contains(403) == true)
isBanned = true;
if (!isBanned) if (!isBanned)
context.Succeed(requirement); context.Succeed(requirement);
@@ -6,6 +6,7 @@ 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.ApiKey;
using SharpbinV3.Server.DTOs.Auth; using SharpbinV3.Server.DTOs.Auth;
using SharpbinV3.Server.DTOs.User; using SharpbinV3.Server.DTOs.User;
using SharpbinV3.Server.Extensions; using SharpbinV3.Server.Extensions;
@@ -22,6 +23,7 @@ namespace SharpbinV3.Server.Controllers
public class AuthController( public class AuthController(
UserService userService, UserService userService,
AuthService authService, AuthService authService,
ApiKeyService apiKeyService,
IOptions<AuthSettings> options, IOptions<AuthSettings> options,
VerificationService verification, VerificationService verification,
TotpVerificationProvider totp, TotpVerificationProvider totp,
@@ -30,6 +32,7 @@ namespace SharpbinV3.Server.Controllers
{ {
private readonly AuthService _authService = authService; private readonly AuthService _authService = authService;
private readonly UserService _userService = userService; private readonly UserService _userService = userService;
private readonly ApiKeyService _apiKeyService = apiKeyService;
private readonly VerificationService _verification = verification; private readonly VerificationService _verification = verification;
private readonly TotpVerificationProvider _totp = totp; private readonly TotpVerificationProvider _totp = totp;
private readonly AppDbContext _db = db; private readonly AppDbContext _db = db;
@@ -164,7 +167,7 @@ namespace SharpbinV3.Server.Controllers
} }
[HttpGet] [HttpGet]
[Authorize] [Authorize(Policy = "JwtOnly")]
[Route("totp/enroll")] [Route("totp/enroll")]
public async Task<IActionResult> StartTotpEnrollment() public async Task<IActionResult> StartTotpEnrollment()
{ {
@@ -187,16 +190,12 @@ namespace SharpbinV3.Server.Controllers
} }
[HttpPost] [HttpPost]
[Authorize] [Authorize(Policy = "JwtOnly")]
[Route("totp/enable")] [Route("totp/enable")]
[EnableRateLimiting("Sensitive")] [EnableRateLimiting("Sensitive")]
public async Task<IActionResult> EnableTotp([FromBody] EnableTotpDto request) public async Task<IActionResult> EnableTotp([FromBody] EnableTotpDto request)
{ {
var uuidClaim = User.Claims.FirstOrDefault(c => c.Type == "UUID")?.Value; var uuid = Guid.Parse(User.FindFirst("uuid")!.Value);
if (string.IsNullOrEmpty(uuidClaim))
return Unauthorized(new { success = false, message = "Invalid token." });
var uuid = Guid.Parse(uuidClaim);
if (string.IsNullOrWhiteSpace(request.Secret) || string.IsNullOrWhiteSpace(request.Code)) if (string.IsNullOrWhiteSpace(request.Secret) || string.IsNullOrWhiteSpace(request.Code))
return BadRequest(new { success = false, message = "Secret and code are required." }); return BadRequest(new { success = false, message = "Secret and code are required." });
@@ -221,7 +220,7 @@ namespace SharpbinV3.Server.Controllers
} }
[HttpPost] [HttpPost]
[Authorize] [Authorize(Policy = "JwtOnly")]
[Route("totp/disable")] [Route("totp/disable")]
public async Task<IActionResult> DisableTotp([FromBody] DisableTotpDto dto) public async Task<IActionResult> DisableTotp([FromBody] DisableTotpDto dto)
{ {
@@ -240,5 +239,88 @@ namespace SharpbinV3.Server.Controllers
await _db.SaveChangesAsync(); await _db.SaveChangesAsync();
return Ok(new { success = true, message = "TOTP disabled." }); return Ok(new { success = true, message = "TOTP disabled." });
} }
[HttpPost]
[Authorize(Policy = "JwtOnly")]
[Route("apikey/create")]
[EnableRateLimiting("Strict")]
public async Task<IActionResult> CreateApiKey([FromBody] CreateApiKeyRequest request)
{
if (string.IsNullOrWhiteSpace(request.Name))
return BadRequest(new { success = false, message = "API key name is required." });
if (request.Name.Length > 26)
return BadRequest(new { success = false, message = "API key name must not exceed 26 characters." });
var user = await _authService.GetUserFromHttpContext(HttpContext);
if (user == null)
return BadRequest(new { success = false, message = "User not found." });
var existingKeys = await _apiKeyService.GetUserKeysAsync(user.UUID);
if (existingKeys.Count >= 10)
return BadRequest(new { success = false, message = "API key limit reached. Please delete existing keys before creating new ones." });
var (apiKey, key) = await _apiKeyService.CreateAsync(user.UUID, request.Name);
return Ok(
new
{
success = true,
message = "API key created. Save it now as you won't be able to see it again.",
apiKey = new ApiKeyResponseDto
{
UUID = apiKey.UUID,
Key = key,
Name = apiKey.Name,
CreatedAt = apiKey.CreatedAt,
},
}
);
}
[HttpGet]
[Authorize]
[Route("apikey/list")]
public async Task<IActionResult> ListApiKeys()
{
var user = await _authService.GetUserFromHttpContext(HttpContext);
if (user == null)
return BadRequest(new { success = false, message = "User not found." });
var apiKeys = await _apiKeyService.GetUserKeysAsync(user.UUID);
return Ok(
new
{
success = true,
apiKeys = apiKeys
.Select(k => new ApiKeyListItemDto
{
UUID = k.UUID,
Name = k.Name,
CreatedAt = k.CreatedAt,
LastUsedAt = k.LastUsedAt,
})
.ToList(),
}
);
}
[HttpDelete]
[Authorize(Policy = "JwtOnly")]
[Route("apikey/{uuid}")]
public async Task<IActionResult> DeleteApiKey(string uuid)
{
if (!Guid.TryParse(uuid, out var keyUUID))
return BadRequest(new { success = false, message = "Invalid API key UUID." });
var user = await _authService.GetUserFromHttpContext(HttpContext);
if (user == null)
return BadRequest(new { success = false, message = "User not found." });
var deleted = await _apiKeyService.DeleteAsync(user.UUID, keyUUID);
if (!deleted)
return NotFound(new { success = false, message = "API key not found." });
return Ok(new { success = true, message = "API key deleted." });
}
} }
} }
@@ -40,7 +40,7 @@ namespace SharpbinV3.Server.Controllers
string syntax = "plaintext", string syntax = "plaintext",
int visibility = 0, int visibility = 0,
long expiresAt = 0, long expiresAt = 0,
string? token = null string? verificationToken = null
) )
{ {
if (!_pasteService.ValidateExpiresAt(expiresAt)) if (!_pasteService.ValidateExpiresAt(expiresAt))
@@ -60,11 +60,18 @@ namespace SharpbinV3.Server.Controllers
new { success = false, message = $"Paste size exceeds the maximum allowed size of {_pasteSettings.MaxPasteSizeInBytes} bytes." } new { success = false, message = $"Paste size exceeds the maximum allowed size of {_pasteSettings.MaxPasteSizeInBytes} bytes." }
); );
if ( if (_pasteSettings.RequiresVerification && !HttpContext.IsApiKeyAuthenticated())
_pasteSettings.RequiresVerification {
&& !await _verificationService.VerifyAsync(new VerificationContext { Token = token, Ip = HttpContext.GetRequestIP() }) var providedApiKey = HttpContext.GetApiKey();
) if (providedApiKey != null)
return BadRequest(new { success = false, message = "Invalid API key." });
var verifyResult = await _verificationService.VerifyAsync(
new VerificationContext { Token = verificationToken, Ip = HttpContext.GetRequestIP() }
);
if (!verifyResult)
return BadRequest(new { success = false, message = "Verification failed." }); return BadRequest(new { success = false, 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, _pasteSettings.EnablePasteCompression); Paste paste = await _pasteService.Create(user, content, title, syntax, visibility, expiresAt, _pasteSettings.EnablePasteCompression);
@@ -149,7 +156,7 @@ namespace SharpbinV3.Server.Controllers
[HttpPut] [HttpPut]
[Route("{id}")] [Route("{id}")]
[Authorize(Policy = "AuthAndNotBanned")] [Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> EditPaste(string id) public async Task<IActionResult> EditPaste(string id)
{ {
string content = await new StreamReader(Request.Body).ReadToEndAsync(); string content = await new StreamReader(Request.Body).ReadToEndAsync();
@@ -160,9 +167,7 @@ namespace SharpbinV3.Server.Controllers
if (paste == null) if (paste == null)
return StatusCode(404, new { success = false, message = "Paste not found." }); return StatusCode(404, new { success = false, message = "Paste not found." });
var user = HttpContext.GetJwtUser(); var user = HttpContext.GetJwtUser()!;
if (user == null)
return Unauthorized(new { success = false, message = "Invalid token." });
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)
@@ -178,16 +183,14 @@ namespace SharpbinV3.Server.Controllers
[HttpPatch] [HttpPatch]
[Route("{id}")] [Route("{id}")]
[Authorize(Policy = "AuthAndNotBanned")] [Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> ModifyPasteMetadata(string id, [FromBody] UpdatePasteDto request) public async Task<IActionResult> ModifyPasteMetadata(string id, [FromBody] UpdatePasteDto request)
{ {
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 user = HttpContext.GetJwtUser(); var user = HttpContext.GetJwtUser()!;
if (user == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255); var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
@@ -239,16 +242,14 @@ namespace SharpbinV3.Server.Controllers
[HttpDelete] [HttpDelete]
[Route("{id}")] [Route("{id}")]
[Authorize(Policy = "AuthAndNotBanned")] [Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> DeletePaste(string id) public async Task<IActionResult> DeletePaste(string id)
{ {
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 user = HttpContext.GetJwtUser(); var user = HttpContext.GetJwtUser()!;
if (user == null)
return Unauthorized(new { success = false, message = "Invalid token." });
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)
@@ -291,16 +292,14 @@ namespace SharpbinV3.Server.Controllers
[HttpPost] [HttpPost]
[Route("{id}/report")] [Route("{id}/report")]
[Authorize(Policy = "AuthAndNotBanned")] [Authorize(Policy = "JwtOnlyAndNotBanned")]
[EnableRateLimiting("Sensitive")] [EnableRateLimiting("Sensitive")]
public async Task<IActionResult> ReportPaste(string id, [FromBody] ReportDto request) public async Task<IActionResult> ReportPaste(string id, [FromBody] ReportDto request)
{ {
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 user = HttpContext.GetJwtUser(); var user = HttpContext.GetJwtUser()!;
if (user == null)
return Unauthorized(new { success = false, message = "Invalid token." });
Enum.TryParse<ReportType>(request.ReportType, true, out var reportType); Enum.TryParse<ReportType>(request.ReportType, true, out var reportType);
if (!Enum.IsDefined(reportType)) if (!Enum.IsDefined(reportType))
@@ -340,7 +339,7 @@ namespace SharpbinV3.Server.Controllers
[HttpPatch] [HttpPatch]
[Route("{id}/report/{reportId}")] [Route("{id}/report/{reportId}")]
[Authorize(Policy = "AuthAndNotBanned")] [Authorize(Policy = "JwtOnlyAndNotBanned")]
[EnableRateLimiting("Sensitive")] [EnableRateLimiting("Sensitive")]
public async Task<IActionResult> ModifyPasteReport(string id, int reportId, [FromBody] ReportDto request) public async Task<IActionResult> ModifyPasteReport(string id, int reportId, [FromBody] ReportDto request)
{ {
@@ -352,9 +351,7 @@ namespace SharpbinV3.Server.Controllers
if (report == null || report.TargetType != ReportTargetType.Paste || report.PastePID != paste.PID) if (report == null || report.TargetType != ReportTargetType.Paste || report.PastePID != paste.PID)
return NotFound(new { success = false, message = "Report not found." }); return NotFound(new { success = false, message = "Report not found." });
var user = HttpContext.GetJwtUser(); var user = HttpContext.GetJwtUser()!;
if (user == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255); var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
if (report.ReporterUUID != user.UUID && !hasPrivilegedRole) if (report.ReporterUUID != user.UUID && !hasPrivilegedRole)
@@ -376,7 +373,7 @@ namespace SharpbinV3.Server.Controllers
[HttpDelete] [HttpDelete]
[Route("{id}/report/{reportId}")] [Route("{id}/report/{reportId}")]
[Authorize(Policy = "AuthAndNotBanned")] [Authorize(Policy = "JwtOnlyAndNotBanned")]
[EnableRateLimiting("Sensitive")] [EnableRateLimiting("Sensitive")]
public async Task<IActionResult> DeletePasteReport(string id, int reportId) public async Task<IActionResult> DeletePasteReport(string id, int reportId)
{ {
@@ -388,9 +385,7 @@ namespace SharpbinV3.Server.Controllers
if (report == null || report.TargetType != ReportTargetType.Paste || report.PastePID != paste.PID) if (report == null || report.TargetType != ReportTargetType.Paste || report.PastePID != paste.PID)
return NotFound(new { success = false, message = "Report not found." }); return NotFound(new { success = false, message = "Report not found." });
var user = HttpContext.GetJwtUser(); var user = HttpContext.GetJwtUser()!;
if (user == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255); var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
if (report.ReporterUUID != user.UUID && !hasPrivilegedRole) if (report.ReporterUUID != user.UUID && !hasPrivilegedRole)
@@ -15,12 +15,10 @@ namespace SharpbinV3.Server.Controllers
[Route("{reportId:int}")] [Route("{reportId:int}")]
[HttpGet] [HttpGet]
[EnableRateLimiting("Sliding")] [EnableRateLimiting("Sliding")]
[Authorize(Policy = "AuthAndNotBanned")] [Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> GetReportById(int reportId) public async Task<IActionResult> GetReportById(int reportId)
{ {
var user = HttpContext.GetJwtUser(); 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); var report = await reportService.GetReportByID(reportId);
if (report is null) if (report is null)
@@ -57,12 +55,10 @@ namespace SharpbinV3.Server.Controllers
[Route("{reportId:int}")] [Route("{reportId:int}")]
[HttpPatch] [HttpPatch]
[EnableRateLimiting("Sensitive")] [EnableRateLimiting("Sensitive")]
[Authorize(Policy = "AuthAndNotBanned")] [Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> UpdateReport(int reportId, [FromBody] ReportUpdateDto request) public async Task<IActionResult> UpdateReport(int reportId, [FromBody] ReportUpdateDto request)
{ {
var user = HttpContext.GetJwtUser(); 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)) if (!user.Roles.Contains(1) && !user.Roles.Contains(255))
return StatusCode(403, new { success = false, message = "You do not have permission to update reports." }); return StatusCode(403, new { success = false, message = "You do not have permission to update reports." });
@@ -127,12 +123,10 @@ namespace SharpbinV3.Server.Controllers
[Route("pastes")] [Route("pastes")]
[HttpGet] [HttpGet]
[EnableRateLimiting("Sliding")] [EnableRateLimiting("Sliding")]
[Authorize(Policy = "AuthAndNotBanned")] [Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> GetReportsForPastes([FromQuery] ReportQuery request) public async Task<IActionResult> GetReportsForPastes([FromQuery] ReportQuery request)
{ {
var user = HttpContext.GetJwtUser(); 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)) if (!user.Roles.Contains(1) && !user.Roles.Contains(255))
return StatusCode(403, new { success = false, message = "You do not have permission to view pastes." }); return StatusCode(403, new { success = false, message = "You do not have permission to view pastes." });
@@ -159,12 +153,10 @@ namespace SharpbinV3.Server.Controllers
[Route("users")] [Route("users")]
[HttpGet] [HttpGet]
[EnableRateLimiting("Sliding")] [EnableRateLimiting("Sliding")]
[Authorize(Policy = "AuthAndNotBanned")] [Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> GetReportsForUsers([FromQuery] ReportQuery request) public async Task<IActionResult> GetReportsForUsers([FromQuery] ReportQuery request)
{ {
var user = HttpContext.GetJwtUser(); 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)) if (!user.Roles.Contains(1) && !user.Roles.Contains(255))
return StatusCode(403, new { success = false, message = "You do not have permission to view users." }); return StatusCode(403, new { success = false, message = "You do not have permission to view users." });
@@ -197,7 +189,7 @@ namespace SharpbinV3.Server.Controllers
[Route("all")] [Route("all")]
[HttpGet] [HttpGet]
[EnableRateLimiting("Sliding")] [EnableRateLimiting("Sliding")]
[Authorize(Policy = "AuthAndNotBanned")] [Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> GetAllReports( public async Task<IActionResult> GetAllReports(
[FromQuery] Guid? reporterUuid, [FromQuery] Guid? reporterUuid,
[FromQuery] ReportTargetType? targetType, [FromQuery] ReportTargetType? targetType,
@@ -207,9 +199,7 @@ namespace SharpbinV3.Server.Controllers
[FromQuery] int pageSize = 20 [FromQuery] int pageSize = 20
) )
{ {
var user = HttpContext.GetJwtUser(); 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)) if (!user.Roles.Contains(1) && !user.Roles.Contains(255))
return StatusCode(403, new { success = false, message = "You do not have permission to view reports." }); return StatusCode(403, new { success = false, message = "You do not have permission to view reports." });
+15 -32
View File
@@ -53,16 +53,13 @@ namespace SharpbinV3.Server.Controllers
[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)
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." }) : 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}")]
[Authorize] [Authorize(Policy = "JwtOnly")]
[EnableRateLimiting("Strict")] [EnableRateLimiting("Strict")]
public async Task<IActionResult> UpdateByUUID(Guid uuid, [FromBody] UpdateUserDto updatedUser) public async Task<IActionResult> UpdateByUUID(Guid uuid, [FromBody] UpdateUserDto updatedUser)
{ {
@@ -70,9 +67,7 @@ namespace SharpbinV3.Server.Controllers
if (!ModelState.IsValid) if (!ModelState.IsValid)
return BadRequest(ModelState); return BadRequest(ModelState);
var jwtUser = HttpContext.GetJwtUser(); var jwtUser = HttpContext.GetJwtUser()!;
if (jwtUser == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var user = await _userService.GetByUUID(uuid); var user = await _userService.GetByUUID(uuid);
if (user == null) if (user == null)
@@ -113,13 +108,11 @@ namespace SharpbinV3.Server.Controllers
} }
[HttpDelete("uuid/{uuid}")] [HttpDelete("uuid/{uuid}")]
[Authorize(Policy = "AuthAndNotBanned")] [Authorize(Policy = "JwtOnlyAndNotBanned")]
[EnableRateLimiting("Sensitive")] [EnableRateLimiting("Sensitive")]
public async Task<IActionResult> DeleteByUUID(Guid uuid, [FromBody] DeleteUserDto dto) public async Task<IActionResult> DeleteByUUID(Guid uuid, [FromBody] DeleteUserDto dto)
{ {
var jwtUser = HttpContext.GetJwtUser(); var jwtUser = HttpContext.GetJwtUser()!;
if (jwtUser == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var user = await _userService.GetByUUID(uuid); var user = await _userService.GetByUUID(uuid);
if (user == null) if (user == null)
@@ -159,12 +152,10 @@ namespace SharpbinV3.Server.Controllers
[HttpPost] [HttpPost]
[Route("{uuid}/report")] [Route("{uuid}/report")]
[EnableRateLimiting("Sensitive")] [EnableRateLimiting("Sensitive")]
[Authorize(Policy = "AuthAndNotBanned")] [Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> ReportUser(Guid uuid, [FromBody] ReportDto request) public async Task<IActionResult> ReportUser(Guid uuid, [FromBody] ReportDto request)
{ {
var reporter = HttpContext.GetJwtUser(); var reporter = HttpContext.GetJwtUser()!;
if (reporter == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var reportedUser = await _userService.GetByUUID(uuid); var reportedUser = await _userService.GetByUUID(uuid);
if (reportedUser == null) if (reportedUser == null)
@@ -210,12 +201,10 @@ namespace SharpbinV3.Server.Controllers
[HttpPatch] [HttpPatch]
[Route("{uuid}/report/{reportId}")] [Route("{uuid}/report/{reportId}")]
[EnableRateLimiting("Sensitive")] [EnableRateLimiting("Sensitive")]
[Authorize(Policy = "AuthAndNotBanned")] [Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> UpdateUserReport(Guid uuid, int reportId, [FromBody] ReportDto request) public async Task<IActionResult> UpdateUserReport(Guid uuid, int reportId, [FromBody] ReportDto request)
{ {
var jwtUser = HttpContext.GetJwtUser(); var jwtUser = HttpContext.GetJwtUser()!;
if (jwtUser == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var user = await _userService.GetByUUID(uuid); var user = await _userService.GetByUUID(uuid);
if (user == null) if (user == null)
@@ -239,12 +228,10 @@ namespace SharpbinV3.Server.Controllers
[HttpDelete] [HttpDelete]
[Route("{uuid}/report/{reportId}")] [Route("{uuid}/report/{reportId}")]
[EnableRateLimiting("Sensitive")] [EnableRateLimiting("Sensitive")]
[Authorize(Policy = "AuthAndNotBanned")] [Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> DeleteUserReport(Guid uuid, int reportId) public async Task<IActionResult> DeleteUserReport(Guid uuid, int reportId)
{ {
var jwtUser = HttpContext.GetJwtUser(); var jwtUser = HttpContext.GetJwtUser()!;
if (jwtUser == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var user = await _userService.GetByUUID(uuid); var user = await _userService.GetByUUID(uuid);
if (user == null) if (user == null)
@@ -262,13 +249,11 @@ namespace SharpbinV3.Server.Controllers
} }
[HttpGet] [HttpGet]
[Authorize] [Authorize(Policy = "JwtOnly")]
[Route("{uuid}/reports")] [Route("{uuid}/reports")]
public async Task<IActionResult> GetUserReports(Guid uuid, [FromQuery] ReportQuery request) public async Task<IActionResult> GetUserReports(Guid uuid, [FromQuery] ReportQuery request)
{ {
var jwtUser = HttpContext.GetJwtUser(); var jwtUser = HttpContext.GetJwtUser()!;
if (jwtUser == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var user = await _userService.GetByUUID(uuid); var user = await _userService.GetByUUID(uuid);
if (user == null) if (user == null)
@@ -297,13 +282,11 @@ namespace SharpbinV3.Server.Controllers
} }
[HttpGet] [HttpGet]
[Authorize] [Authorize(Policy = "JwtOnly")]
[Route("{uuid}/reports/submitted")] [Route("{uuid}/reports/submitted")]
public async Task<IActionResult> GetUserSubmittedReports(Guid uuid, [FromQuery] ReportQuery request) public async Task<IActionResult> GetUserSubmittedReports(Guid uuid, [FromQuery] ReportQuery request)
{ {
var jwtUser = HttpContext.GetJwtUser(); var jwtUser = HttpContext.GetJwtUser()!;
if (jwtUser == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var user = await _userService.GetByUUID(uuid); var user = await _userService.GetByUUID(uuid);
if (user == null) if (user == null)
@@ -0,0 +1,10 @@
namespace SharpbinV3.Server.DTOs.ApiKey
{
public sealed class ApiKeyListItemDto
{
public required string Name { get; set; }
public required Guid UUID { get; set; }
public required long CreatedAt { get; set; }
public long? LastUsedAt { get; set; }
}
}
@@ -0,0 +1,10 @@
namespace SharpbinV3.Server.DTOs.ApiKey
{
public sealed class ApiKeyResponseDto
{
public required string Key { get; set; }
public required string Name { get; set; }
public required Guid UUID { get; set; }
public required long CreatedAt { get; set; }
}
}
@@ -0,0 +1,7 @@
namespace SharpbinV3.Server.DTOs.ApiKey
{
public sealed class CreateApiKeyRequest
{
public required string Name { get; set; }
}
}
+7
View File
@@ -11,6 +11,7 @@ namespace SharpbinV3.Server.Data
public DbSet<RefreshToken> RefreshTokens => Set<RefreshToken>(); public DbSet<RefreshToken> RefreshTokens => Set<RefreshToken>();
public DbSet<UserTotp> UserTotps => Set<UserTotp>(); public DbSet<UserTotp> UserTotps => Set<UserTotp>();
public DbSet<Report> Reports => Set<Report>(); public DbSet<Report> Reports => Set<Report>();
public DbSet<ApiKey> ApiKeys => Set<ApiKey>();
protected override void OnModelCreating(ModelBuilder modelBuilder) protected override void OnModelCreating(ModelBuilder modelBuilder)
{ {
@@ -56,6 +57,12 @@ namespace SharpbinV3.Server.Data
.WithMany(u => u.Reports) .WithMany(u => u.Reports)
.HasForeignKey(r => r.UserUUID) .HasForeignKey(r => r.UserUUID)
.OnDelete(DeleteBehavior.SetNull); .OnDelete(DeleteBehavior.SetNull);
modelBuilder.Entity<ApiKey>()
.HasOne(a => a.User)
.WithMany(u => u.ApiKeys)
.HasForeignKey(a => a.UserUUID)
.OnDelete(DeleteBehavior.Cascade);
} }
} }
} }
+16
View File
@@ -0,0 +1,16 @@
using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.Server.Data.Entities
{
public sealed class ApiKey
{
[Key]
public Guid UUID { get; set; } = Guid.CreateVersion7();
public required Guid UserUUID { get; set; }
public User? User { get; set; }
public required string KeyHash { get; set; }
public required string Name { get; set; }
public long CreatedAt { get; set; } = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
public long? LastUsedAt { get; set; }
}
}
+1
View File
@@ -23,6 +23,7 @@ namespace SharpbinV3.Server.Data.Entities
public List<Paste> Pastes { get; set; } = []; public List<Paste> Pastes { get; set; } = [];
public List<RefreshToken> RefreshTokens { get; set; } = []; public List<RefreshToken> RefreshTokens { get; set; } = [];
public List<Report> Reports { get; set; } = []; public List<Report> Reports { get; set; } = [];
public List<ApiKey> ApiKeys { get; set; } = [];
public UserTotp? Totp { get; set; } public UserTotp? Totp { get; set; }
} }
} }
@@ -1,5 +1,6 @@
using System.IdentityModel.Tokens.Jwt; using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims; using System.Security.Claims;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.Services; using SharpbinV3.Server.Services;
namespace SharpbinV3.Server.Extensions namespace SharpbinV3.Server.Extensions
@@ -16,6 +17,38 @@ namespace SharpbinV3.Server.Extensions
"X-ProxyUser-IP", "X-ProxyUser-IP",
]; ];
private const string ApiKeyContextKey = "ApiKey";
public static string? GetApiKey(this HttpContext context)
{
var apiKeyHeader = context.Request.Headers["X-API-Key"].FirstOrDefault();
if (string.IsNullOrEmpty(apiKeyHeader))
return null;
if (apiKeyHeader.Length != ApiKeyService.KeyLength)
return null;
return apiKeyHeader;
}
public static ApiKey? GetApiKeyFromContext(this HttpContext context)
{
if (context.Items.TryGetValue(ApiKeyContextKey, out var apiKey))
return apiKey as ApiKey;
return null;
}
public static void SetApiKeyContext(this HttpContext context, ApiKey apiKey)
{
context.Items[ApiKeyContextKey] = apiKey;
}
public static bool IsApiKeyAuthenticated(this HttpContext context)
{
return context.GetApiKeyFromContext() != null;
}
public static JwtUser? GetJwtUser(this HttpContext context) public static JwtUser? GetJwtUser(this HttpContext context)
{ {
if (context.User == null || !context.User.Identity?.IsAuthenticated == true) if (context.User == null || !context.User.Identity?.IsAuthenticated == true)
@@ -0,0 +1,26 @@
using SharpbinV3.Server.Extensions;
using SharpbinV3.Server.Services;
namespace SharpbinV3.Server.Middleware
{
public sealed class ApiKeyAuthenticationMiddleware(RequestDelegate next)
{
private readonly RequestDelegate _next = next;
public async Task InvokeAsync(HttpContext context, ApiKeyService apiKeyService)
{
var apiKeyString = context.GetApiKey();
if (!string.IsNullOrEmpty(apiKeyString))
{
var apiKey = await apiKeyService.GetByKeyAsync(apiKeyString);
if (apiKey != null)
{
context.SetApiKeyContext(apiKey);
await apiKeyService.UpdateLastUsedAsync(apiKey.UUID);
}
}
await _next(context);
}
}
}
@@ -0,0 +1,405 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SharpbinV3.Server.Data;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20260210231315_AddApiKeys")]
partial class AddApiKeys
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.1");
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<string>("KeyHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long?>("LastUsedAt")
.HasColumnType("INTEGER");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("UUID");
b.HasIndex("UserUUID");
b.ToTable("ApiKeys");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.Property<int>("PID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<Guid?>("AuthorUUID")
.HasColumnType("TEXT");
b.Property<byte[]>("Content")
.IsRequired()
.HasColumnType("BLOB");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long?>("EditedAt")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("ID")
.HasColumnType("TEXT");
b.Property<bool>("IsCompressed")
.HasColumnType("INTEGER");
b.Property<long>("Size")
.HasColumnType("INTEGER");
b.Property<string>("Syntax")
.HasColumnType("TEXT");
b.Property<string>("Title")
.HasColumnType("TEXT");
b.Property<long>("TrueSize")
.HasColumnType("INTEGER");
b.Property<Guid>("UUID")
.HasColumnType("TEXT");
b.Property<int>("Views")
.HasColumnType("INTEGER");
b.Property<int>("Visibility")
.HasColumnType("INTEGER");
b.HasKey("PID");
b.HasIndex("AuthorUUID");
b.HasIndex("ExpiresAt");
b.HasIndex("ID")
.IsUnique();
b.HasIndex("PID")
.IsUnique();
b.HasIndex("Size");
b.HasIndex("Syntax");
b.HasIndex("UUID")
.IsUnique();
b.HasIndex("Views");
b.HasIndex("Visibility");
b.ToTable("Pastes");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<int>("PastePID")
.HasColumnType("INTEGER");
b.Property<long>("ViewedAt")
.HasColumnType("INTEGER");
b.Property<string>("ViewerHash")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("PastePID", "ViewerHash")
.IsUnique();
b.ToTable("PasteViews");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("TEXT");
b.Property<DateTimeOffset>("ExpiresAt")
.HasColumnType("TEXT");
b.Property<string>("JwtId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("ReplacedByToken")
.HasColumnType("TEXT");
b.Property<bool>("Revoked")
.HasColumnType("INTEGER");
b.Property<byte[]>("RowVersion")
.IsRequired()
.HasColumnType("BLOB");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<bool>("Used")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("TokenHash")
.IsUnique();
b.HasIndex("UserUUID");
b.ToTable("RefreshTokens");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b =>
{
b.Property<int>("ReportID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<string>("Description")
.HasMaxLength(1000)
.HasColumnType("TEXT");
b.Property<int?>("PastePID")
.HasColumnType("INTEGER");
b.Property<Guid>("ReporterUUID")
.HasColumnType("TEXT");
b.Property<int>("Status")
.HasColumnType("INTEGER");
b.Property<int>("TargetType")
.HasColumnType("INTEGER");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<long?>("UpdatedAt")
.HasColumnType("INTEGER");
b.Property<Guid?>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("ReportID");
b.HasIndex("PastePID");
b.HasIndex("ReportID")
.IsUnique();
b.HasIndex("ReporterUUID");
b.HasIndex("TargetType");
b.HasIndex("UserUUID");
b.ToTable("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<string>("DisplayName")
.HasColumnType("TEXT");
b.Property<string>("Email")
.HasColumnType("TEXT");
b.Property<long?>("LastLogin")
.HasColumnType("INTEGER");
b.Property<string>("PasswordHash")
.IsRequired()
.HasColumnType("TEXT");
b.PrimitiveCollection<string>("Roles")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int?>("UID")
.HasColumnType("INTEGER");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Visibility")
.HasColumnType("INTEGER");
b.HasKey("UUID");
b.HasIndex("UID");
b.HasIndex("UUID")
.IsUnique();
b.ToTable("Users");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b =>
{
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<byte[]>("EncryptedSecret")
.IsRequired()
.HasColumnType("BLOB");
b.HasKey("UserUUID");
b.ToTable("UserTotps");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("ApiKeys")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Pastes")
.HasForeignKey("AuthorUUID")
.OnDelete(DeleteBehavior.Cascade);
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("PasteViews")
.HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Paste");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("RefreshTokens")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("Reports")
.HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Reports")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.SetNull);
b.Navigation("Paste");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithOne("Totp")
.HasForeignKey("SharpbinV3.Server.Data.Entities.UserTotp", "UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.Navigation("PasteViews");
b.Navigation("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Navigation("ApiKeys");
b.Navigation("Pastes");
b.Navigation("RefreshTokens");
b.Navigation("Reports");
b.Navigation("Totp");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,49 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
/// <inheritdoc />
public partial class AddApiKeys : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "ApiKeys",
columns: table => new
{
UUID = table.Column<Guid>(type: "TEXT", nullable: false),
UserUUID = table.Column<Guid>(type: "TEXT", nullable: false),
KeyHash = table.Column<string>(type: "TEXT", nullable: false),
Name = table.Column<string>(type: "TEXT", nullable: false),
CreatedAt = table.Column<long>(type: "INTEGER", nullable: false),
LastUsedAt = table.Column<long>(type: "INTEGER", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_ApiKeys", x => x.UUID);
table.ForeignKey(
name: "FK_ApiKeys_Users_UserUUID",
column: x => x.UserUUID,
principalTable: "Users",
principalColumn: "UUID",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_ApiKeys_UserUUID",
table: "ApiKeys",
column: "UserUUID");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ApiKeys");
}
}
}
@@ -17,6 +17,36 @@ namespace SharpbinV3.Server.Migrations
#pragma warning disable 612, 618 #pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.1"); modelBuilder.HasAnnotation("ProductVersion", "10.0.1");
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<string>("KeyHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long?>("LastUsedAt")
.HasColumnType("INTEGER");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("UUID");
b.HasIndex("UserUUID");
b.ToTable("ApiKeys");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b => modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{ {
b.Property<int>("PID") b.Property<int>("PID")
@@ -276,6 +306,17 @@ namespace SharpbinV3.Server.Migrations
b.ToTable("UserTotps"); b.ToTable("UserTotps");
}); });
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("ApiKeys")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b => modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{ {
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
@@ -345,6 +386,8 @@ namespace SharpbinV3.Server.Migrations
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b => modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{ {
b.Navigation("ApiKeys");
b.Navigation("Pastes"); b.Navigation("Pastes");
b.Navigation("RefreshTokens"); b.Navigation("RefreshTokens");
+67 -1
View File
@@ -1,12 +1,15 @@
using System.Text; using System.Text;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
using System.Threading.RateLimiting; using System.Threading.RateLimiting;
using Microsoft.AspNetCore.Authentication;
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.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi;
using SharpbinV3.Server.Authentication;
using SharpbinV3.Server.Authorization; using SharpbinV3.Server.Authorization;
using SharpbinV3.Server.Data; using SharpbinV3.Server.Data;
using SharpbinV3.Server.Extensions; using SharpbinV3.Server.Extensions;
@@ -38,7 +41,21 @@ namespace SharpbinV3.Server
options.AddDocumentTransformer( options.AddDocumentTransformer(
(document, context, cancellationToken) => (document, context, cancellationToken) =>
{ {
document?.Components ??= new();
document?.Servers?.Clear(); document?.Servers?.Clear();
document?.Components?.SecuritySchemes ??= new Dictionary<string, IOpenApiSecurityScheme>();
document
?.Components
?.SecuritySchemes
?["ApiKey"] = new OpenApiSecurityScheme
{
Type = SecuritySchemeType.ApiKey,
Name = "X-API-Key",
In = ParameterLocation.Header,
Description = "Bypass authentication and captcha by providing a valid API key.",
};
return Task.CompletedTask; return Task.CompletedTask;
} }
); );
@@ -54,6 +71,7 @@ namespace SharpbinV3.Server
builder.Services.AddScoped<UserService>(); builder.Services.AddScoped<UserService>();
builder.Services.AddScoped<AuthService>(); builder.Services.AddScoped<AuthService>();
builder.Services.AddScoped<PasteService>(); builder.Services.AddScoped<PasteService>();
builder.Services.AddScoped<ApiKeyService>();
builder.Services.AddScoped<VerificationService>(); builder.Services.AddScoped<VerificationService>();
builder.Services.AddScoped<TotpVerificationProvider>(); builder.Services.AddScoped<TotpVerificationProvider>();
builder.Services.AddHttpClient<IVerificationProvider, TurnstileVerificationProvider>(); builder.Services.AddHttpClient<IVerificationProvider, TurnstileVerificationProvider>();
@@ -75,7 +93,34 @@ namespace SharpbinV3.Server
.ValidateOnStart(); .ValidateOnStart();
builder.Services.Configure<AuthSettings>(builder.Configuration.GetSection("AuthSettings")); builder.Services.Configure<AuthSettings>(builder.Configuration.GetSection("AuthSettings"));
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(); builder
.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = AuthSchemes.Combined;
options.DefaultScheme = AuthSchemes.Combined;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddPolicyScheme(
AuthSchemes.Combined,
AuthSchemes.Combined,
options =>
{
options.ForwardDefaultSelector = context =>
{
var apiKeyHeader = context.Request.Headers["X-API-Key"].ToString();
if (!string.IsNullOrEmpty(apiKeyHeader))
return AuthSchemes.ApiKey;
var authHeader = context.Request.Headers.Authorization.ToString();
if (!string.IsNullOrEmpty(authHeader) && authHeader.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
return JwtBearerDefaults.AuthenticationScheme;
return JwtBearerDefaults.AuthenticationScheme;
};
}
)
.AddJwtBearer()
.AddScheme<AuthenticationSchemeOptions, ApiKeyAuthenticationHandler>(AuthSchemes.ApiKey, _ => { });
builder builder
.Services.AddOptions<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme) .Services.AddOptions<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme)
@@ -109,6 +154,27 @@ namespace SharpbinV3.Server
builder.Services.AddAuthorizationBuilder().AddPolicy("NotBanned", policy => policy.Requirements.Add(new NotBannedRequirement())); builder.Services.AddAuthorizationBuilder().AddPolicy("NotBanned", policy => policy.Requirements.Add(new NotBannedRequirement()));
builder.Services.AddAuthorizationBuilder().AddPolicy("AuthAndNotBanned", policy => policy.Requirements.Add(new NotBannedRequirement())); builder.Services.AddAuthorizationBuilder().AddPolicy("AuthAndNotBanned", policy => policy.Requirements.Add(new NotBannedRequirement()));
builder
.Services.AddAuthorizationBuilder()
.AddPolicy(
"JwtOnly",
policy =>
{
policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
policy.RequireAuthenticatedUser();
}
);
builder
.Services.AddAuthorizationBuilder()
.AddPolicy(
"JwtOnlyAndNotBanned",
policy =>
{
policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
policy.RequireAuthenticatedUser();
policy.Requirements.Add(new NotBannedRequirement());
}
);
builder.Services.AddSingleton<IAuthorizationHandler>(new NotBannedHandler(false)); builder.Services.AddSingleton<IAuthorizationHandler>(new NotBannedHandler(false));
builder.Services.AddSingleton<IAuthorizationHandler>(new NotBannedHandler(true)); builder.Services.AddSingleton<IAuthorizationHandler>(new NotBannedHandler(true));
@@ -0,0 +1,74 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.Settings;
namespace SharpbinV3.Server.Services
{
public sealed class ApiKeyService(AppDbContext db, IOptions<AuthSettings> authOptions)
{
private readonly AppDbContext _db = db;
private readonly AuthSettings _authSettings = authOptions.Value;
public const int KeyLength = 64;
private string ComputeHash(string input)
{
if (string.IsNullOrEmpty(_authSettings.API_Key_HMAC_Secret))
return Utilities.ComputeSha256(input);
else
return Utilities.ComputeHmacSha256(input, _authSettings.API_Key_HMAC_Secret);
}
public async Task<ApiKey?> GetByKeyAsync(string key)
{
var keyHash = ComputeHash(key);
return await _db.ApiKeys.Include(a => a.User).FirstOrDefaultAsync(a => a.KeyHash == keyHash);
}
public async Task<(ApiKey apiKey, string key)> CreateAsync(Guid userUUID, string name)
{
var key = Utilities.GenerateSecureRandomString(KeyLength);
var keyHash = ComputeHash(key);
var apiKey = new ApiKey
{
UserUUID = userUUID,
Name = name,
KeyHash = keyHash,
};
_db.ApiKeys.Add(apiKey);
await _db.SaveChangesAsync();
return (apiKey, key);
}
public async Task<bool> DeleteAsync(Guid userUUID, Guid keyUUID)
{
var apiKey = await _db.ApiKeys.FirstOrDefaultAsync(a => a.UUID == keyUUID && a.UserUUID == userUUID);
if (apiKey == null)
return false;
_db.ApiKeys.Remove(apiKey);
await _db.SaveChangesAsync();
return true;
}
public async Task<List<ApiKey>> GetUserKeysAsync(Guid userUUID)
{
return await _db.ApiKeys.Where(a => a.UserUUID == userUUID).OrderByDescending(a => a.CreatedAt).ToListAsync();
}
public async Task UpdateLastUsedAsync(Guid keyUUID)
{
var apiKey = await _db.ApiKeys.FirstOrDefaultAsync(a => a.UUID == keyUUID);
if (apiKey == null)
return;
apiKey.LastUsedAt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
await _db.SaveChangesAsync();
}
}
}
+6 -1
View File
@@ -7,6 +7,7 @@ using Microsoft.IdentityModel.Tokens;
using SharpbinV3.Server.Data; using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities; using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.DTOs.Auth; using SharpbinV3.Server.DTOs.Auth;
using SharpbinV3.Server.Extensions;
using SharpbinV3.Server.Settings; using SharpbinV3.Server.Settings;
using Bcrypt = BCrypt.Net.BCrypt; using Bcrypt = BCrypt.Net.BCrypt;
@@ -91,7 +92,7 @@ namespace SharpbinV3.Server.Services
var jwtToken = jwtHandler.WriteToken(token); var jwtToken = jwtHandler.WriteToken(token);
var jti = claims.First(c => c.Type == JwtRegisteredClaimNames.Jti).Value; var jti = claims.First(c => c.Type == JwtRegisteredClaimNames.Jti).Value;
var rawRefreshToken = Utilities.GenerateRandomString(36) + Guid.NewGuid(); var rawRefreshToken = Utilities.GenerateSecureRandomString(36) + Guid.NewGuid();
var refreshToken = new RefreshToken var refreshToken = new RefreshToken
{ {
Id = Guid.NewGuid(), Id = Guid.NewGuid(),
@@ -201,6 +202,10 @@ namespace SharpbinV3.Server.Services
public async Task<User?> GetUserFromHttpContext(HttpContext context) public async Task<User?> GetUserFromHttpContext(HttpContext context)
{ {
var apiKey = context.GetApiKeyFromContext();
if (apiKey != null)
return await _db.Users.FirstOrDefaultAsync(u => u.UUID == apiKey.UserUUID);
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;
+1 -1
View File
@@ -35,7 +35,7 @@ namespace SharpbinV3.Server.Services
var paste = new Paste var paste = new Paste
{ {
UUID = Guid.CreateVersion7(), UUID = Guid.CreateVersion7(),
ID = Utilities.GenerateRandomString(8), ID = Utilities.GenerateSecureRandomString(8),
Title = title, Title = title,
AuthorUUID = author?.UUID, AuthorUUID = author?.UUID,
User = author, User = author,
@@ -7,5 +7,6 @@
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; public bool Admins_Require_2FA { get; set; } = true;
public string API_Key_HMAC_Secret { get; set; } = string.Empty;
} }
} }
+26
View File
@@ -11,6 +11,32 @@ namespace SharpbinV3.Server
return new string([.. Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)])]); return new string([.. Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)])]);
} }
public static string GenerateSecureRandomString(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Span<byte> buffer = stackalloc byte[128];
var result = new char[length];
int pos = 0;
while (pos < length)
{
RandomNumberGenerator.Fill(buffer);
foreach (byte b in buffer)
{
if (b >= 248)
continue; // 248 is the largest multiple of 62 < 256
result[pos++] = chars[b % chars.Length];
if (pos == length)
break;
}
}
return new string(result);
}
public static string ComputeSha256(string input) public static string ComputeSha256(string input)
{ {
var inputBytes = System.Text.Encoding.UTF8.GetBytes(input); var inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
+7
View File
@@ -8,6 +8,13 @@
"csharpier" "csharpier"
], ],
"rollForward": false "rollForward": false
},
"dotnet-ef": {
"version": "10.0.3",
"commands": [
"dotnet-ef"
],
"rollForward": false
} }
} }
} }