mirror of
https://github.com/whoswhip/Sharpbin.git
synced 2026-12-06 02:48:43 +00:00
feat: password resets
fix: frontend docker file chore: format via csharpier again
This commit is contained in:
@@ -14,7 +14,11 @@ ENV NODE_ENV=production
|
||||
ENV HOST=0.0.0.0
|
||||
ENV PORT=5173
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci --omit=dev --ignore-scripts && apk add --no-cache wget
|
||||
RUN apk add --no-cache wget libstdc++ \
|
||||
&& apk add --no-cache --virtual .build-deps python3 make g++ \
|
||||
&& npm ci --omit=dev \
|
||||
&& npm cache clean --force \
|
||||
&& apk del .build-deps
|
||||
COPY --from=build --chown=node:node /app/build ./build
|
||||
RUN chown -R node:node /app
|
||||
EXPOSE 5173
|
||||
|
||||
@@ -7,6 +7,7 @@ export interface User {
|
||||
username: string;
|
||||
displayName: string | null;
|
||||
email: string | null;
|
||||
emailVerified: boolean;
|
||||
lastLogin: number | null;
|
||||
roles: number; // bitfield; 5 = User | Admin
|
||||
isBanned: boolean;
|
||||
|
||||
@@ -98,7 +98,7 @@
|
||||
|
||||
<svelte:head>
|
||||
<link rel="icon" href={favicon} />
|
||||
{#if data.options?.cf_turnstile_site_key && (page.url.pathname === '/login' || page.url.pathname === '/register' || page.url.pathname === '/')}
|
||||
{#if data.options?.cf_turnstile_site_key && (page.url.pathname === '/login' || page.url.pathname === '/register' || page.url.pathname === '/' || page.url.pathname === '/forgot-password')}
|
||||
<script
|
||||
src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit&onload=turnstileLoaded"
|
||||
async
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
<script lang="ts">
|
||||
import { resolve } from '$app/paths';
|
||||
import { extractError } from '$lib/utils/misc';
|
||||
import { onMount } from 'svelte';
|
||||
import type { PageData } from './$types';
|
||||
|
||||
let email = $state('');
|
||||
let error = $state('');
|
||||
let message = $state('');
|
||||
|
||||
interface Props {
|
||||
data: PageData;
|
||||
}
|
||||
|
||||
let { data }: Props = $props();
|
||||
|
||||
onMount(() => {
|
||||
const render = () => {
|
||||
if (window.turnstile && data.options?.cf_turnstile_site_key) {
|
||||
window.turnstile.render('.cf-turnstile', {
|
||||
sitekey: data.options.cf_turnstile_site_key,
|
||||
theme: 'dark',
|
||||
size: 'flexible',
|
||||
appearence: 'interaction-only'
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
if (window.turnstile) {
|
||||
render();
|
||||
} else {
|
||||
window.addEventListener('turnstile:loaded', render, { once: true });
|
||||
}
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('turnstile:loaded', render);
|
||||
};
|
||||
});
|
||||
|
||||
async function submit(event: Event) {
|
||||
event.preventDefault();
|
||||
error = '';
|
||||
message = '';
|
||||
|
||||
const body: { email: string; token?: string } = { email };
|
||||
if (data.options?.cf_turnstile_site_key && window.turnstile) {
|
||||
const token = window.turnstile.getResponse();
|
||||
if (token) body.token = token;
|
||||
}
|
||||
|
||||
const res = await fetch('/api/auth/password/forgot', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body)
|
||||
});
|
||||
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
if (window.turnstile) window.turnstile.reset();
|
||||
error = extractError(json) || 'Request failed.';
|
||||
return;
|
||||
}
|
||||
|
||||
if (window.turnstile) window.turnstile.reset();
|
||||
message = json.message || 'If an account exists for that email, a reset link has been sent.';
|
||||
email = '';
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<title>Forgot Password - Sharpbin</title>
|
||||
<meta name="description" content="Request a password reset link for your Sharpbin account." />
|
||||
</svelte:head>
|
||||
|
||||
<main
|
||||
class="flex min-h-[calc(100vh-120px)] 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">
|
||||
<h1 class="mb-2 text-center text-3xl font-bold">Forgot Password</h1>
|
||||
<p class="mb-6 text-center text-sm text-neutral-400">
|
||||
Enter the email address on your account and we’ll send a reset link if one exists.
|
||||
</p>
|
||||
<form onsubmit={submit} class="space-y-4">
|
||||
<input
|
||||
type="email"
|
||||
placeholder="Email"
|
||||
bind:value={email}
|
||||
autocomplete="email"
|
||||
required
|
||||
class="focus:bg-neutral-750 w-full rounded border border-neutral-700 bg-neutral-800 p-2 placeholder-neutral-500 transition-colors duration-200 focus:border-neutral-600"
|
||||
/>
|
||||
{#if data.options?.cf_turnstile_site_key}
|
||||
<div class="cf-turnstile w-full"></div>
|
||||
{/if}
|
||||
<button
|
||||
type="submit"
|
||||
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"
|
||||
>
|
||||
Send Reset Link
|
||||
</button>
|
||||
{#if error}
|
||||
<div
|
||||
class="rounded border border-red-900 bg-red-950 p-2 text-sm whitespace-pre-line text-red-200"
|
||||
>
|
||||
{error}
|
||||
</div>
|
||||
{/if}
|
||||
{#if message}
|
||||
<div
|
||||
class="rounded border border-green-900 bg-green-950 p-2 text-sm whitespace-pre-line text-green-200"
|
||||
>
|
||||
{message}
|
||||
</div>
|
||||
{/if}
|
||||
</form>
|
||||
<p class="mt-4 text-center text-sm text-neutral-400">
|
||||
<a
|
||||
href={resolve('/login')}
|
||||
class="text-neutral-200 transition-colors duration-200 hover:text-white">Back to login</a
|
||||
>
|
||||
</p>
|
||||
</div>
|
||||
</main>
|
||||
@@ -159,5 +159,11 @@
|
||||
class="text-neutral-200 transition-colors duration-200 hover:text-white">Register</a
|
||||
>
|
||||
</p>
|
||||
<p class="mt-2 text-center text-sm text-neutral-400">
|
||||
<a
|
||||
href={resolve('/forgot-password')}
|
||||
class="text-neutral-200 transition-colors duration-200 hover:text-white">Forgot password?</a
|
||||
>
|
||||
</p>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { apiUrl } from '$lib/server/api';
|
||||
import { extractError } from '$lib/utils/misc';
|
||||
import { error } from '@sveltejs/kit';
|
||||
import type { PageServerLoad } from './$types';
|
||||
|
||||
export const load: PageServerLoad = async ({ url, request }) => {
|
||||
const token = url.searchParams.get('token');
|
||||
if (!token) {
|
||||
throw error(400, 'Reset token is required.');
|
||||
}
|
||||
|
||||
const headers = new Headers(request.headers);
|
||||
const res = await fetch(`${apiUrl}/api/auth/password/reset-info?token=${token}`, { headers });
|
||||
const json = await res.json().catch(() => null);
|
||||
if (!res.ok) {
|
||||
const message = extractError(json);
|
||||
throw error(res.status, message ?? 'Request failed');
|
||||
}
|
||||
|
||||
return {
|
||||
token,
|
||||
username: typeof json?.username === 'string' ? json.username : undefined,
|
||||
requiresTotp: Boolean(json?.requiresTotp)
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,231 @@
|
||||
<script lang="ts">
|
||||
import { resolve } from '$app/paths';
|
||||
import { extractError } from '$lib/utils/misc';
|
||||
import { Check, X } from '@lucide/svelte';
|
||||
import { slide, fade } from 'svelte/transition';
|
||||
import type { PageData } from './$types';
|
||||
|
||||
interface Props {
|
||||
data: PageData;
|
||||
}
|
||||
|
||||
let { data }: Props = $props();
|
||||
let password = $state('');
|
||||
let confirmPassword = $state('');
|
||||
let totpCode = $state('');
|
||||
let error = $state('');
|
||||
let message = $state('');
|
||||
let complete = $state(false);
|
||||
let loading = $state(false);
|
||||
let passwordFocused = $state(false);
|
||||
let passwordChecks = $state({
|
||||
minLength: false,
|
||||
maxLength: false,
|
||||
upper: false,
|
||||
lower: false,
|
||||
number: false
|
||||
});
|
||||
let passwordValid = $state(false);
|
||||
|
||||
function validatePassword(pw: string) {
|
||||
passwordChecks.minLength = pw.length >= 8;
|
||||
passwordChecks.maxLength = pw.length <= 128;
|
||||
passwordChecks.upper = /[A-Z]/.test(pw);
|
||||
passwordChecks.lower = /[a-z]/.test(pw);
|
||||
passwordChecks.number = /[0-9]/.test(pw);
|
||||
passwordValid =
|
||||
passwordChecks.minLength &&
|
||||
passwordChecks.maxLength &&
|
||||
passwordChecks.upper &&
|
||||
passwordChecks.lower &&
|
||||
passwordChecks.number;
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
validatePassword(password);
|
||||
});
|
||||
|
||||
async function submit(event: Event) {
|
||||
event.preventDefault();
|
||||
error = '';
|
||||
message = '';
|
||||
|
||||
if (!password || !confirmPassword) {
|
||||
error = 'Both password fields are required.';
|
||||
return;
|
||||
}
|
||||
if (password !== confirmPassword) {
|
||||
error = 'Passwords do not match.';
|
||||
return;
|
||||
}
|
||||
if (!passwordValid) {
|
||||
error =
|
||||
'Password should have at least 8 characters, no more than 128 characters, including uppercase, lowercase, and digits.';
|
||||
return;
|
||||
}
|
||||
|
||||
loading = true;
|
||||
try {
|
||||
const res = await fetch('/api/auth/password/reset', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
token: data.token,
|
||||
newPassword: password,
|
||||
...(data.requiresTotp ? { totpCode } : {})
|
||||
})
|
||||
});
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
error = extractError(json) || 'Password reset failed.';
|
||||
return;
|
||||
}
|
||||
complete = true;
|
||||
message = json.message || 'Password reset successfully.';
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<title>Reset Password - Sharpbin</title>
|
||||
<meta name="description" content="Set a new password for your Sharpbin account." />
|
||||
</svelte:head>
|
||||
|
||||
<main
|
||||
class="flex min-h-[calc(100vh-120px)] 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">
|
||||
{#if complete}
|
||||
<h1 class="mb-2 text-center text-3xl font-bold">Password Reset</h1>
|
||||
<p class="text-center text-sm text-neutral-400">{message}</p>
|
||||
<p class="mt-4 text-center text-sm text-neutral-400">
|
||||
<a
|
||||
href={resolve('/login')}
|
||||
class="text-neutral-200 transition-colors duration-200 hover:text-white">Back to login</a
|
||||
>
|
||||
</p>
|
||||
{:else}
|
||||
<h1 class="mb-2 text-center text-3xl font-bold">Reset Password</h1>
|
||||
<p class="mb-6 text-center text-sm text-neutral-400">
|
||||
{#if data.username}
|
||||
Reset the password for {data.username}.
|
||||
{:else}
|
||||
Set a new password for your account.
|
||||
{/if}
|
||||
</p>
|
||||
<form onsubmit={submit} class="space-y-4">
|
||||
<input
|
||||
type="password"
|
||||
placeholder="New password"
|
||||
bind:value={password}
|
||||
autocomplete="new-password"
|
||||
required
|
||||
onfocus={() => (passwordFocused = true)}
|
||||
onblur={() => (passwordFocused = false)}
|
||||
class="focus:bg-neutral-750 w-full rounded border border-neutral-700 bg-neutral-800 p-2 placeholder-neutral-500 transition-colors duration-200 focus:border-neutral-600"
|
||||
/>
|
||||
{#if passwordFocused}
|
||||
<ul
|
||||
transition:slide
|
||||
class="space-y-2 rounded border border-neutral-700 bg-neutral-800 p-3 text-sm"
|
||||
>
|
||||
<li
|
||||
class="flex items-center gap-2 {passwordChecks.minLength
|
||||
? 'text-green-400'
|
||||
: 'text-red-400'}"
|
||||
>
|
||||
{#if passwordChecks.minLength}<Check class="h-4 w-4" />{:else}<X
|
||||
class="h-4 w-4"
|
||||
/>{/if}
|
||||
At least 8 characters
|
||||
</li>
|
||||
<li
|
||||
class="flex items-center gap-2 {passwordChecks.maxLength
|
||||
? 'text-green-400'
|
||||
: 'text-red-400'}"
|
||||
>
|
||||
{#if passwordChecks.maxLength}<Check class="h-4 w-4" />{:else}<X
|
||||
class="h-4 w-4"
|
||||
/>{/if}
|
||||
No more than 128 characters
|
||||
</li>
|
||||
<li
|
||||
class="flex items-center gap-2 {passwordChecks.upper
|
||||
? 'text-green-400'
|
||||
: 'text-red-400'}"
|
||||
>
|
||||
{#if passwordChecks.upper}<Check class="h-4 w-4" />{:else}<X class="h-4 w-4" />{/if}
|
||||
At least one uppercase letter
|
||||
</li>
|
||||
<li
|
||||
class="flex items-center gap-2 {passwordChecks.lower
|
||||
? 'text-green-400'
|
||||
: 'text-red-400'}"
|
||||
>
|
||||
{#if passwordChecks.lower}<Check class="h-4 w-4" />{:else}<X class="h-4 w-4" />{/if}
|
||||
At least one lowercase letter
|
||||
</li>
|
||||
<li
|
||||
class="flex items-center gap-2 {passwordChecks.number
|
||||
? 'text-green-400'
|
||||
: 'text-red-400'}"
|
||||
>
|
||||
{#if passwordChecks.number}<Check class="h-4 w-4" />{:else}<X class="h-4 w-4" />{/if}
|
||||
At least one number
|
||||
</li>
|
||||
</ul>
|
||||
{/if}
|
||||
<input
|
||||
type="password"
|
||||
placeholder="Confirm new password"
|
||||
bind:value={confirmPassword}
|
||||
autocomplete="new-password"
|
||||
required
|
||||
class="focus:bg-neutral-750 w-full rounded border border-neutral-700 bg-neutral-800 p-2 placeholder-neutral-500 transition-colors duration-200 focus:border-neutral-600"
|
||||
/>
|
||||
{#if confirmPassword && password !== confirmPassword}
|
||||
<div
|
||||
transition:fade
|
||||
class="rounded border border-red-900 bg-red-950 p-2 text-sm text-red-200"
|
||||
>
|
||||
Passwords do not match.
|
||||
</div>
|
||||
{/if}
|
||||
{#if data.requiresTotp}
|
||||
<input
|
||||
type="text"
|
||||
placeholder="TOTP Code"
|
||||
bind:value={totpCode}
|
||||
maxlength="6"
|
||||
inputmode="numeric"
|
||||
pattern="[0-9]*"
|
||||
required
|
||||
oninput={(e) => {
|
||||
if (e.target instanceof HTMLInputElement) {
|
||||
e.target.value = e.target.value.replace(/\D/g, '').slice(0, 6);
|
||||
totpCode = e.target.value;
|
||||
}
|
||||
}}
|
||||
class="focus:bg-neutral-750 w-full rounded border border-neutral-700 bg-neutral-800 p-2 placeholder-neutral-500 transition-colors duration-200 focus:border-neutral-600"
|
||||
/>
|
||||
{/if}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading || !passwordValid || password !== confirmPassword}
|
||||
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:opacity-50"
|
||||
>
|
||||
{loading ? 'Updating...' : 'Reset Password'}
|
||||
</button>
|
||||
{#if error}
|
||||
<div
|
||||
class="rounded border border-red-900 bg-red-950 p-2 text-sm whitespace-pre-line text-red-200"
|
||||
>
|
||||
{error}
|
||||
</div>
|
||||
{/if}
|
||||
</form>
|
||||
{/if}
|
||||
</div>
|
||||
</main>
|
||||
@@ -14,6 +14,7 @@
|
||||
Ban,
|
||||
AtSign,
|
||||
Pencil,
|
||||
KeyRound,
|
||||
Trash2,
|
||||
Clock,
|
||||
Hash,
|
||||
@@ -30,7 +31,7 @@
|
||||
dateToRelativeString,
|
||||
extractError
|
||||
} from '$lib/utils/misc';
|
||||
import { getToken, hasRole, roles } from '$lib/utils/auth';
|
||||
import { clearTokens, getToken, hasRole, roles } from '$lib/utils/auth';
|
||||
import { openModal } from '$lib/stores/modal';
|
||||
import { user } from '$lib/stores/user';
|
||||
import { onMount } from 'svelte';
|
||||
@@ -64,6 +65,30 @@
|
||||
let interval: ReturnType<typeof setInterval> | null = null;
|
||||
let isEditingDisplayName = $state(false);
|
||||
let editDisplayNameValue = $state('');
|
||||
let isEditingEmail = $state(false);
|
||||
let editEmailValue = $state('');
|
||||
let emailActionLoading = $state(false);
|
||||
let emailMessage = $state('');
|
||||
let emailError = $state('');
|
||||
let passwordCurrentValue = $state('');
|
||||
let passwordNewValue = $state('');
|
||||
let passwordConfirmValue = $state('');
|
||||
let passwordFocused = $state(false);
|
||||
let passwordChecks = $state({
|
||||
minLength: false,
|
||||
maxLength: false,
|
||||
upper: false,
|
||||
lower: false,
|
||||
number: false
|
||||
});
|
||||
let passwordValid = $state(false);
|
||||
let passwordActionLoading = $state(false);
|
||||
let passwordMessage = $state('');
|
||||
let passwordError = $state('');
|
||||
let passwordResetLinkValue = $state('');
|
||||
let passwordResetLinkLoading = $state(false);
|
||||
let passwordResetLinkMessage = $state('');
|
||||
let passwordResetLinkError = $state('');
|
||||
|
||||
let apiKeys: { uuid: string; name: string; createdAt: string; lastUsedAt: string | null }[] =
|
||||
$state([]);
|
||||
@@ -76,6 +101,12 @@
|
||||
|
||||
let reportsSubmitted = $derived(data.reportsSubmitted);
|
||||
let reportsTarget = $derived(data.reportsTarget);
|
||||
let adminsRequire2FA = $derived(
|
||||
Boolean(
|
||||
(data as unknown as { authOptions?: { admins_require_2fa?: boolean } }).authOptions
|
||||
?.admins_require_2fa
|
||||
)
|
||||
);
|
||||
|
||||
let activeTab: 'pastes' | 'reportsSubmitted' | 'reportsTarget' | 'settings' = $state('pastes');
|
||||
let activeSubTab:
|
||||
@@ -184,7 +215,7 @@
|
||||
message?: string;
|
||||
};
|
||||
|
||||
type SecurityAction = 'UpdateRoles' | 'DeleteUser';
|
||||
type SecurityAction = 'UpdateRoles' | 'DeleteUser' | 'GeneratePasswordResetLink';
|
||||
|
||||
async function fetchActionSecurityRequirements(action: SecurityAction) {
|
||||
const token = getToken();
|
||||
@@ -248,6 +279,24 @@
|
||||
).trim();
|
||||
}
|
||||
|
||||
function validatePassword(pw: string) {
|
||||
passwordChecks.minLength = pw.length >= 8;
|
||||
passwordChecks.maxLength = pw.length <= 128;
|
||||
passwordChecks.upper = /[A-Z]/.test(pw);
|
||||
passwordChecks.lower = /[a-z]/.test(pw);
|
||||
passwordChecks.number = /[0-9]/.test(pw);
|
||||
passwordValid =
|
||||
passwordChecks.minLength &&
|
||||
passwordChecks.maxLength &&
|
||||
passwordChecks.upper &&
|
||||
passwordChecks.lower &&
|
||||
passwordChecks.number;
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
validatePassword(passwordNewValue);
|
||||
});
|
||||
|
||||
async function fetchPage(pageNum: number) {
|
||||
if (pageNum < 1 || pageNum > (pagination.totalPages || 1) || loading) return;
|
||||
loading = true;
|
||||
@@ -305,11 +354,182 @@
|
||||
modalError = '';
|
||||
}
|
||||
|
||||
async function changeEmail() {
|
||||
const email = editEmailValue.trim();
|
||||
if (!email) return;
|
||||
let totpcode = '';
|
||||
if (totpEnabled) {
|
||||
totpcode = await promptTotpCode('TOTP required to change email', 'Continue');
|
||||
if (!totpcode) return;
|
||||
}
|
||||
emailActionLoading = true;
|
||||
emailMessage = '';
|
||||
emailError = '';
|
||||
const token = getToken();
|
||||
try {
|
||||
const res = await fetch('/api/auth/email/change', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify({
|
||||
email,
|
||||
...(totpcode ? { totpcode } : {})
|
||||
})
|
||||
});
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
emailError = extractError(json) || 'Failed to send verification email.';
|
||||
return;
|
||||
}
|
||||
emailMessage = json.message || 'Verification email sent.';
|
||||
isEditingEmail = false;
|
||||
editEmailValue = '';
|
||||
} catch {
|
||||
emailError = 'Network error';
|
||||
} finally {
|
||||
emailActionLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function changePassword() {
|
||||
passwordMessage = '';
|
||||
passwordError = '';
|
||||
const currentPassword = passwordCurrentValue;
|
||||
const newPassword = passwordNewValue;
|
||||
const confirmPassword = passwordConfirmValue;
|
||||
if (!currentPassword || !newPassword || !confirmPassword) {
|
||||
passwordError = 'Current password, new password, and confirmation are required.';
|
||||
return;
|
||||
}
|
||||
if (newPassword !== confirmPassword) {
|
||||
passwordError = 'New passwords do not match.';
|
||||
return;
|
||||
}
|
||||
if (!passwordValid) {
|
||||
passwordError =
|
||||
'Password should have at least 8 characters, no more than 128 characters, including uppercase, lowercase, and digits.';
|
||||
return;
|
||||
}
|
||||
let totpcode = '';
|
||||
if (totpEnabled || adminsRequire2FA) {
|
||||
if (adminsRequire2FA && !totpEnabled) {
|
||||
passwordError = '2FA is required to perform this action.';
|
||||
return;
|
||||
}
|
||||
totpcode = await promptTotpCode('TOTP required to change password', 'Continue');
|
||||
if (!totpcode) return;
|
||||
}
|
||||
passwordActionLoading = true;
|
||||
const token = getToken();
|
||||
try {
|
||||
const res = await fetch('/api/auth/password/change', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify({
|
||||
currentPassword,
|
||||
newPassword,
|
||||
...(totpcode ? { totpCode: totpcode } : {})
|
||||
})
|
||||
});
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
passwordError = extractError(json) || 'Failed to change password.';
|
||||
return;
|
||||
}
|
||||
clearTokens();
|
||||
window.location.href = '/login';
|
||||
} catch {
|
||||
passwordError = 'Network error';
|
||||
} finally {
|
||||
passwordActionLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function generatePasswordResetLink() {
|
||||
passwordResetLinkMessage = '';
|
||||
passwordResetLinkError = '';
|
||||
const token = getToken();
|
||||
if (!token || !data.user?.uuid) return;
|
||||
|
||||
try {
|
||||
const requirements = await fetchActionSecurityRequirements('GeneratePasswordResetLink');
|
||||
if (requirements.blocked) {
|
||||
passwordResetLinkError =
|
||||
requirements.message || 'You cannot perform this action right now.';
|
||||
return;
|
||||
}
|
||||
let totpcode = '';
|
||||
if (requirements.requiresTotp) {
|
||||
totpcode = await promptTotpCode('TOTP required to generate reset link', 'Continue');
|
||||
if (!totpcode) return;
|
||||
}
|
||||
|
||||
passwordResetLinkLoading = true;
|
||||
const res = await fetch(`/api/auth/password/admin-reset-link/${data.user.uuid}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify({
|
||||
...(totpcode ? { totpCode: totpcode } : {})
|
||||
})
|
||||
});
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
passwordResetLinkError = extractError(json) || 'Failed to generate password reset link.';
|
||||
return;
|
||||
}
|
||||
passwordResetLinkValue = json.resetLink || '';
|
||||
passwordResetLinkMessage = json.message || 'Password reset link generated.';
|
||||
} catch {
|
||||
passwordResetLinkError = 'Network error';
|
||||
} finally {
|
||||
passwordResetLinkLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function resendVerificationEmail() {
|
||||
emailActionLoading = true;
|
||||
emailMessage = '';
|
||||
emailError = '';
|
||||
const token = getToken();
|
||||
try {
|
||||
const res = await fetch('/api/auth/email/resend-verification', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
});
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
emailError = extractError(json) || 'Failed to resend verification email.';
|
||||
return;
|
||||
}
|
||||
emailMessage = json.message || 'Verification email sent.';
|
||||
} catch {
|
||||
emailError = 'Network error';
|
||||
} finally {
|
||||
emailActionLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
function startEditEmail() {
|
||||
editEmailValue = data.user?.email || '';
|
||||
isEditingEmail = true;
|
||||
emailMessage = '';
|
||||
emailError = '';
|
||||
}
|
||||
|
||||
async function handleDeleteAccount() {
|
||||
loading = true;
|
||||
modalError = '';
|
||||
const token = getToken();
|
||||
let totpcode = '';
|
||||
let verificationToken = '';
|
||||
if (totpEnabled) {
|
||||
totpcode = String(
|
||||
await openModal<string>({
|
||||
@@ -325,6 +545,42 @@
|
||||
loading = false;
|
||||
return;
|
||||
}
|
||||
} else if (isOwner && data.user?.emailVerified && data.user?.email) {
|
||||
const requestRes = await fetch(`/api/user/uuid/${data.user?.uuid}/delete-verification`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`
|
||||
}
|
||||
});
|
||||
if (!requestRes.ok) {
|
||||
const err = await requestRes.json().catch(() => ({}));
|
||||
loading = false;
|
||||
modalError = extractError(err) || 'Failed to send account deletion verification email.';
|
||||
await openModal({
|
||||
mode: 'confirm',
|
||||
title: 'Error',
|
||||
message: modalError,
|
||||
confirmButtonText: 'OK',
|
||||
cancelValue: true
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
verificationToken = String(
|
||||
await openModal<string>({
|
||||
mode: 'prompt',
|
||||
title: 'Verify Account Deletion',
|
||||
message: 'Enter the account deletion code sent to your verified email.',
|
||||
placeholder: 'Deletion code',
|
||||
inputType: 'text',
|
||||
confirmButtonText: 'Delete Account',
|
||||
cancelValue: ''
|
||||
})
|
||||
).trim();
|
||||
if (!verificationToken) {
|
||||
loading = false;
|
||||
return;
|
||||
}
|
||||
}
|
||||
const res = await fetch(`/api/user/uuid/${data.user?.uuid}`, {
|
||||
method: 'DELETE',
|
||||
@@ -332,7 +588,12 @@
|
||||
Authorization: `Bearer ${token}`,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: totpEnabled && totpcode ? JSON.stringify({ totpcode }) : undefined
|
||||
body:
|
||||
totpEnabled && totpcode
|
||||
? JSON.stringify({ totpcode })
|
||||
: verificationToken
|
||||
? JSON.stringify({ token: verificationToken })
|
||||
: undefined
|
||||
});
|
||||
loading = false;
|
||||
if (!res.ok) {
|
||||
@@ -347,6 +608,10 @@
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (isOwner) {
|
||||
clearTokens();
|
||||
user.set(null);
|
||||
}
|
||||
window.location.href = '/';
|
||||
}
|
||||
|
||||
@@ -847,6 +1112,117 @@
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{#if isOwner}
|
||||
<div class="col-span-2">
|
||||
<h2 class="text-xl font-semibold text-neutral-100">Email</h2>
|
||||
<p class="mb-1 text-sm text-neutral-400">
|
||||
Used for account verification and security notifications.
|
||||
</p>
|
||||
|
||||
{#if emailError}
|
||||
<div
|
||||
class="mb-3 rounded border border-red-900/50 bg-red-900/10 p-3 text-sm text-red-200"
|
||||
>
|
||||
{emailError}
|
||||
</div>
|
||||
{/if}
|
||||
{#if emailMessage}
|
||||
<div
|
||||
class="mb-3 rounded border border-green-900/50 bg-green-900/10 p-3 text-sm text-green-200"
|
||||
>
|
||||
{emailMessage}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="rounded bg-neutral-800/50 p-3">
|
||||
{#if isEditingEmail}
|
||||
<div class="flex flex-col gap-3 sm:flex-row sm:items-center">
|
||||
<input
|
||||
type="email"
|
||||
bind:value={editEmailValue}
|
||||
placeholder="you@example.com"
|
||||
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"
|
||||
autocomplete="email"
|
||||
onkeydown={(e) => {
|
||||
if (e.key === 'Enter') changeEmail();
|
||||
else if (e.key === 'Escape') {
|
||||
isEditingEmail = false;
|
||||
editEmailValue = '';
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<div class="flex shrink-0 gap-2">
|
||||
<button
|
||||
onclick={changeEmail}
|
||||
disabled={emailActionLoading || !editEmailValue.trim()}
|
||||
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 disabled:opacity-50"
|
||||
>
|
||||
{#if emailActionLoading}
|
||||
<LoaderCircle class="h-4 w-4 animate-spin" />
|
||||
{:else}
|
||||
<Check class="h-4 w-4" />
|
||||
{/if}
|
||||
Send verification
|
||||
</button>
|
||||
<button
|
||||
onclick={() => {
|
||||
isEditingEmail = false;
|
||||
editEmailValue = '';
|
||||
}}
|
||||
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>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div class="flex min-w-0 flex-col gap-1">
|
||||
<span class="font-mono break-all text-neutral-300">
|
||||
{data.user?.email || 'No email set'}
|
||||
</span>
|
||||
<span
|
||||
class="text-sm {data.user?.emailVerified
|
||||
? 'text-green-400'
|
||||
: 'text-amber-400'}"
|
||||
>
|
||||
{data.user?.email
|
||||
? data.user?.emailVerified
|
||||
? 'Verified'
|
||||
: 'Not verified'
|
||||
: 'Add an email to enable verification'}
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
{#if data.user?.email && !data.user?.emailVerified}
|
||||
<button
|
||||
onclick={resendVerificationEmail}
|
||||
disabled={emailActionLoading}
|
||||
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 emailActionLoading}
|
||||
<LoaderCircle class="h-4 w-4 animate-spin" />
|
||||
{:else}
|
||||
<Check class="h-4 w-4" />
|
||||
{/if}
|
||||
Resend
|
||||
</button>
|
||||
{/if}
|
||||
<button
|
||||
onclick={startEditEmail}
|
||||
disabled={emailActionLoading}
|
||||
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"
|
||||
>
|
||||
<Pencil class="h-4 w-4" />
|
||||
{data.user?.email ? 'Change' : 'Add'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
{:else if isOwner && activeSubTab === 'settings:security'}
|
||||
<div class="col-span-2">
|
||||
<div class="space-y-4">
|
||||
@@ -864,6 +1240,138 @@
|
||||
{totpEnabled ? 'Manage' : 'Enable'}
|
||||
</button>
|
||||
</div>
|
||||
<div class="rounded bg-neutral-800/50 p-4">
|
||||
<div class="mb-3 flex flex-col gap-1">
|
||||
<span class="font-medium text-neutral-200">Change Password</span>
|
||||
<span class="text-sm text-neutral-500">
|
||||
Use your current password and choose a new one.
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{#if passwordError}
|
||||
<div
|
||||
class="mb-3 rounded border border-red-900/50 bg-red-900/10 p-3 text-sm text-red-200"
|
||||
>
|
||||
{passwordError}
|
||||
</div>
|
||||
{/if}
|
||||
{#if passwordMessage}
|
||||
<div
|
||||
class="mb-3 rounded border border-green-900/50 bg-green-900/10 p-3 text-sm text-green-200"
|
||||
>
|
||||
{passwordMessage}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="grid gap-3">
|
||||
<input
|
||||
type="password"
|
||||
bind:value={passwordCurrentValue}
|
||||
placeholder="Current password"
|
||||
autocomplete="current-password"
|
||||
class="w-full rounded border border-neutral-700 bg-neutral-900 px-3 py-2 text-neutral-200 transition-colors outline-none focus:border-neutral-500"
|
||||
/>
|
||||
<input
|
||||
type="password"
|
||||
bind:value={passwordNewValue}
|
||||
placeholder="New password"
|
||||
autocomplete="new-password"
|
||||
onfocus={() => (passwordFocused = true)}
|
||||
onblur={() => (passwordFocused = false)}
|
||||
class="w-full rounded border border-neutral-700 bg-neutral-900 px-3 py-2 text-neutral-200 transition-colors outline-none focus:border-neutral-500"
|
||||
/>
|
||||
{#if passwordFocused}
|
||||
<ul
|
||||
transition:fade
|
||||
class="space-y-2 rounded border border-neutral-700 bg-neutral-800 p-3 text-sm"
|
||||
>
|
||||
<li
|
||||
class="flex items-center gap-2 {passwordChecks.minLength
|
||||
? 'text-green-400'
|
||||
: 'text-red-400'}"
|
||||
>
|
||||
{#if passwordChecks.minLength}
|
||||
<Check class="h-4 w-4" />
|
||||
{:else}
|
||||
<X class="h-4 w-4" />
|
||||
{/if}
|
||||
At least 8 characters
|
||||
</li>
|
||||
<li
|
||||
class="flex items-center gap-2 {passwordChecks.maxLength
|
||||
? 'text-green-400'
|
||||
: 'text-red-400'}"
|
||||
>
|
||||
{#if passwordChecks.maxLength}
|
||||
<Check class="h-4 w-4" />
|
||||
{:else}
|
||||
<X class="h-4 w-4" />
|
||||
{/if}
|
||||
No more than 128 characters
|
||||
</li>
|
||||
<li
|
||||
class="flex items-center gap-2 {passwordChecks.upper
|
||||
? 'text-green-400'
|
||||
: 'text-red-400'}"
|
||||
>
|
||||
{#if passwordChecks.upper}
|
||||
<Check class="h-4 w-4" />
|
||||
{:else}
|
||||
<X class="h-4 w-4" />
|
||||
{/if}
|
||||
At least one uppercase letter
|
||||
</li>
|
||||
<li
|
||||
class="flex items-center gap-2 {passwordChecks.lower
|
||||
? 'text-green-400'
|
||||
: 'text-red-400'}"
|
||||
>
|
||||
{#if passwordChecks.lower}
|
||||
<Check class="h-4 w-4" />
|
||||
{:else}
|
||||
<X class="h-4 w-4" />
|
||||
{/if}
|
||||
At least one lowercase letter
|
||||
</li>
|
||||
<li
|
||||
class="flex items-center gap-2 {passwordChecks.number
|
||||
? 'text-green-400'
|
||||
: 'text-red-400'}"
|
||||
>
|
||||
{#if passwordChecks.number}
|
||||
<Check class="h-4 w-4" />
|
||||
{:else}
|
||||
<X class="h-4 w-4" />
|
||||
{/if}
|
||||
At least one number
|
||||
</li>
|
||||
</ul>
|
||||
{/if}
|
||||
<input
|
||||
type="password"
|
||||
bind:value={passwordConfirmValue}
|
||||
placeholder="Confirm new password"
|
||||
autocomplete="new-password"
|
||||
class="w-full rounded border border-neutral-700 bg-neutral-900 px-3 py-2 text-neutral-200 transition-colors outline-none focus:border-neutral-500"
|
||||
/>
|
||||
<div class="flex items-center justify-end">
|
||||
<button
|
||||
onclick={changePassword}
|
||||
disabled={passwordActionLoading ||
|
||||
!passwordValid ||
|
||||
passwordNewValue !== passwordConfirmValue}
|
||||
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 passwordActionLoading}
|
||||
<LoaderCircle class="h-4 w-4 animate-spin" />
|
||||
{:else}
|
||||
<KeyRound class="h-4 w-4" />
|
||||
{/if}
|
||||
Change Password
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{#if isOwner}
|
||||
@@ -911,6 +1419,62 @@
|
||||
Edit
|
||||
</button>
|
||||
</div>
|
||||
<div class="rounded bg-neutral-800/50 p-4">
|
||||
<div class="flex justify-between gap-1">
|
||||
<div class="flex flex-col">
|
||||
<span class="font-medium text-neutral-200">Password Reset Link</span>
|
||||
<span class="text-sm text-neutral-500">
|
||||
Send the user a reset link or copy one for manual delivery.
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex items-center justify-end">
|
||||
<button
|
||||
onclick={generatePasswordResetLink}
|
||||
disabled={passwordResetLinkLoading}
|
||||
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 passwordResetLinkLoading}
|
||||
<LoaderCircle class="h-4 w-4 animate-spin" />
|
||||
{:else}
|
||||
<KeyRound class="h-4 w-4" />
|
||||
{/if}
|
||||
Generate Reset Link
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if passwordResetLinkError}
|
||||
<div
|
||||
class="mt-3 rounded border border-red-900/50 bg-red-900/10 p-3 text-sm text-red-200"
|
||||
>
|
||||
{passwordResetLinkError}
|
||||
</div>
|
||||
{/if}
|
||||
{#if passwordResetLinkMessage}
|
||||
<div
|
||||
class="mt-3 rounded border border-green-900/50 bg-green-900/10 p-3 text-sm text-green-200"
|
||||
>
|
||||
{passwordResetLinkMessage}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if passwordResetLinkValue}
|
||||
<div class="mt-3 flex items-center gap-2 rounded bg-neutral-900/70 p-2">
|
||||
<code class="flex-1 font-mono text-sm break-all text-green-300"
|
||||
>{passwordResetLinkValue}</code
|
||||
>
|
||||
<button
|
||||
class="p-1 text-neutral-400 hover:text-white"
|
||||
onclick={() => {
|
||||
navigator.clipboard.writeText(passwordResetLinkValue);
|
||||
}}
|
||||
use:tooltip={'Copy reset link'}
|
||||
>
|
||||
<Copy class="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{#if !isOwner && data.user?.roles && !hasRole(data.user.roles, roles.Admin)}
|
||||
|
||||
@@ -52,9 +52,11 @@ namespace SharpbinV3.Server.Controllers
|
||||
var existingUser = await _userService.GetByUsername(request.Username);
|
||||
if (existingUser != null)
|
||||
return Conflict(new { success = false, message = "Username already exists." });
|
||||
if (!string.IsNullOrEmpty(request.Email))
|
||||
|
||||
var normalizedEmail = UserService.NormalizeEmail(request.Email);
|
||||
if (normalizedEmail != null)
|
||||
{
|
||||
var existingEmailUser = await _userService.GetByEmail(request.Email);
|
||||
var existingEmailUser = await _userService.GetByEmail(normalizedEmail);
|
||||
if (existingEmailUser != null)
|
||||
return Conflict(new { success = false, message = "Email already in use." });
|
||||
}
|
||||
@@ -64,13 +66,16 @@ namespace SharpbinV3.Server.Controllers
|
||||
User user;
|
||||
try
|
||||
{
|
||||
user = await _authService.CreateUser(request.Username, request.Password, request.Email, request.DisplayName);
|
||||
user = await _authService.CreateUser(request.Username, request.Password, normalizedEmail, request.DisplayName);
|
||||
}
|
||||
catch (DbUpdateException)
|
||||
{
|
||||
if (await _userService.GetByUsername(request.Username) != null)
|
||||
return Conflict(new { success = false, message = "Username already exists." });
|
||||
|
||||
if (normalizedEmail != null && await _userService.GetByEmail(normalizedEmail) != null)
|
||||
return Conflict(new { success = false, message = "Email already in use." });
|
||||
|
||||
throw;
|
||||
}
|
||||
|
||||
@@ -178,6 +183,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
{
|
||||
cf_turnstile_site_key = string.IsNullOrEmpty(authSettings.CF_Turnstile_SiteKey) ? null : authSettings.CF_Turnstile_SiteKey,
|
||||
registration_enabled = authSettings.Registration_Enabled,
|
||||
admins_require_2fa = authSettings.Admins_Require_2FA,
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -349,5 +355,247 @@ namespace SharpbinV3.Server.Controllers
|
||||
else
|
||||
return BadRequest(new { success = false, message });
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[EnableRateLimiting("Strict")]
|
||||
[Route("password/forgot")]
|
||||
public async Task<IActionResult> RequestPasswordReset([FromBody] PasswordResetRequestDto request)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(ModelState);
|
||||
|
||||
if (!await _verification.VerifyAsync(new VerificationContext { Token = request.Token, Ip = HttpContext.GetRequestIP() }))
|
||||
return BadRequest(new { success = false, message = "Verification failed." });
|
||||
|
||||
var result = await _authService.RequestPasswordResetForEmail(request.Email);
|
||||
if (!result.success)
|
||||
return Ok(new { success = true, message = "If an account exists for that email, a reset link has been sent." });
|
||||
|
||||
return Ok(new { success = true, message = result.message });
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
[Route("password/reset-info")]
|
||||
public async Task<IActionResult> GetPasswordResetInfo([FromQuery] string token)
|
||||
{
|
||||
var info = await _authService.GetPasswordResetTokenInfo(token);
|
||||
if (!info.success || info.user == null)
|
||||
return BadRequest(new { success = false, message = info.message });
|
||||
if (info.blocked)
|
||||
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
|
||||
|
||||
return Ok(
|
||||
new
|
||||
{
|
||||
success = true,
|
||||
username = info.username,
|
||||
requiresTotp = info.requiresTotp,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Route("password/reset")]
|
||||
[EnableRateLimiting("Sensitive")]
|
||||
public async Task<IActionResult> ResetPassword([FromBody] PasswordResetDto request)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(ModelState);
|
||||
|
||||
var result = await _authService.ResetPasswordWithToken(request.Token, request.NewPassword, request.TotpCode);
|
||||
if (!result.success)
|
||||
{
|
||||
if (result.message == "2FA is required to perform this action.")
|
||||
return StatusCode(403, new { success = false, message = result.message });
|
||||
return BadRequest(new { success = false, message = result.message });
|
||||
}
|
||||
|
||||
return Ok(new { success = true, message = result.message });
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||
[Route("password/change")]
|
||||
[EnableRateLimiting("Sensitive")]
|
||||
public async Task<IActionResult> ChangePassword([FromBody] PasswordChangeDto request)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(ModelState);
|
||||
|
||||
var user = await _authService.GetUserFromHttpContext(HttpContext);
|
||||
if (user == null)
|
||||
return BadRequest(new { success = false, message = "User not found." });
|
||||
|
||||
var result = await _authService.ChangeOwnPassword(user, request.CurrentPassword, request.NewPassword, request.TotpCode);
|
||||
if (!result.success)
|
||||
{
|
||||
if (result.message == "2FA is required to perform this action.")
|
||||
return StatusCode(403, new { success = false, message = result.message });
|
||||
return BadRequest(new { success = false, message = result.message });
|
||||
}
|
||||
|
||||
return Ok(new { success = true, message = result.message });
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||
[Route("password/admin-reset-link/{uuid}")]
|
||||
[EnableRateLimiting("Sensitive")]
|
||||
public async Task<IActionResult> AdminGeneratePasswordResetLink(Guid uuid, [FromBody] AdminPasswordResetLinkDto request)
|
||||
{
|
||||
var jwtUser = HttpContext.GetJwtUser()!;
|
||||
if (!jwtUser.Roles.HasFlag(Role.Admin))
|
||||
return StatusCode(403, new { success = false, message = "You do not have permission to perform this action." });
|
||||
|
||||
var targetUser = await _userService.GetByUUID(uuid);
|
||||
if (targetUser == null)
|
||||
return NotFound(new { success = false, message = "User not found." });
|
||||
|
||||
if (jwtUser.TotpEnabled)
|
||||
{
|
||||
if (
|
||||
string.IsNullOrWhiteSpace(request.TotpCode)
|
||||
|| !await _totp.VerifyAsync(new VerificationContext { UserUUID = jwtUser.UUID, Code = request.TotpCode })
|
||||
)
|
||||
{
|
||||
return Unauthorized(new { success = false, message = "Invalid TOTP code." });
|
||||
}
|
||||
}
|
||||
else if (options.Value.Admins_Require_2FA)
|
||||
{
|
||||
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
|
||||
}
|
||||
|
||||
var result = await _authService.GeneratePasswordResetLink(targetUser, sendEmail: !string.IsNullOrWhiteSpace(targetUser.Email));
|
||||
if (!result.success)
|
||||
{
|
||||
if (result.retryAfter.HasValue)
|
||||
{
|
||||
Response.Headers.RetryAfter = Math.Ceiling(result.retryAfter.Value / 1000d).ToString();
|
||||
return StatusCode(
|
||||
StatusCodes.Status429TooManyRequests,
|
||||
new
|
||||
{
|
||||
success = false,
|
||||
message = result.message,
|
||||
retryAfter = result.retryAfter,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return BadRequest(
|
||||
new
|
||||
{
|
||||
success = false,
|
||||
message = result.message,
|
||||
retryAfter = result.retryAfter,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return Ok(
|
||||
new
|
||||
{
|
||||
success = true,
|
||||
message = result.message,
|
||||
resetLink = result.resetLink,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Authorize(Policy = "JwtOnly")]
|
||||
[EnableRateLimiting("Sensitive")]
|
||||
[Route("email/resend-verification")]
|
||||
public async Task<IActionResult> ResendEmailVerification()
|
||||
{
|
||||
var user = await _authService.GetUserFromHttpContext(HttpContext);
|
||||
if (user == null)
|
||||
return BadRequest(new { success = false, message = "User not found." });
|
||||
|
||||
var result = await _authService.ResendEmailVerification(user);
|
||||
if (!result.success)
|
||||
{
|
||||
if (result.retryAfter.HasValue)
|
||||
{
|
||||
Response.Headers.RetryAfter = Math.Ceiling(result.retryAfter.Value / 1000d).ToString();
|
||||
return StatusCode(
|
||||
StatusCodes.Status429TooManyRequests,
|
||||
new
|
||||
{
|
||||
success = false,
|
||||
message = result.message,
|
||||
retryAfter = result.retryAfter,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return BadRequest(
|
||||
new
|
||||
{
|
||||
success = false,
|
||||
message = result.message,
|
||||
retryAfter = result.retryAfter,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return Ok(new { success = true, message = result.message });
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Authorize(Policy = "JwtOnly")]
|
||||
[EnableRateLimiting("Sensitive")]
|
||||
[Route("email/change")]
|
||||
public async Task<IActionResult> ChangeEmail([FromBody] ChangeEmailDto request)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(ModelState);
|
||||
|
||||
var user = await _authService.GetUserFromHttpContext(HttpContext);
|
||||
if (user == null)
|
||||
return BadRequest(new { success = false, message = "User not found." });
|
||||
|
||||
var totpEnabled = await _db.UserTotps.AnyAsync(t => t.UserUUID == user.UUID);
|
||||
if (totpEnabled)
|
||||
{
|
||||
if (
|
||||
string.IsNullOrWhiteSpace(request.TotpCode)
|
||||
|| !await _totp.VerifyAsync(new VerificationContext { UserUUID = user.UUID, Code = request.TotpCode })
|
||||
)
|
||||
{
|
||||
return Unauthorized(new { success = false, message = "Invalid TOTP code." });
|
||||
}
|
||||
}
|
||||
|
||||
var result = await _authService.RequestEmailChange(user, request.Email);
|
||||
if (!result.success)
|
||||
{
|
||||
if (result.retryAfter.HasValue)
|
||||
{
|
||||
Response.Headers.RetryAfter = Math.Ceiling(result.retryAfter.Value / 1000d).ToString();
|
||||
return StatusCode(
|
||||
StatusCodes.Status429TooManyRequests,
|
||||
new
|
||||
{
|
||||
success = false,
|
||||
message = result.message,
|
||||
retryAfter = result.retryAfter,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return BadRequest(
|
||||
new
|
||||
{
|
||||
success = false,
|
||||
message = result.message,
|
||||
retryAfter = result.retryAfter,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return Ok(new { success = true, message = result.message });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
[Route("api/[controller]")]
|
||||
public class UserController(
|
||||
UserService userService,
|
||||
AuthService authService,
|
||||
AppDbContext db,
|
||||
TotpVerificationProvider totp,
|
||||
VerificationService verificationService,
|
||||
@@ -30,6 +31,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
) : ControllerBase
|
||||
{
|
||||
private readonly UserService _userService = userService;
|
||||
private readonly AuthService _authService = authService;
|
||||
private readonly AppDbContext _db = db;
|
||||
private readonly TotpVerificationProvider _totp = totp;
|
||||
private readonly VerificationService _verificationService = verificationService;
|
||||
@@ -130,12 +132,12 @@ namespace SharpbinV3.Server.Controllers
|
||||
if ((updatedUser.Roles.HasValue || updatedUser.IsBanned.HasValue) && !actorIsAdmin)
|
||||
return StatusCode(403, new { success = false, message = "You do not have permission to modify this user." });
|
||||
|
||||
if (updatedUser.Email != null)
|
||||
return BadRequest(new { success = false, message = "Use the email change endpoint to update email addresses." });
|
||||
|
||||
bool isSensitiveUpdate =
|
||||
(updatedUser.Roles.HasValue && updatedUser.Roles.Value != targetUser.Roles) // updating roles
|
||||
|| (updatedUser.IsBanned.HasValue && updatedUser.IsBanned.Value != targetUser.IsBanned) // updating ban status
|
||||
|| (
|
||||
updatedUser.Email != null && updatedUser.Email != targetUser.Email // updating email
|
||||
);
|
||||
|| (updatedUser.IsBanned.HasValue && updatedUser.IsBanned.Value != targetUser.IsBanned); // updating ban status
|
||||
|
||||
if (actorIsAdmin && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA && isSensitiveUpdate)
|
||||
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
|
||||
@@ -167,7 +169,6 @@ namespace SharpbinV3.Server.Controllers
|
||||
targetUser.DisplayName = updatedUser.DisplayName ?? targetUser.DisplayName;
|
||||
if (actorIsAdmin || isSelfUpdate)
|
||||
{
|
||||
targetUser.Email = updatedUser.Email ?? targetUser.Email;
|
||||
targetUser.Visibility = updatedUser.Visibility ?? targetUser.Visibility;
|
||||
}
|
||||
if (actorIsAdmin)
|
||||
@@ -193,6 +194,8 @@ namespace SharpbinV3.Server.Controllers
|
||||
|
||||
if (!jwtUser.Roles.HasFlag(Role.Admin) && user.UUID != jwtUser.UUID)
|
||||
return StatusCode(403, new { success = false, message = "You do not have permission to delete this user." });
|
||||
|
||||
var isSelfDelete = user.UUID == jwtUser.UUID;
|
||||
if (jwtUser.Roles.HasFlag(Role.Admin) && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA)
|
||||
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
|
||||
if (user.Roles.HasFlag(Role.Admin))
|
||||
@@ -208,22 +211,70 @@ namespace SharpbinV3.Server.Controllers
|
||||
return Unauthorized(new { message = "Invalid TOTP code." });
|
||||
}
|
||||
}
|
||||
else
|
||||
else if (isSelfDelete && user.EmailVerified && !string.IsNullOrWhiteSpace(user.Email))
|
||||
{
|
||||
if (
|
||||
string.IsNullOrEmpty(dto.Token)
|
||||
|| !await _verificationService.VerifyAsync(new VerificationContext { Token = dto.Token, Ip = HttpContext.GetRequestIP() })
|
||||
)
|
||||
if (string.IsNullOrEmpty(dto.Token) || !await _authService.VerifyAccountDeletionToken(user, dto.Token))
|
||||
{
|
||||
return Unauthorized(new { message = "Invalid verification token." });
|
||||
return Unauthorized(new { message = "Invalid account deletion verification token." });
|
||||
}
|
||||
}
|
||||
|
||||
var deletedEmail = user.EmailVerified ? user.Email : null;
|
||||
var deletedUsername = user.Username;
|
||||
_db.Users.Remove(user);
|
||||
await _db.SaveChangesAsync();
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(deletedEmail))
|
||||
await _authService.SendAccountDeletedNotification(deletedEmail, deletedUsername);
|
||||
|
||||
return Ok(new { message = "User deleted successfully." });
|
||||
}
|
||||
|
||||
[HttpPost("uuid/{uuid}/delete-verification")]
|
||||
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||
[EnableRateLimiting("Sensitive")]
|
||||
public async Task<IActionResult> RequestDeleteVerification(Guid uuid)
|
||||
{
|
||||
var jwtUser = HttpContext.GetJwtUser()!;
|
||||
if (jwtUser.UUID != uuid)
|
||||
return StatusCode(403, new { success = false, message = "You do not have permission to delete this user." });
|
||||
|
||||
var user = await _userService.GetByUUID(uuid);
|
||||
if (user == null)
|
||||
return NotFound(new { success = false, message = "User not found." });
|
||||
|
||||
if (user.Roles.HasFlag(Role.Admin))
|
||||
return StatusCode(403, new { success = false, message = "You cannot delete an admin user." });
|
||||
|
||||
if (jwtUser.TotpEnabled)
|
||||
return BadRequest(new { success = false, message = "Use TOTP to delete this account." });
|
||||
|
||||
if (!user.EmailVerified || string.IsNullOrWhiteSpace(user.Email))
|
||||
return BadRequest(new { success = false, message = "A verified email address is required for email deletion verification." });
|
||||
|
||||
var result = await _authService.RequestAccountDeletionVerification(user);
|
||||
if (!result.success)
|
||||
{
|
||||
if (result.retryAfter.HasValue)
|
||||
{
|
||||
Response.Headers.RetryAfter = Math.Ceiling(result.retryAfter.Value / 1000d).ToString();
|
||||
return StatusCode(
|
||||
StatusCodes.Status429TooManyRequests,
|
||||
new
|
||||
{
|
||||
success = false,
|
||||
message = result.message,
|
||||
retryAfter = result.retryAfter,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return BadRequest(new { success = false, message = result.message });
|
||||
}
|
||||
|
||||
return Ok(new { success = true, message = result.message });
|
||||
}
|
||||
|
||||
private async Task<IActionResult> BuildUserResponse(User user, int page = 1)
|
||||
{
|
||||
var isRequestedUser = HttpContext.User?.FindFirst("uuid")?.Value == user.UUID.ToString();
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace SharpbinV3.Server.DTOs.Auth
|
||||
{
|
||||
public sealed class AdminPasswordResetLinkDto
|
||||
{
|
||||
public string? TotpCode { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace SharpbinV3.Server.DTOs.Auth
|
||||
{
|
||||
public sealed class ChangeEmailDto
|
||||
{
|
||||
[Required]
|
||||
[EmailAddress]
|
||||
public string Email { get; set; } = string.Empty;
|
||||
|
||||
public string? TotpCode { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace SharpbinV3.Server.DTOs.Auth
|
||||
{
|
||||
public sealed class PasswordChangeDto
|
||||
{
|
||||
[Required]
|
||||
public string CurrentPassword { get; set; } = string.Empty;
|
||||
|
||||
[Required]
|
||||
[StringLength(128, MinimumLength = 8)]
|
||||
public string NewPassword { get; set; } = string.Empty;
|
||||
|
||||
public string? TotpCode { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace SharpbinV3.Server.DTOs.Auth
|
||||
{
|
||||
public sealed class PasswordResetDto
|
||||
{
|
||||
[Required]
|
||||
public string Token { get; set; } = string.Empty;
|
||||
|
||||
[Required]
|
||||
[StringLength(128, MinimumLength = 8)]
|
||||
public string NewPassword { get; set; } = string.Empty;
|
||||
|
||||
public string? TotpCode { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace SharpbinV3.Server.DTOs.Auth
|
||||
{
|
||||
public sealed class PasswordResetRequestDto
|
||||
{
|
||||
[Required]
|
||||
[EmailAddress]
|
||||
public string Email { get; set; } = string.Empty;
|
||||
|
||||
public string? Token { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,10 @@ namespace SharpbinV3.Server.Data
|
||||
.HasIndex(r => r.TokenHash)
|
||||
.IsUnique();
|
||||
|
||||
modelBuilder.Entity<User>()
|
||||
.HasIndex(u => u.Email)
|
||||
.IsUnique()
|
||||
.HasFilter("\"Email\" IS NOT NULL");
|
||||
|
||||
modelBuilder.Entity<UserTotp>()
|
||||
.HasOne(t => t.User)
|
||||
|
||||
@@ -17,6 +17,7 @@ namespace SharpbinV3.Server.Data.Entities
|
||||
public required Guid UserUUID { get; set; }
|
||||
public User User { get; set; } = null!;
|
||||
public required string TokenHash { get; set; }
|
||||
public string? TargetEmail { get; set; }
|
||||
public long CreatedAt { get; set; } = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
||||
public long ExpiresAt { get; set; }
|
||||
public required EmailTokenType Type { get; set; }
|
||||
|
||||
@@ -3,6 +3,7 @@ namespace SharpbinV3.Server.Data.Enums
|
||||
public enum SecurityAction
|
||||
{
|
||||
UpdateRoles = 1,
|
||||
DeleteUser = 2
|
||||
DeleteUser = 2,
|
||||
GeneratePasswordResetLink = 3
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
<h2>Account Deleted</h2>
|
||||
<p>Hi <strong>{{USERNAME}}</strong>,</p>
|
||||
<p>Your Sharpbin account and all associated data have been permanently deleted.</p>
|
||||
<p>No further action is needed.</p>
|
||||
@@ -0,0 +1,6 @@
|
||||
<h2>Confirm Account Deletion</h2>
|
||||
<p>Hi <strong>{{USERNAME}}</strong>,</p>
|
||||
<p>A request was made to permanently delete your Sharpbin account and all associated data.</p>
|
||||
<p>Use this verification code to confirm account deletion:</p>
|
||||
<div class="link-box">{{DELETE_TOKEN}}</div>
|
||||
<p>This code expires in 24 hours. If you did not request this, do not share this code.</p>
|
||||
@@ -0,0 +1,5 @@
|
||||
<h2>Email Change Requested</h2>
|
||||
<p>Hi <strong>{{USERNAME}}</strong>,</p>
|
||||
<p>Your Sharpbin account email is being changed from <strong>{{OLD_EMAIL}}</strong> to <strong>{{NEW_EMAIL}}</strong>.</p>
|
||||
<p>If you made this change, no action is needed.</p>
|
||||
<p>If you did not request this change, secure your account immediately by changing your password and reviewing your active sessions.</p>
|
||||
@@ -0,0 +1,5 @@
|
||||
<h2>Email Address Changed</h2>
|
||||
<p>Hi <strong>{{USERNAME}}</strong>,</p>
|
||||
<p>Your Sharpbin account email was changed from <strong>{{OLD_EMAIL}}</strong> to <strong>{{NEW_EMAIL}}</strong>.</p>
|
||||
<p>If you made this change, no action is needed.</p>
|
||||
<p>If you did not make this change, secure your account immediately by changing your password and reviewing your active sessions.</p>
|
||||
@@ -0,0 +1,5 @@
|
||||
<h2>Password Changed</h2>
|
||||
<p>Hi <strong>{{USERNAME}}</strong>,</p>
|
||||
<p>The password for your Sharpbin account was just changed.</p>
|
||||
<p>If you made this change, no action is needed.</p>
|
||||
<p>If you did not make this change, secure your account immediately by changing your password again and reviewing active sessions.</p>
|
||||
@@ -0,0 +1,12 @@
|
||||
<h2>Reset Your Password</h2>
|
||||
<p>Hi <strong>{{USERNAME}}</strong>,</p>
|
||||
<p>We received a request to reset the password for your Sharpbin account.</p>
|
||||
<p style="text-align: center;">
|
||||
<a href="{{RESET_URL}}" class="button">Reset Password</a>
|
||||
</p>
|
||||
<p>If the button doesn't work, you can copy and paste this link into your browser:</p>
|
||||
<div class="link-box">
|
||||
<a href="{{RESET_URL}}">{{RESET_URL}}</a>
|
||||
</div>
|
||||
<p><strong>This link will expire in 24 hours.</strong></p>
|
||||
<p>If you didn't request a password reset, you can ignore this email.</p>
|
||||
@@ -0,0 +1,12 @@
|
||||
<h2>Verify Your New Email Address</h2>
|
||||
<p>Hi <strong>{{USERNAME}}</strong>,</p>
|
||||
<p>Confirm this email address for your Sharpbin account by clicking the button below.</p>
|
||||
<p style="text-align: center;">
|
||||
<a href="{{VERIFICATION_URL}}" class="button">Verify Email Address</a>
|
||||
</p>
|
||||
<p>If the button doesn't work, you can copy and paste this link into your browser:</p>
|
||||
<div class="link-box">
|
||||
<a href="{{VERIFICATION_URL}}">{{VERIFICATION_URL}}</a>
|
||||
</div>
|
||||
<p><strong>This link will expire in 24 hours.</strong></p>
|
||||
<p>If you did not request this change, you can ignore this email.</p>
|
||||
@@ -0,0 +1,629 @@
|
||||
// <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("20260618030444_EmailChangeTokens")]
|
||||
partial class EmailChangeTokens
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder.HasAnnotation("ProductVersion", "10.0.3");
|
||||
|
||||
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.Comment", b =>
|
||||
{
|
||||
b.Property<long>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<byte[]>("Content")
|
||||
.HasMaxLength(5000)
|
||||
.HasColumnType("BLOB");
|
||||
|
||||
b.Property<long>("CreatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<bool>("IsCompressed")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("OriginalSize")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long?>("ParentCommentID")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("PastePID")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("StoredSize")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long?>("UpdatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<Guid>("UserUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ParentCommentID");
|
||||
|
||||
b.HasIndex("PastePID");
|
||||
|
||||
b.HasIndex("UserUUID");
|
||||
|
||||
b.ToTable("Comments");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.CommentInteraction", b =>
|
||||
{
|
||||
b.Property<long>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("CommentID")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("CreatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("Type")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<Guid>("UserUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("CommentID", "Type");
|
||||
|
||||
b.HasIndex("CommentID", "UserUUID")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("CommentInteractions");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b =>
|
||||
{
|
||||
b.Property<Guid>("UUID")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long>("CreatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("ExpiresAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("TargetEmail")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("TokenHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<int>("Type")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<bool>("Used")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<Guid>("UserUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("UUID");
|
||||
|
||||
b.HasIndex("UserUUID");
|
||||
|
||||
b.ToTable("EmailVerificationTokens");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
|
||||
{
|
||||
b.Property<long>("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>("OriginalSize")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("StoredSize")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("Syntax")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Title")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
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("StoredSize");
|
||||
|
||||
b.HasIndex("Syntax");
|
||||
|
||||
b.HasIndex("UUID");
|
||||
|
||||
b.HasIndex("Views");
|
||||
|
||||
b.ToTable("Pastes");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteInteraction", b =>
|
||||
{
|
||||
b.Property<long>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("CreatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("PasteID")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("Type")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<Guid>("UserUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("PasteID", "Type");
|
||||
|
||||
b.HasIndex("PasteID", "UserUUID")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("PasteInteractions");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("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?>("CommentID")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("CreatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("Description")
|
||||
.HasMaxLength(1000)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long?>("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("CommentID");
|
||||
|
||||
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<bool>("EmailVerified")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<bool>("IsBanned")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long?>("LastLogin")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("PasswordHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<int>("Roles")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long?>("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.HasIndex("Username")
|
||||
.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.Comment", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.Comment", "ParentComment")
|
||||
.WithMany("Replies")
|
||||
.HasForeignKey("ParentCommentID")
|
||||
.OnDelete(DeleteBehavior.Restrict);
|
||||
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
|
||||
.WithMany("Comments")
|
||||
.HasForeignKey("PastePID")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
|
||||
.WithMany("Comments")
|
||||
.HasForeignKey("UserUUID")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("ParentComment");
|
||||
|
||||
b.Navigation("Paste");
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.CommentInteraction", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.Comment", "Comment")
|
||||
.WithMany("Interactions")
|
||||
.HasForeignKey("CommentID")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Comment");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
|
||||
.WithMany("EmailVerificationTokens")
|
||||
.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.PasteInteraction", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
|
||||
.WithMany("Interactions")
|
||||
.HasForeignKey("PasteID")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Paste");
|
||||
});
|
||||
|
||||
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.Comment", null)
|
||||
.WithMany("Reports")
|
||||
.HasForeignKey("CommentID")
|
||||
.OnDelete(DeleteBehavior.SetNull);
|
||||
|
||||
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.Comment", b =>
|
||||
{
|
||||
b.Navigation("Interactions");
|
||||
|
||||
b.Navigation("Replies");
|
||||
|
||||
b.Navigation("Reports");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
|
||||
{
|
||||
b.Navigation("Comments");
|
||||
|
||||
b.Navigation("Interactions");
|
||||
|
||||
b.Navigation("PasteViews");
|
||||
|
||||
b.Navigation("Reports");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
|
||||
{
|
||||
b.Navigation("ApiKeys");
|
||||
|
||||
b.Navigation("Comments");
|
||||
|
||||
b.Navigation("EmailVerificationTokens");
|
||||
|
||||
b.Navigation("Pastes");
|
||||
|
||||
b.Navigation("RefreshTokens");
|
||||
|
||||
b.Navigation("Reports");
|
||||
|
||||
b.Navigation("Totp");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SharpbinV3.Server.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class EmailChangeTokens : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "TargetEmail",
|
||||
table: "EmailVerificationTokens",
|
||||
type: "TEXT",
|
||||
nullable: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "TargetEmail",
|
||||
table: "EmailVerificationTokens");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,633 @@
|
||||
// <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("20260618231408_uniqueEmails")]
|
||||
partial class uniqueEmails
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder.HasAnnotation("ProductVersion", "10.0.3");
|
||||
|
||||
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.Comment", b =>
|
||||
{
|
||||
b.Property<long>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<byte[]>("Content")
|
||||
.HasMaxLength(5000)
|
||||
.HasColumnType("BLOB");
|
||||
|
||||
b.Property<long>("CreatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<bool>("IsCompressed")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("OriginalSize")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long?>("ParentCommentID")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("PastePID")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("StoredSize")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long?>("UpdatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<Guid>("UserUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ParentCommentID");
|
||||
|
||||
b.HasIndex("PastePID");
|
||||
|
||||
b.HasIndex("UserUUID");
|
||||
|
||||
b.ToTable("Comments");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.CommentInteraction", b =>
|
||||
{
|
||||
b.Property<long>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("CommentID")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("CreatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("Type")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<Guid>("UserUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("CommentID", "Type");
|
||||
|
||||
b.HasIndex("CommentID", "UserUUID")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("CommentInteractions");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b =>
|
||||
{
|
||||
b.Property<Guid>("UUID")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long>("CreatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("ExpiresAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("TargetEmail")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("TokenHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<int>("Type")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<bool>("Used")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<Guid>("UserUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("UUID");
|
||||
|
||||
b.HasIndex("UserUUID");
|
||||
|
||||
b.ToTable("EmailVerificationTokens");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
|
||||
{
|
||||
b.Property<long>("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>("OriginalSize")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("StoredSize")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("Syntax")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Title")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
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("StoredSize");
|
||||
|
||||
b.HasIndex("Syntax");
|
||||
|
||||
b.HasIndex("UUID");
|
||||
|
||||
b.HasIndex("Views");
|
||||
|
||||
b.ToTable("Pastes");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteInteraction", b =>
|
||||
{
|
||||
b.Property<long>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("CreatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("PasteID")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("Type")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<Guid>("UserUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("PasteID", "Type");
|
||||
|
||||
b.HasIndex("PasteID", "UserUUID")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("PasteInteractions");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("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?>("CommentID")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("CreatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("Description")
|
||||
.HasMaxLength(1000)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long?>("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("CommentID");
|
||||
|
||||
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<bool>("EmailVerified")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<bool>("IsBanned")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long?>("LastLogin")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("PasswordHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<int>("Roles")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long?>("UID")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("Username")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<int>("Visibility")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.HasKey("UUID");
|
||||
|
||||
b.HasIndex("Email")
|
||||
.IsUnique()
|
||||
.HasFilter("\"Email\" IS NOT NULL");
|
||||
|
||||
b.HasIndex("UID");
|
||||
|
||||
b.HasIndex("UUID")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("Username")
|
||||
.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.Comment", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.Comment", "ParentComment")
|
||||
.WithMany("Replies")
|
||||
.HasForeignKey("ParentCommentID")
|
||||
.OnDelete(DeleteBehavior.Restrict);
|
||||
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
|
||||
.WithMany("Comments")
|
||||
.HasForeignKey("PastePID")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
|
||||
.WithMany("Comments")
|
||||
.HasForeignKey("UserUUID")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("ParentComment");
|
||||
|
||||
b.Navigation("Paste");
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.CommentInteraction", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.Comment", "Comment")
|
||||
.WithMany("Interactions")
|
||||
.HasForeignKey("CommentID")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Comment");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
|
||||
.WithMany("EmailVerificationTokens")
|
||||
.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.PasteInteraction", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
|
||||
.WithMany("Interactions")
|
||||
.HasForeignKey("PasteID")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Paste");
|
||||
});
|
||||
|
||||
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.Comment", null)
|
||||
.WithMany("Reports")
|
||||
.HasForeignKey("CommentID")
|
||||
.OnDelete(DeleteBehavior.SetNull);
|
||||
|
||||
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.Comment", b =>
|
||||
{
|
||||
b.Navigation("Interactions");
|
||||
|
||||
b.Navigation("Replies");
|
||||
|
||||
b.Navigation("Reports");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
|
||||
{
|
||||
b.Navigation("Comments");
|
||||
|
||||
b.Navigation("Interactions");
|
||||
|
||||
b.Navigation("PasteViews");
|
||||
|
||||
b.Navigation("Reports");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
|
||||
{
|
||||
b.Navigation("ApiKeys");
|
||||
|
||||
b.Navigation("Comments");
|
||||
|
||||
b.Navigation("EmailVerificationTokens");
|
||||
|
||||
b.Navigation("Pastes");
|
||||
|
||||
b.Navigation("RefreshTokens");
|
||||
|
||||
b.Navigation("Reports");
|
||||
|
||||
b.Navigation("Totp");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SharpbinV3.Server.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class uniqueEmails : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.Sql(
|
||||
"""
|
||||
UPDATE "Users"
|
||||
SET "Email" = NULL, "EmailVerified" = 0
|
||||
WHERE "Email" IS NULL OR trim("Email") = '';
|
||||
"""
|
||||
);
|
||||
|
||||
migrationBuilder.Sql(
|
||||
"""
|
||||
UPDATE "Users"
|
||||
SET "Email" = lower(trim("Email"))
|
||||
WHERE "Email" IS NOT NULL;
|
||||
"""
|
||||
);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Users_Email",
|
||||
table: "Users",
|
||||
column: "Email",
|
||||
unique: true,
|
||||
filter: "\"Email\" IS NOT NULL");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropIndex(
|
||||
name: "IX_Users_Email",
|
||||
table: "Users");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -132,6 +132,9 @@ namespace SharpbinV3.Server.Migrations
|
||||
b.Property<long>("ExpiresAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("TargetEmail")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("TokenHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
@@ -418,6 +421,10 @@ namespace SharpbinV3.Server.Migrations
|
||||
|
||||
b.HasKey("UUID");
|
||||
|
||||
b.HasIndex("Email")
|
||||
.IsUnique()
|
||||
.HasFilter("\"Email\" IS NOT NULL");
|
||||
|
||||
b.HasIndex("UID");
|
||||
|
||||
b.HasIndex("UUID")
|
||||
|
||||
@@ -6,8 +6,11 @@ using Microsoft.Extensions.Options;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using SharpbinV3.Server.Data;
|
||||
using SharpbinV3.Server.Data.Entities;
|
||||
using SharpbinV3.Server.DTOs;
|
||||
using SharpbinV3.Server.DTOs.Auth;
|
||||
using SharpbinV3.Server.Extensions;
|
||||
using SharpbinV3.Server.Services.Verification;
|
||||
using SharpbinV3.Server.Services.Verification.Providers;
|
||||
using SharpbinV3.Server.Settings;
|
||||
using Bcrypt = BCrypt.Net.BCrypt;
|
||||
|
||||
@@ -27,6 +30,7 @@ namespace SharpbinV3.Server.Services
|
||||
public sealed class AuthService(
|
||||
AppDbContext db,
|
||||
EmailService email,
|
||||
TotpVerificationProvider totp,
|
||||
IOptions<JWTSettings> jwtOptions,
|
||||
IOptions<AuthSettings> authOptions,
|
||||
IOptions<AppSettings> appSettings,
|
||||
@@ -35,11 +39,15 @@ namespace SharpbinV3.Server.Services
|
||||
{
|
||||
private readonly AppDbContext _db = db;
|
||||
private readonly EmailService _email = email;
|
||||
private readonly TotpVerificationProvider _totp = totp;
|
||||
private readonly JWTSettings _jwtSettings = jwtOptions.Value;
|
||||
private readonly AuthSettings _authSettings = authOptions.Value;
|
||||
private readonly AppSettings _appSettings = appSettings.Value;
|
||||
private readonly ILogger _logger = logger;
|
||||
private const int EmailVerificationTokenLength = 64;
|
||||
private static readonly TimeSpan EmailActionCooldown = TimeSpan.FromHours(12);
|
||||
private static readonly TimeSpan EmailVerificationLifetime = TimeSpan.FromDays(1);
|
||||
private static readonly TimeSpan PasswordResetLifetime = TimeSpan.FromDays(1);
|
||||
|
||||
public async Task<User> CreateUser(string username, string password, string? email, string? displayName)
|
||||
{
|
||||
@@ -47,7 +55,7 @@ namespace SharpbinV3.Server.Services
|
||||
{
|
||||
Username = UserService.NormalizeUsername(username),
|
||||
PasswordHash = Bcrypt.HashPassword(password),
|
||||
Email = email,
|
||||
Email = UserService.NormalizeEmail(email),
|
||||
DisplayName = displayName,
|
||||
UUID = Guid.CreateVersion7(),
|
||||
};
|
||||
@@ -185,7 +193,7 @@ namespace SharpbinV3.Server.Services
|
||||
{
|
||||
var existingUser = await _db.Users.FirstOrDefaultAsync(u => u.UUID == user.UUID) ?? throw new Exception("User not found");
|
||||
existingUser.Username = UserService.NormalizeUsername(user.Username);
|
||||
existingUser.Email = user.Email;
|
||||
existingUser.Email = UserService.NormalizeEmail(user.Email);
|
||||
existingUser.DisplayName = user.DisplayName;
|
||||
existingUser.Roles = user.Roles;
|
||||
existingUser.LastLogin = user.LastLogin;
|
||||
@@ -203,6 +211,101 @@ namespace SharpbinV3.Server.Services
|
||||
await _db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
public async Task<(bool success, string message, long? retryAfter, string? resetLink)> GeneratePasswordResetLink(
|
||||
User user,
|
||||
bool sendEmail = true
|
||||
)
|
||||
{
|
||||
return await IssuePasswordResetTokenAsync(user, sendEmail: sendEmail, invalidateExisting: true, exposeLink: true);
|
||||
}
|
||||
|
||||
public async Task<(bool success, string message, bool requiresTotp, bool blocked, string username, User? user)> GetPasswordResetTokenInfo(
|
||||
string token
|
||||
)
|
||||
{
|
||||
var tokenEntity = await GetValidPasswordResetToken(token);
|
||||
if (tokenEntity == null)
|
||||
return (false, "Token is expired or already used.", false, false, string.Empty, null);
|
||||
|
||||
var user = tokenEntity.User;
|
||||
if (user == null)
|
||||
return (false, "Token is expired or already used.", false, false, string.Empty, null);
|
||||
|
||||
var state = await GetPasswordResetTwoFactorState(user);
|
||||
return (true, "Token is valid.", state.requiresTotp, state.blocked, user.Username, user);
|
||||
}
|
||||
|
||||
public async Task<(bool success, string message)> ChangeOwnPassword(User user, string currentPassword, string newPassword, string? totpCode)
|
||||
{
|
||||
if (!Bcrypt.Verify(currentPassword, user.PasswordHash))
|
||||
return (false, "Current password is incorrect.");
|
||||
|
||||
var totpState = await GetPasswordResetTwoFactorState(user);
|
||||
if (totpState.blocked)
|
||||
return (false, "2FA is required to perform this action.");
|
||||
|
||||
if (totpState.requiresTotp)
|
||||
{
|
||||
if (
|
||||
string.IsNullOrWhiteSpace(totpCode) || !await _totp.VerifyAsync(new VerificationContext { UserUUID = user.UUID, Code = totpCode })
|
||||
)
|
||||
return (false, "Invalid TOTP code.");
|
||||
}
|
||||
|
||||
if (!RegisterUserDto.ValidatePassword().IsMatch(newPassword))
|
||||
return (false, "Password should have at least 8 characters, including uppercase, lowercase, and digits.");
|
||||
|
||||
var originalEmail = user.Email;
|
||||
await using var transaction = await _db.Database.BeginTransactionAsync();
|
||||
await ReplacePasswordAsync(user, newPassword, saveChanges: false);
|
||||
await _db.SaveChangesAsync();
|
||||
await transaction.CommitAsync();
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(originalEmail))
|
||||
{
|
||||
await _email.SendAsync(originalEmail, "Sharpbin Password Changed", EmailTemplates.PasswordChanged(user.Username));
|
||||
}
|
||||
|
||||
return (true, "Password updated successfully.");
|
||||
}
|
||||
|
||||
public async Task<(bool success, string message)> ResetPasswordWithToken(string token, string newPassword, string? totpCode)
|
||||
{
|
||||
if (!RegisterUserDto.ValidatePassword().IsMatch(newPassword))
|
||||
return (false, "Password should have at least 8 characters, including uppercase, lowercase, and digits.");
|
||||
|
||||
var tokenEntity = await GetValidPasswordResetToken(token);
|
||||
if (tokenEntity == null || tokenEntity.User == null)
|
||||
return (false, "Token is expired or already used.");
|
||||
|
||||
var user = tokenEntity.User;
|
||||
var totpState = await GetPasswordResetTwoFactorState(user);
|
||||
if (totpState.blocked)
|
||||
return (false, "2FA is required to perform this action.");
|
||||
|
||||
if (totpState.requiresTotp)
|
||||
{
|
||||
if (
|
||||
string.IsNullOrWhiteSpace(totpCode) || !await _totp.VerifyAsync(new VerificationContext { UserUUID = user.UUID, Code = totpCode })
|
||||
)
|
||||
return (false, "Invalid TOTP code.");
|
||||
}
|
||||
|
||||
await using var transaction = await _db.Database.BeginTransactionAsync();
|
||||
var originalEmail = user.Email;
|
||||
tokenEntity.Used = true;
|
||||
await ReplacePasswordAsync(user, newPassword, saveChanges: false);
|
||||
await _db.SaveChangesAsync();
|
||||
await transaction.CommitAsync();
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(originalEmail))
|
||||
{
|
||||
await _email.SendAsync(originalEmail, "Sharpbin Password Changed", EmailTemplates.PasswordChanged(user.Username));
|
||||
}
|
||||
|
||||
return (true, "Password reset successfully.");
|
||||
}
|
||||
|
||||
public async Task<User?> GetUserFromHttpContext(HttpContext context)
|
||||
{
|
||||
var apiKey = context.GetApiKeyFromContext();
|
||||
@@ -216,15 +319,165 @@ namespace SharpbinV3.Server.Services
|
||||
return await _db.Users.FirstOrDefaultAsync(u => u.UUID == userUUID);
|
||||
}
|
||||
|
||||
public async Task SendEmailVerification(User user)
|
||||
public async Task<(bool success, string message, long? retryAfter)> ResendEmailVerification(User user)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(user.Email))
|
||||
return (false, "No email address is set for this account.", null);
|
||||
|
||||
if (user.EmailVerified)
|
||||
return (false, "Email is already verified.", null);
|
||||
|
||||
var cooldown = await GetEmailTokenCooldown(user.UUID, EmailTokenType.VerifyEmail);
|
||||
if (cooldown > TimeSpan.Zero)
|
||||
return (
|
||||
false,
|
||||
$"Please wait {Utilities.FormatDuration(cooldown)} before requesting another verification email.",
|
||||
Utilities.TimeSpanToMilliseconds(cooldown)
|
||||
);
|
||||
|
||||
await SendEmailVerification(user, invalidateExisting: true);
|
||||
return (true, "Verification email sent.", null);
|
||||
}
|
||||
|
||||
public async Task<(bool success, string message, long? retryAfter)> RequestPasswordResetForEmail(string email)
|
||||
{
|
||||
var normalizedEmail = UserService.NormalizeEmail(email);
|
||||
if (normalizedEmail == null)
|
||||
return (true, "If an account exists for that email, a reset link has been sent.", null);
|
||||
|
||||
var user = await _db.Users.FirstOrDefaultAsync(u => u.Email == normalizedEmail);
|
||||
if (user == null)
|
||||
return (true, "If an account exists for that email, a reset link has been sent.", null);
|
||||
|
||||
await IssuePasswordResetTokenAsync(user, sendEmail: true, invalidateExisting: true, exposeLink: false);
|
||||
return (true, "If an account exists for that email, a reset link has been sent.", null);
|
||||
}
|
||||
|
||||
public async Task<(bool success, string message, long? retryAfter)> RequestAccountDeletionVerification(User user)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(user.Email) || !user.EmailVerified)
|
||||
return (false, "A verified email address is required for email deletion verification.", null);
|
||||
|
||||
var cooldown = await GetEmailTokenCooldown(user.UUID, EmailTokenType.DeleteAccount);
|
||||
if (cooldown > TimeSpan.Zero)
|
||||
return (
|
||||
false,
|
||||
$"Please wait {Utilities.FormatDuration(cooldown)} before requesting another account deletion email.",
|
||||
Utilities.TimeSpanToMilliseconds(cooldown)
|
||||
);
|
||||
|
||||
await InvalidateActiveTokens(user.UUID, EmailTokenType.DeleteAccount);
|
||||
|
||||
var token = Utilities.GenerateSecureRandomString(EmailVerificationTokenLength);
|
||||
var tokenHash = Utilities.ComputeSha256(token);
|
||||
var emailBody = EmailTemplates.DeleteAccountVerification(user.Username, token);
|
||||
|
||||
await _email.SendAsync(user.Email, "Confirm Account Deletion - Sharpbin", emailBody);
|
||||
await _db.EmailVerificationTokens.AddAsync(
|
||||
new EmailVerificationToken
|
||||
{
|
||||
TokenHash = tokenHash,
|
||||
UserUUID = user.UUID,
|
||||
User = user,
|
||||
ExpiresAt = DateTimeOffset.UtcNow.Add(EmailVerificationLifetime).ToUnixTimeMilliseconds(),
|
||||
Type = EmailTokenType.DeleteAccount,
|
||||
}
|
||||
);
|
||||
await _db.SaveChangesAsync();
|
||||
|
||||
return (true, "Account deletion verification email sent.", null);
|
||||
}
|
||||
|
||||
public async Task<bool> VerifyAccountDeletionToken(User user, string token)
|
||||
{
|
||||
if (token.Length != EmailVerificationTokenLength)
|
||||
return false;
|
||||
|
||||
var tokenHash = Utilities.ComputeSha256(token);
|
||||
var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
||||
var tokenEntity = await _db.EmailVerificationTokens.FirstOrDefaultAsync(t =>
|
||||
t.UserUUID == user.UUID && t.TokenHash == tokenHash && t.Type == EmailTokenType.DeleteAccount && !t.Used && t.ExpiresAt >= now
|
||||
);
|
||||
|
||||
if (tokenEntity == null)
|
||||
return false;
|
||||
|
||||
tokenEntity.Used = true;
|
||||
await _db.SaveChangesAsync();
|
||||
return true;
|
||||
}
|
||||
|
||||
public async Task SendAccountDeletedNotification(string email, string username)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(email))
|
||||
return;
|
||||
|
||||
await _email.SendAsync(email, "Sharpbin Account Deleted", EmailTemplates.AccountDeleted(username));
|
||||
}
|
||||
|
||||
public async Task<(bool success, string message, long? retryAfter)> RequestEmailChange(User user, string requestedEmail)
|
||||
{
|
||||
var newEmail = UserService.NormalizeEmail(requestedEmail);
|
||||
if (newEmail == null)
|
||||
return (false, "Email is required.", null);
|
||||
|
||||
if (string.Equals(user.Email, newEmail, StringComparison.OrdinalIgnoreCase))
|
||||
return (false, "That email is already on your account.", null);
|
||||
|
||||
var existingEmailUser = await _db.Users.FirstOrDefaultAsync(u => u.Email == newEmail && u.UUID != user.UUID);
|
||||
if (existingEmailUser != null)
|
||||
return (false, "Email already in use.", null);
|
||||
|
||||
var cooldown = await GetEmailTokenCooldown(user.UUID, EmailTokenType.ChangeEmail);
|
||||
if (cooldown > TimeSpan.Zero)
|
||||
return (
|
||||
false,
|
||||
$"Please wait {Utilities.FormatDuration(cooldown)} before changing your email again.",
|
||||
Utilities.TimeSpanToMilliseconds(cooldown)
|
||||
);
|
||||
|
||||
await InvalidateActiveEmailTokens(user.UUID);
|
||||
|
||||
var token = Utilities.GenerateSecureRandomString(EmailVerificationTokenLength);
|
||||
var tokenHash = Utilities.ComputeSha256(token);
|
||||
var verificationUrl = BuildVerificationUrl(token);
|
||||
var emailBody = EmailTemplates.VerifyChangedEmail(verificationUrl, user.Username);
|
||||
|
||||
await _email.SendAsync(newEmail, "Verify Your New Email - Sharpbin", emailBody);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(user.Email))
|
||||
{
|
||||
var notificationBody = EmailTemplates.EmailChangeRequested(user.Username, user.Email, newEmail);
|
||||
await _email.SendAsync(user.Email, "Sharpbin Email Change Requested", notificationBody);
|
||||
}
|
||||
|
||||
var verificationToken = new EmailVerificationToken
|
||||
{
|
||||
TokenHash = tokenHash,
|
||||
UserUUID = user.UUID,
|
||||
User = user,
|
||||
TargetEmail = newEmail,
|
||||
ExpiresAt = DateTimeOffset.UtcNow.Add(EmailVerificationLifetime).ToUnixTimeMilliseconds(),
|
||||
Type = EmailTokenType.ChangeEmail,
|
||||
};
|
||||
await _db.EmailVerificationTokens.AddAsync(verificationToken);
|
||||
await _db.SaveChangesAsync();
|
||||
|
||||
return (true, "Verification email sent to the new address.", null);
|
||||
}
|
||||
|
||||
public async Task SendEmailVerification(User user, bool invalidateExisting = true)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(user.Email))
|
||||
return;
|
||||
|
||||
if (invalidateExisting)
|
||||
await InvalidateActiveEmailTokens(user.UUID);
|
||||
|
||||
string token = Utilities.GenerateSecureRandomString(EmailVerificationTokenLength);
|
||||
string tokenHash = Utilities.ComputeSha256(token);
|
||||
|
||||
string verificationUrl = $"{(_appSettings.Https ? "https" : "http")}://{_appSettings.Domain}/verify-email?token={token}";
|
||||
string verificationUrl = BuildVerificationUrl(token);
|
||||
string emailBody = EmailTemplates.VerifyEmail(verificationUrl, user.Username);
|
||||
|
||||
await _email.SendAsync(user.Email, "Verify Your Email - Sharpbin", emailBody);
|
||||
@@ -233,13 +486,59 @@ namespace SharpbinV3.Server.Services
|
||||
TokenHash = tokenHash,
|
||||
UserUUID = user.UUID,
|
||||
User = user,
|
||||
ExpiresAt = DateTimeOffset.UtcNow.AddDays(1).ToUnixTimeMilliseconds(),
|
||||
ExpiresAt = DateTimeOffset.UtcNow.Add(EmailVerificationLifetime).ToUnixTimeMilliseconds(),
|
||||
Type = EmailTokenType.VerifyEmail,
|
||||
};
|
||||
await _db.EmailVerificationTokens.AddAsync(verificationToken);
|
||||
await _db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
public async Task<(bool success, string message, long? retryAfter, string? resetLink)> IssuePasswordResetTokenAsync(
|
||||
User user,
|
||||
bool sendEmail,
|
||||
bool invalidateExisting,
|
||||
bool exposeLink
|
||||
)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(user.Email) && sendEmail)
|
||||
return (false, "No email address is set for this account.", null, null);
|
||||
|
||||
var cooldown = await GetEmailTokenCooldown(user.UUID, EmailTokenType.ResetPassword);
|
||||
if (cooldown > TimeSpan.Zero)
|
||||
return (
|
||||
false,
|
||||
$"Please wait {Utilities.FormatDuration(cooldown)} before requesting another password reset link.",
|
||||
Utilities.TimeSpanToMilliseconds(cooldown),
|
||||
null
|
||||
);
|
||||
|
||||
if (invalidateExisting)
|
||||
await InvalidateActiveTokens(user.UUID, EmailTokenType.ResetPassword);
|
||||
|
||||
var token = Utilities.GenerateSecureRandomString(EmailVerificationTokenLength);
|
||||
var tokenHash = Utilities.ComputeSha256(token);
|
||||
var resetLink = BuildResetPasswordUrl(token);
|
||||
|
||||
if (sendEmail && !string.IsNullOrWhiteSpace(user.Email))
|
||||
{
|
||||
var emailBody = EmailTemplates.ResetPassword(user.Username, resetLink);
|
||||
await _email.SendAsync(user.Email, "Reset Your Password - Sharpbin", emailBody);
|
||||
}
|
||||
|
||||
var verificationToken = new EmailVerificationToken
|
||||
{
|
||||
TokenHash = tokenHash,
|
||||
UserUUID = user.UUID,
|
||||
User = user,
|
||||
ExpiresAt = DateTimeOffset.UtcNow.Add(PasswordResetLifetime).ToUnixTimeMilliseconds(),
|
||||
Type = EmailTokenType.ResetPassword,
|
||||
};
|
||||
await _db.EmailVerificationTokens.AddAsync(verificationToken);
|
||||
await _db.SaveChangesAsync();
|
||||
|
||||
return (true, sendEmail ? "Password reset email sent." : "Password reset link generated.", null, exposeLink ? resetLink : null);
|
||||
}
|
||||
|
||||
public async Task<(bool success, string message)> VerifyEmailVerificationToken(string token)
|
||||
{
|
||||
if (token.Length != EmailVerificationTokenLength)
|
||||
@@ -258,13 +557,116 @@ namespace SharpbinV3.Server.Services
|
||||
|
||||
if (verificationToken != null && !verificationToken.Used)
|
||||
{
|
||||
if (verificationToken.Type == EmailTokenType.ChangeEmail)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(verificationToken.TargetEmail))
|
||||
return (false, "Token is invalid.");
|
||||
|
||||
var normalizedTargetEmail = UserService.NormalizeEmail(verificationToken.TargetEmail);
|
||||
if (normalizedTargetEmail == null)
|
||||
return (false, "Token is invalid.");
|
||||
|
||||
var existingEmailUser = await _db.Users.FirstOrDefaultAsync(u =>
|
||||
u.Email == normalizedTargetEmail && u.UUID != verificationToken.UserUUID
|
||||
);
|
||||
if (existingEmailUser != null)
|
||||
return (false, "Email already in use.");
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(verificationToken.User.Email))
|
||||
{
|
||||
var notificationBody = EmailTemplates.EmailChanged(
|
||||
verificationToken.User.Username,
|
||||
verificationToken.User.Email,
|
||||
normalizedTargetEmail
|
||||
);
|
||||
await _email.SendAsync(verificationToken.User.Email, "Sharpbin Email Address Changed", notificationBody);
|
||||
}
|
||||
|
||||
verificationToken.User.Email = normalizedTargetEmail;
|
||||
}
|
||||
|
||||
verificationToken.Used = true;
|
||||
verificationToken.User.EmailVerified = true;
|
||||
await InvalidateActiveEmailTokens(verificationToken.UserUUID);
|
||||
await _db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
await _db.SaveChangesAsync();
|
||||
return (true, "Email successfully verified.");
|
||||
}
|
||||
|
||||
private async Task ReplacePasswordAsync(User user, string newPassword, bool saveChanges = true)
|
||||
{
|
||||
var existingUser = await _db.Users.FirstOrDefaultAsync(u => u.UUID == user.UUID) ?? throw new Exception("User not found");
|
||||
existingUser.PasswordHash = Bcrypt.HashPassword(newPassword);
|
||||
|
||||
await _db
|
||||
.RefreshTokens.Where(rt => rt.UserUUID == user.UUID && !rt.Revoked)
|
||||
.ExecuteUpdateAsync(setters => setters.SetProperty(rt => rt.Revoked, true).SetProperty(rt => rt.Used, true));
|
||||
|
||||
await InvalidateActiveTokens(user.UUID, EmailTokenType.ResetPassword);
|
||||
_db.Users.Update(existingUser);
|
||||
if (saveChanges)
|
||||
await _db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
private async Task<EmailVerificationToken?> GetValidPasswordResetToken(string token)
|
||||
{
|
||||
if (token.Length != EmailVerificationTokenLength)
|
||||
return null;
|
||||
|
||||
var tokenHash = Utilities.ComputeSha256(token);
|
||||
return await _db
|
||||
.EmailVerificationTokens.Include(t => t.User)
|
||||
.FirstOrDefaultAsync(t => t.TokenHash == tokenHash && t.Type == EmailTokenType.ResetPassword);
|
||||
}
|
||||
|
||||
private async Task<(bool requiresTotp, bool blocked)> GetPasswordResetTwoFactorState(User user)
|
||||
{
|
||||
var totpEnabled = await _db.UserTotps.AnyAsync(t => t.UserUUID == user.UUID);
|
||||
var blocked = user.Roles.HasFlag(Role.Admin) && _authSettings.Admins_Require_2FA && !totpEnabled;
|
||||
return (totpEnabled, blocked);
|
||||
}
|
||||
|
||||
private async Task InvalidateActiveTokens(Guid userUUID, params EmailTokenType[] types)
|
||||
{
|
||||
var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
||||
var tokenTypes = types.Length > 0 ? types : [EmailTokenType.VerifyEmail, EmailTokenType.ChangeEmail, EmailTokenType.ResetPassword];
|
||||
await _db
|
||||
.EmailVerificationTokens.Where(t => t.UserUUID == userUUID && !t.Used && t.ExpiresAt >= now && tokenTypes.Contains(t.Type))
|
||||
.ExecuteUpdateAsync(setters => setters.SetProperty(t => t.Used, true));
|
||||
}
|
||||
|
||||
private async Task InvalidateActiveEmailTokens(Guid userUUID)
|
||||
{
|
||||
await InvalidateActiveTokens(userUUID, EmailTokenType.VerifyEmail, EmailTokenType.ChangeEmail);
|
||||
}
|
||||
|
||||
private async Task InvalidateActivePasswordResetTokens(Guid userUUID)
|
||||
{
|
||||
await InvalidateActiveTokens(userUUID, EmailTokenType.ResetPassword);
|
||||
}
|
||||
|
||||
private async Task<TimeSpan> GetEmailTokenCooldown(Guid userUUID, EmailTokenType type)
|
||||
{
|
||||
var lastCreatedAt = await _db
|
||||
.EmailVerificationTokens.Where(t => t.UserUUID == userUUID && t.Type == type)
|
||||
.OrderByDescending(t => t.CreatedAt)
|
||||
.Select(t => (long?)t.CreatedAt)
|
||||
.FirstOrDefaultAsync();
|
||||
|
||||
if (lastCreatedAt == null)
|
||||
return TimeSpan.Zero;
|
||||
|
||||
var nextAllowedAt = DateTimeOffset.FromUnixTimeMilliseconds(lastCreatedAt.Value).Add(EmailActionCooldown);
|
||||
var remaining = nextAllowedAt - DateTimeOffset.UtcNow;
|
||||
return remaining > TimeSpan.Zero ? remaining : TimeSpan.Zero;
|
||||
}
|
||||
|
||||
private string BuildVerificationUrl(string token) =>
|
||||
$"{(_appSettings.Https ? "https" : "http")}://{_appSettings.Domain}/verify-email?token={token}";
|
||||
|
||||
private string BuildResetPasswordUrl(string token) =>
|
||||
$"{(_appSettings.Https ? "https" : "http")}://{_appSettings.Domain}/reset-password?token={token}";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,5 +37,71 @@ namespace SharpbinV3.Server.Services
|
||||
|
||||
return RenderTemplate("Verify Your Email", contentTemplate, replacements);
|
||||
}
|
||||
|
||||
public static string VerifyChangedEmail(string verificationUrl, string username)
|
||||
{
|
||||
var contentTemplate = LoadEmbeddedResource("SharpbinV3.Server.EmailTemplates.VerifyChangedEmail.html");
|
||||
var replacements = new Dictionary<string, string> { { "USERNAME", username }, { "VERIFICATION_URL", verificationUrl } };
|
||||
|
||||
return RenderTemplate("Verify Your New Email", contentTemplate, replacements);
|
||||
}
|
||||
|
||||
public static string EmailChangeRequested(string username, string oldEmail, string newEmail)
|
||||
{
|
||||
var contentTemplate = LoadEmbeddedResource("SharpbinV3.Server.EmailTemplates.EmailChangeRequested.html");
|
||||
var replacements = new Dictionary<string, string>
|
||||
{
|
||||
{ "USERNAME", username },
|
||||
{ "OLD_EMAIL", oldEmail },
|
||||
{ "NEW_EMAIL", newEmail },
|
||||
};
|
||||
|
||||
return RenderTemplate("Email Change Requested", contentTemplate, replacements);
|
||||
}
|
||||
|
||||
public static string EmailChanged(string username, string oldEmail, string newEmail)
|
||||
{
|
||||
var contentTemplate = LoadEmbeddedResource("SharpbinV3.Server.EmailTemplates.EmailChanged.html");
|
||||
var replacements = new Dictionary<string, string>
|
||||
{
|
||||
{ "USERNAME", username },
|
||||
{ "OLD_EMAIL", oldEmail },
|
||||
{ "NEW_EMAIL", newEmail },
|
||||
};
|
||||
|
||||
return RenderTemplate("Email Address Changed", contentTemplate, replacements);
|
||||
}
|
||||
|
||||
public static string ResetPassword(string username, string resetUrl)
|
||||
{
|
||||
var contentTemplate = LoadEmbeddedResource("SharpbinV3.Server.EmailTemplates.ResetPassword.html");
|
||||
var replacements = new Dictionary<string, string> { { "USERNAME", username }, { "RESET_URL", resetUrl } };
|
||||
|
||||
return RenderTemplate("Reset Your Password", contentTemplate, replacements);
|
||||
}
|
||||
|
||||
public static string PasswordChanged(string username)
|
||||
{
|
||||
var contentTemplate = LoadEmbeddedResource("SharpbinV3.Server.EmailTemplates.PasswordChanged.html");
|
||||
var replacements = new Dictionary<string, string> { { "USERNAME", username } };
|
||||
|
||||
return RenderTemplate("Password Changed", contentTemplate, replacements);
|
||||
}
|
||||
|
||||
public static string DeleteAccountVerification(string username, string deleteToken)
|
||||
{
|
||||
var contentTemplate = LoadEmbeddedResource("SharpbinV3.Server.EmailTemplates.DeleteAccountVerification.html");
|
||||
var replacements = new Dictionary<string, string> { { "USERNAME", username }, { "DELETE_TOKEN", deleteToken } };
|
||||
|
||||
return RenderTemplate("Confirm Account Deletion", contentTemplate, replacements);
|
||||
}
|
||||
|
||||
public static string AccountDeleted(string username)
|
||||
{
|
||||
var contentTemplate = LoadEmbeddedResource("SharpbinV3.Server.EmailTemplates.AccountDeleted.html");
|
||||
var replacements = new Dictionary<string, string> { { "USERNAME", username } };
|
||||
|
||||
return RenderTemplate("Account Deleted", contentTemplate, replacements);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,20 +35,33 @@ namespace SharpbinV3.Server.Services
|
||||
|
||||
public Task<User?> GetByEmail(string email, bool withPastes = false)
|
||||
{
|
||||
var normalizedEmail = NormalizeEmail(email);
|
||||
if (normalizedEmail == null)
|
||||
return Task.FromResult<User?>(null);
|
||||
|
||||
IQueryable<User> query = _db.Users;
|
||||
if (withPastes)
|
||||
query = query.Include(u => u.Pastes);
|
||||
return query.FirstOrDefaultAsync(u => u.Email == email);
|
||||
return query.FirstOrDefaultAsync(u => u.Email == normalizedEmail);
|
||||
}
|
||||
|
||||
public async Task<User> Update(User user)
|
||||
{
|
||||
user.Username = NormalizeUsername(user.Username);
|
||||
user.Email = NormalizeEmail(user.Email);
|
||||
_db.Users.Update(user);
|
||||
await _db.SaveChangesAsync();
|
||||
return user;
|
||||
}
|
||||
|
||||
public static string NormalizeUsername(string username) => username.ToLowerInvariant();
|
||||
|
||||
public static string? NormalizeEmail(string? email)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(email))
|
||||
return null;
|
||||
|
||||
return email.Trim().ToLowerInvariant();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,5 +34,19 @@ namespace SharpbinV3.Server
|
||||
|
||||
return Convert.ToHexString(hashBytes);
|
||||
}
|
||||
|
||||
public static long TimeSpanToMilliseconds(TimeSpan value) => (long)Math.Ceiling(value.TotalMilliseconds);
|
||||
|
||||
public static string FormatDuration(TimeSpan value)
|
||||
{
|
||||
if (value.TotalHours >= 1)
|
||||
{
|
||||
var hours = (int)Math.Ceiling(value.TotalHours);
|
||||
return $"{hours} hour{(hours == 1 ? "" : "s")}";
|
||||
}
|
||||
|
||||
var minutes = Math.Max(1, (int)Math.Ceiling(value.TotalMinutes));
|
||||
return $"{minutes} minute{(minutes == 1 ? "" : "s")}";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user