From d4976ac9aac41cb7ad23070480862bf2cec89095 Mon Sep 17 00:00:00 2001 From: whoswhip Date: Thu, 18 Jun 2026 21:15:34 -0400 Subject: [PATCH] feat: password resets fix: frontend docker file chore: format via csharpier again --- SharpbinV3.Client/Dockerfile | 6 +- SharpbinV3.Client/src/lib/types/user.ts | 1 + SharpbinV3.Client/src/routes/+layout.svelte | 2 +- .../src/routes/forgot-password/+page.svelte | 123 ++++ .../src/routes/login/+page.svelte | 6 + .../src/routes/reset-password/+page.server.ts | 25 + .../src/routes/reset-password/+page.svelte | 231 +++++++ .../src/routes/user/[username]/+page.svelte | 570 +++++++++++++++- .../Controllers/AuthController.cs | 254 ++++++- .../Controllers/UserController.cs | 73 +- .../DTOs/Auth/AdminPasswordResetLinkDto.cs | 7 + SharpbinV3.Server/DTOs/Auth/ChangeEmailDto.cs | 13 + .../DTOs/Auth/PasswordChangeDto.cs | 16 + .../DTOs/Auth/PasswordResetDto.cs | 16 + .../DTOs/Auth/PasswordResetRequestDto.cs | 13 + SharpbinV3.Server/Data/AppDbContext.cs | 4 + .../Data/Entities/EmailVerificationToken.cs | 1 + .../Data/Enums/SecurityAction.cs | 3 +- .../EmailTemplates/AccountDeleted.html | 4 + .../DeleteAccountVerification.html | 6 + .../EmailTemplates/EmailChangeRequested.html | 5 + .../EmailTemplates/EmailChanged.html | 5 + .../EmailTemplates/PasswordChanged.html | 5 + .../EmailTemplates/ResetPassword.html | 12 + .../EmailTemplates/VerifyChangedEmail.html | 12 + ...260618030444_EmailChangeTokens.Designer.cs | 629 +++++++++++++++++ .../20260618030444_EmailChangeTokens.cs | 28 + .../20260618231408_uniqueEmails.Designer.cs | 633 ++++++++++++++++++ .../Migrations/20260618231408_uniqueEmails.cs | 45 ++ .../Migrations/AppDbContextModelSnapshot.cs | 7 + SharpbinV3.Server/Services/AuthService.cs | 412 +++++++++++- SharpbinV3.Server/Services/EmailTemplates.cs | 66 ++ SharpbinV3.Server/Services/UserService.cs | 15 +- SharpbinV3.Server/Utilities.cs | 14 + 34 files changed, 3236 insertions(+), 26 deletions(-) create mode 100644 SharpbinV3.Client/src/routes/forgot-password/+page.svelte create mode 100644 SharpbinV3.Client/src/routes/reset-password/+page.server.ts create mode 100644 SharpbinV3.Client/src/routes/reset-password/+page.svelte create mode 100644 SharpbinV3.Server/DTOs/Auth/AdminPasswordResetLinkDto.cs create mode 100644 SharpbinV3.Server/DTOs/Auth/ChangeEmailDto.cs create mode 100644 SharpbinV3.Server/DTOs/Auth/PasswordChangeDto.cs create mode 100644 SharpbinV3.Server/DTOs/Auth/PasswordResetDto.cs create mode 100644 SharpbinV3.Server/DTOs/Auth/PasswordResetRequestDto.cs create mode 100644 SharpbinV3.Server/EmailTemplates/AccountDeleted.html create mode 100644 SharpbinV3.Server/EmailTemplates/DeleteAccountVerification.html create mode 100644 SharpbinV3.Server/EmailTemplates/EmailChangeRequested.html create mode 100644 SharpbinV3.Server/EmailTemplates/EmailChanged.html create mode 100644 SharpbinV3.Server/EmailTemplates/PasswordChanged.html create mode 100644 SharpbinV3.Server/EmailTemplates/ResetPassword.html create mode 100644 SharpbinV3.Server/EmailTemplates/VerifyChangedEmail.html create mode 100644 SharpbinV3.Server/Migrations/20260618030444_EmailChangeTokens.Designer.cs create mode 100644 SharpbinV3.Server/Migrations/20260618030444_EmailChangeTokens.cs create mode 100644 SharpbinV3.Server/Migrations/20260618231408_uniqueEmails.Designer.cs create mode 100644 SharpbinV3.Server/Migrations/20260618231408_uniqueEmails.cs diff --git a/SharpbinV3.Client/Dockerfile b/SharpbinV3.Client/Dockerfile index 3685d80..722dedf 100644 --- a/SharpbinV3.Client/Dockerfile +++ b/SharpbinV3.Client/Dockerfile @@ -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 diff --git a/SharpbinV3.Client/src/lib/types/user.ts b/SharpbinV3.Client/src/lib/types/user.ts index b520d82..c4fc22e 100644 --- a/SharpbinV3.Client/src/lib/types/user.ts +++ b/SharpbinV3.Client/src/lib/types/user.ts @@ -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; diff --git a/SharpbinV3.Client/src/routes/+layout.svelte b/SharpbinV3.Client/src/routes/+layout.svelte index 2d53257..0d1d442 100644 --- a/SharpbinV3.Client/src/routes/+layout.svelte +++ b/SharpbinV3.Client/src/routes/+layout.svelte @@ -98,7 +98,7 @@ - {#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')} + + + Forgot Password - Sharpbin + + + +
+
+

Forgot Password

+

+ Enter the email address on your account and we’ll send a reset link if one exists. +

+
+ + {#if data.options?.cf_turnstile_site_key} +
+ {/if} + + {#if error} +
+ {error} +
+ {/if} + {#if message} +
+ {message} +
+ {/if} +
+

+ Back to login +

+
+
diff --git a/SharpbinV3.Client/src/routes/login/+page.svelte b/SharpbinV3.Client/src/routes/login/+page.svelte index 4204a8c..e5a4425 100644 --- a/SharpbinV3.Client/src/routes/login/+page.svelte +++ b/SharpbinV3.Client/src/routes/login/+page.svelte @@ -159,5 +159,11 @@ class="text-neutral-200 transition-colors duration-200 hover:text-white">Register

+

+ Forgot password? +

diff --git a/SharpbinV3.Client/src/routes/reset-password/+page.server.ts b/SharpbinV3.Client/src/routes/reset-password/+page.server.ts new file mode 100644 index 0000000..f3807e4 --- /dev/null +++ b/SharpbinV3.Client/src/routes/reset-password/+page.server.ts @@ -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) + }; +}; diff --git a/SharpbinV3.Client/src/routes/reset-password/+page.svelte b/SharpbinV3.Client/src/routes/reset-password/+page.svelte new file mode 100644 index 0000000..eb07e0b --- /dev/null +++ b/SharpbinV3.Client/src/routes/reset-password/+page.svelte @@ -0,0 +1,231 @@ + + + + Reset Password - Sharpbin + + + +
+
+ {#if complete} +

Password Reset

+

{message}

+

+ Back to login +

+ {:else} +

Reset Password

+

+ {#if data.username} + Reset the password for {data.username}. + {:else} + Set a new password for your account. + {/if} +

+
+ (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} +
    +
  • + {#if passwordChecks.minLength}{:else}{/if} + At least 8 characters +
  • +
  • + {#if passwordChecks.maxLength}{:else}{/if} + No more than 128 characters +
  • +
  • + {#if passwordChecks.upper}{:else}{/if} + At least one uppercase letter +
  • +
  • + {#if passwordChecks.lower}{:else}{/if} + At least one lowercase letter +
  • +
  • + {#if passwordChecks.number}{:else}{/if} + At least one number +
  • +
+ {/if} + + {#if confirmPassword && password !== confirmPassword} +
+ Passwords do not match. +
+ {/if} + {#if data.requiresTotp} + { + 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} + + {#if error} +
+ {error} +
+ {/if} +
+ {/if} +
+
diff --git a/SharpbinV3.Client/src/routes/user/[username]/+page.svelte b/SharpbinV3.Client/src/routes/user/[username]/+page.svelte index 591454b..3d63df5 100644 --- a/SharpbinV3.Client/src/routes/user/[username]/+page.svelte +++ b/SharpbinV3.Client/src/routes/user/[username]/+page.svelte @@ -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 | 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({ @@ -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({ + 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} + {#if isOwner} +
+

Email

+

+ Used for account verification and security notifications. +

+ + {#if emailError} +
+ {emailError} +
+ {/if} + {#if emailMessage} +
+ {emailMessage} +
+ {/if} + +
+ {#if isEditingEmail} +
+ { + if (e.key === 'Enter') changeEmail(); + else if (e.key === 'Escape') { + isEditingEmail = false; + editEmailValue = ''; + } + }} + /> +
+ + +
+
+ {:else} +
+
+ + {data.user?.email || 'No email set'} + + + {data.user?.email + ? data.user?.emailVerified + ? 'Verified' + : 'Not verified' + : 'Add an email to enable verification'} + +
+
+ {#if data.user?.email && !data.user?.emailVerified} + + {/if} + +
+
+ {/if} +
+
+ {/if} {:else if isOwner && activeSubTab === 'settings:security'}
@@ -864,6 +1240,138 @@ {totpEnabled ? 'Manage' : 'Enable'}
+
+
+ Change Password + + Use your current password and choose a new one. + +
+ + {#if passwordError} +
+ {passwordError} +
+ {/if} + {#if passwordMessage} +
+ {passwordMessage} +
+ {/if} + +
+ + (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} +
    +
  • + {#if passwordChecks.minLength} + + {:else} + + {/if} + At least 8 characters +
  • +
  • + {#if passwordChecks.maxLength} + + {:else} + + {/if} + No more than 128 characters +
  • +
  • + {#if passwordChecks.upper} + + {:else} + + {/if} + At least one uppercase letter +
  • +
  • + {#if passwordChecks.lower} + + {:else} + + {/if} + At least one lowercase letter +
  • +
  • + {#if passwordChecks.number} + + {:else} + + {/if} + At least one number +
  • +
+ {/if} + +
+ +
+
+
{#if isOwner} @@ -911,6 +1419,62 @@ Edit +
+
+
+ Password Reset Link + + Send the user a reset link or copy one for manual delivery. + +
+
+ +
+
+ + {#if passwordResetLinkError} +
+ {passwordResetLinkError} +
+ {/if} + {#if passwordResetLinkMessage} +
+ {passwordResetLinkMessage} +
+ {/if} + + {#if passwordResetLinkValue} +
+ {passwordResetLinkValue} + +
+ {/if} +
{#if !isOwner && data.user?.roles && !hasRole(data.user.roles, roles.Admin)} diff --git a/SharpbinV3.Server/Controllers/AuthController.cs b/SharpbinV3.Server/Controllers/AuthController.cs index 7734320..08ae539 100644 --- a/SharpbinV3.Server/Controllers/AuthController.cs +++ b/SharpbinV3.Server/Controllers/AuthController.cs @@ -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 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 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 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 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 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 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 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 }); + } } } diff --git a/SharpbinV3.Server/Controllers/UserController.cs b/SharpbinV3.Server/Controllers/UserController.cs index bb21df9..34ac731 100644 --- a/SharpbinV3.Server/Controllers/UserController.cs +++ b/SharpbinV3.Server/Controllers/UserController.cs @@ -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 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 BuildUserResponse(User user, int page = 1) { var isRequestedUser = HttpContext.User?.FindFirst("uuid")?.Value == user.UUID.ToString(); diff --git a/SharpbinV3.Server/DTOs/Auth/AdminPasswordResetLinkDto.cs b/SharpbinV3.Server/DTOs/Auth/AdminPasswordResetLinkDto.cs new file mode 100644 index 0000000..fa111e0 --- /dev/null +++ b/SharpbinV3.Server/DTOs/Auth/AdminPasswordResetLinkDto.cs @@ -0,0 +1,7 @@ +namespace SharpbinV3.Server.DTOs.Auth +{ + public sealed class AdminPasswordResetLinkDto + { + public string? TotpCode { get; set; } + } +} diff --git a/SharpbinV3.Server/DTOs/Auth/ChangeEmailDto.cs b/SharpbinV3.Server/DTOs/Auth/ChangeEmailDto.cs new file mode 100644 index 0000000..0a3c84f --- /dev/null +++ b/SharpbinV3.Server/DTOs/Auth/ChangeEmailDto.cs @@ -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; } + } +} diff --git a/SharpbinV3.Server/DTOs/Auth/PasswordChangeDto.cs b/SharpbinV3.Server/DTOs/Auth/PasswordChangeDto.cs new file mode 100644 index 0000000..c9e17ae --- /dev/null +++ b/SharpbinV3.Server/DTOs/Auth/PasswordChangeDto.cs @@ -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; } + } +} diff --git a/SharpbinV3.Server/DTOs/Auth/PasswordResetDto.cs b/SharpbinV3.Server/DTOs/Auth/PasswordResetDto.cs new file mode 100644 index 0000000..395e321 --- /dev/null +++ b/SharpbinV3.Server/DTOs/Auth/PasswordResetDto.cs @@ -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; } + } +} diff --git a/SharpbinV3.Server/DTOs/Auth/PasswordResetRequestDto.cs b/SharpbinV3.Server/DTOs/Auth/PasswordResetRequestDto.cs new file mode 100644 index 0000000..3369447 --- /dev/null +++ b/SharpbinV3.Server/DTOs/Auth/PasswordResetRequestDto.cs @@ -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; } + } +} diff --git a/SharpbinV3.Server/Data/AppDbContext.cs b/SharpbinV3.Server/Data/AppDbContext.cs index d713dae..9d5a4e4 100644 --- a/SharpbinV3.Server/Data/AppDbContext.cs +++ b/SharpbinV3.Server/Data/AppDbContext.cs @@ -43,6 +43,10 @@ namespace SharpbinV3.Server.Data .HasIndex(r => r.TokenHash) .IsUnique(); + modelBuilder.Entity() + .HasIndex(u => u.Email) + .IsUnique() + .HasFilter("\"Email\" IS NOT NULL"); modelBuilder.Entity() .HasOne(t => t.User) diff --git a/SharpbinV3.Server/Data/Entities/EmailVerificationToken.cs b/SharpbinV3.Server/Data/Entities/EmailVerificationToken.cs index d6d9422..039827e 100644 --- a/SharpbinV3.Server/Data/Entities/EmailVerificationToken.cs +++ b/SharpbinV3.Server/Data/Entities/EmailVerificationToken.cs @@ -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; } diff --git a/SharpbinV3.Server/Data/Enums/SecurityAction.cs b/SharpbinV3.Server/Data/Enums/SecurityAction.cs index 266ff1e..420b62e 100644 --- a/SharpbinV3.Server/Data/Enums/SecurityAction.cs +++ b/SharpbinV3.Server/Data/Enums/SecurityAction.cs @@ -3,6 +3,7 @@ namespace SharpbinV3.Server.Data.Enums public enum SecurityAction { UpdateRoles = 1, - DeleteUser = 2 + DeleteUser = 2, + GeneratePasswordResetLink = 3 } } diff --git a/SharpbinV3.Server/EmailTemplates/AccountDeleted.html b/SharpbinV3.Server/EmailTemplates/AccountDeleted.html new file mode 100644 index 0000000..b79c45a --- /dev/null +++ b/SharpbinV3.Server/EmailTemplates/AccountDeleted.html @@ -0,0 +1,4 @@ +

Account Deleted

+

Hi {{USERNAME}},

+

Your Sharpbin account and all associated data have been permanently deleted.

+

No further action is needed.

diff --git a/SharpbinV3.Server/EmailTemplates/DeleteAccountVerification.html b/SharpbinV3.Server/EmailTemplates/DeleteAccountVerification.html new file mode 100644 index 0000000..de6ffcf --- /dev/null +++ b/SharpbinV3.Server/EmailTemplates/DeleteAccountVerification.html @@ -0,0 +1,6 @@ +

Confirm Account Deletion

+

Hi {{USERNAME}},

+

A request was made to permanently delete your Sharpbin account and all associated data.

+

Use this verification code to confirm account deletion:

+ +

This code expires in 24 hours. If you did not request this, do not share this code.

diff --git a/SharpbinV3.Server/EmailTemplates/EmailChangeRequested.html b/SharpbinV3.Server/EmailTemplates/EmailChangeRequested.html new file mode 100644 index 0000000..1ea7bc7 --- /dev/null +++ b/SharpbinV3.Server/EmailTemplates/EmailChangeRequested.html @@ -0,0 +1,5 @@ +

Email Change Requested

+

Hi {{USERNAME}},

+

Your Sharpbin account email is being changed from {{OLD_EMAIL}} to {{NEW_EMAIL}}.

+

If you made this change, no action is needed.

+

If you did not request this change, secure your account immediately by changing your password and reviewing your active sessions.

diff --git a/SharpbinV3.Server/EmailTemplates/EmailChanged.html b/SharpbinV3.Server/EmailTemplates/EmailChanged.html new file mode 100644 index 0000000..9fed3e4 --- /dev/null +++ b/SharpbinV3.Server/EmailTemplates/EmailChanged.html @@ -0,0 +1,5 @@ +

Email Address Changed

+

Hi {{USERNAME}},

+

Your Sharpbin account email was changed from {{OLD_EMAIL}} to {{NEW_EMAIL}}.

+

If you made this change, no action is needed.

+

If you did not make this change, secure your account immediately by changing your password and reviewing your active sessions.

diff --git a/SharpbinV3.Server/EmailTemplates/PasswordChanged.html b/SharpbinV3.Server/EmailTemplates/PasswordChanged.html new file mode 100644 index 0000000..efb5850 --- /dev/null +++ b/SharpbinV3.Server/EmailTemplates/PasswordChanged.html @@ -0,0 +1,5 @@ +

Password Changed

+

Hi {{USERNAME}},

+

The password for your Sharpbin account was just changed.

+

If you made this change, no action is needed.

+

If you did not make this change, secure your account immediately by changing your password again and reviewing active sessions.

diff --git a/SharpbinV3.Server/EmailTemplates/ResetPassword.html b/SharpbinV3.Server/EmailTemplates/ResetPassword.html new file mode 100644 index 0000000..0502a4a --- /dev/null +++ b/SharpbinV3.Server/EmailTemplates/ResetPassword.html @@ -0,0 +1,12 @@ +

Reset Your Password

+

Hi {{USERNAME}},

+

We received a request to reset the password for your Sharpbin account.

+

+ Reset Password +

+

If the button doesn't work, you can copy and paste this link into your browser:

+ +

This link will expire in 24 hours.

+

If you didn't request a password reset, you can ignore this email.

diff --git a/SharpbinV3.Server/EmailTemplates/VerifyChangedEmail.html b/SharpbinV3.Server/EmailTemplates/VerifyChangedEmail.html new file mode 100644 index 0000000..938c458 --- /dev/null +++ b/SharpbinV3.Server/EmailTemplates/VerifyChangedEmail.html @@ -0,0 +1,12 @@ +

Verify Your New Email Address

+

Hi {{USERNAME}},

+

Confirm this email address for your Sharpbin account by clicking the button below.

+

+ Verify Email Address +

+

If the button doesn't work, you can copy and paste this link into your browser:

+ +

This link will expire in 24 hours.

+

If you did not request this change, you can ignore this email.

diff --git a/SharpbinV3.Server/Migrations/20260618030444_EmailChangeTokens.Designer.cs b/SharpbinV3.Server/Migrations/20260618030444_EmailChangeTokens.Designer.cs new file mode 100644 index 0000000..37a3087 --- /dev/null +++ b/SharpbinV3.Server/Migrations/20260618030444_EmailChangeTokens.Designer.cs @@ -0,0 +1,629 @@ +// +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 + { + /// + 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("UUID") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("KeyHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("LastUsedAt") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("UUID"); + + b.HasIndex("UserUUID"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Content") + .HasMaxLength(5000) + .HasColumnType("BLOB"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("IsCompressed") + .HasColumnType("INTEGER"); + + b.Property("OriginalSize") + .HasColumnType("INTEGER"); + + b.Property("ParentCommentID") + .HasColumnType("INTEGER"); + + b.Property("PastePID") + .HasColumnType("INTEGER"); + + b.Property("StoredSize") + .HasColumnType("INTEGER"); + + b.Property("UpdatedAt") + .HasColumnType("INTEGER"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CommentID") + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("Type") + .HasColumnType("INTEGER"); + + b.Property("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("UUID") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("ExpiresAt") + .HasColumnType("INTEGER"); + + b.Property("TargetEmail") + .HasColumnType("TEXT"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Type") + .HasColumnType("INTEGER"); + + b.Property("Used") + .HasColumnType("INTEGER"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("UUID"); + + b.HasIndex("UserUUID"); + + b.ToTable("EmailVerificationTokens"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b => + { + b.Property("PID") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AuthorUUID") + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("BLOB"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("EditedAt") + .HasColumnType("INTEGER"); + + b.Property("ExpiresAt") + .HasColumnType("INTEGER"); + + b.Property("ID") + .HasColumnType("TEXT"); + + b.Property("IsCompressed") + .HasColumnType("INTEGER"); + + b.Property("OriginalSize") + .HasColumnType("INTEGER"); + + b.Property("StoredSize") + .HasColumnType("INTEGER"); + + b.Property("Syntax") + .HasColumnType("TEXT"); + + b.Property("Title") + .HasColumnType("TEXT"); + + b.Property("UUID") + .HasColumnType("TEXT"); + + b.Property("Views") + .HasColumnType("INTEGER"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("PasteID") + .HasColumnType("INTEGER"); + + b.Property("Type") + .HasColumnType("INTEGER"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PastePID") + .HasColumnType("INTEGER"); + + b.Property("ViewedAt") + .HasColumnType("INTEGER"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("ExpiresAt") + .HasColumnType("TEXT"); + + b.Property("JwtId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ReplacedByToken") + .HasColumnType("TEXT"); + + b.Property("Revoked") + .HasColumnType("INTEGER"); + + b.Property("RowVersion") + .IsRequired() + .HasColumnType("BLOB"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Used") + .HasColumnType("INTEGER"); + + b.Property("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("ReportID") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CommentID") + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("PastePID") + .HasColumnType("INTEGER"); + + b.Property("ReporterUUID") + .HasColumnType("TEXT"); + + b.Property("Status") + .HasColumnType("INTEGER"); + + b.Property("TargetType") + .HasColumnType("INTEGER"); + + b.Property("Type") + .HasColumnType("INTEGER"); + + b.Property("UpdatedAt") + .HasColumnType("INTEGER"); + + b.Property("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("UUID") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("DisplayName") + .HasColumnType("TEXT"); + + b.Property("Email") + .HasColumnType("TEXT"); + + b.Property("EmailVerified") + .HasColumnType("INTEGER"); + + b.Property("IsBanned") + .HasColumnType("INTEGER"); + + b.Property("LastLogin") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Roles") + .HasColumnType("INTEGER"); + + b.Property("UID") + .HasColumnType("INTEGER"); + + b.Property("Username") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("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("UserUUID") + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("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 + } + } +} diff --git a/SharpbinV3.Server/Migrations/20260618030444_EmailChangeTokens.cs b/SharpbinV3.Server/Migrations/20260618030444_EmailChangeTokens.cs new file mode 100644 index 0000000..46d82c8 --- /dev/null +++ b/SharpbinV3.Server/Migrations/20260618030444_EmailChangeTokens.cs @@ -0,0 +1,28 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SharpbinV3.Server.Migrations +{ + /// + public partial class EmailChangeTokens : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "TargetEmail", + table: "EmailVerificationTokens", + type: "TEXT", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "TargetEmail", + table: "EmailVerificationTokens"); + } + } +} diff --git a/SharpbinV3.Server/Migrations/20260618231408_uniqueEmails.Designer.cs b/SharpbinV3.Server/Migrations/20260618231408_uniqueEmails.Designer.cs new file mode 100644 index 0000000..4b171c6 --- /dev/null +++ b/SharpbinV3.Server/Migrations/20260618231408_uniqueEmails.Designer.cs @@ -0,0 +1,633 @@ +// +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 + { + /// + 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("UUID") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("KeyHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("LastUsedAt") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("UUID"); + + b.HasIndex("UserUUID"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Content") + .HasMaxLength(5000) + .HasColumnType("BLOB"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("IsCompressed") + .HasColumnType("INTEGER"); + + b.Property("OriginalSize") + .HasColumnType("INTEGER"); + + b.Property("ParentCommentID") + .HasColumnType("INTEGER"); + + b.Property("PastePID") + .HasColumnType("INTEGER"); + + b.Property("StoredSize") + .HasColumnType("INTEGER"); + + b.Property("UpdatedAt") + .HasColumnType("INTEGER"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CommentID") + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("Type") + .HasColumnType("INTEGER"); + + b.Property("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("UUID") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("ExpiresAt") + .HasColumnType("INTEGER"); + + b.Property("TargetEmail") + .HasColumnType("TEXT"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Type") + .HasColumnType("INTEGER"); + + b.Property("Used") + .HasColumnType("INTEGER"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("UUID"); + + b.HasIndex("UserUUID"); + + b.ToTable("EmailVerificationTokens"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b => + { + b.Property("PID") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AuthorUUID") + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("BLOB"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("EditedAt") + .HasColumnType("INTEGER"); + + b.Property("ExpiresAt") + .HasColumnType("INTEGER"); + + b.Property("ID") + .HasColumnType("TEXT"); + + b.Property("IsCompressed") + .HasColumnType("INTEGER"); + + b.Property("OriginalSize") + .HasColumnType("INTEGER"); + + b.Property("StoredSize") + .HasColumnType("INTEGER"); + + b.Property("Syntax") + .HasColumnType("TEXT"); + + b.Property("Title") + .HasColumnType("TEXT"); + + b.Property("UUID") + .HasColumnType("TEXT"); + + b.Property("Views") + .HasColumnType("INTEGER"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("PasteID") + .HasColumnType("INTEGER"); + + b.Property("Type") + .HasColumnType("INTEGER"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PastePID") + .HasColumnType("INTEGER"); + + b.Property("ViewedAt") + .HasColumnType("INTEGER"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("ExpiresAt") + .HasColumnType("TEXT"); + + b.Property("JwtId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ReplacedByToken") + .HasColumnType("TEXT"); + + b.Property("Revoked") + .HasColumnType("INTEGER"); + + b.Property("RowVersion") + .IsRequired() + .HasColumnType("BLOB"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Used") + .HasColumnType("INTEGER"); + + b.Property("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("ReportID") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CommentID") + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("PastePID") + .HasColumnType("INTEGER"); + + b.Property("ReporterUUID") + .HasColumnType("TEXT"); + + b.Property("Status") + .HasColumnType("INTEGER"); + + b.Property("TargetType") + .HasColumnType("INTEGER"); + + b.Property("Type") + .HasColumnType("INTEGER"); + + b.Property("UpdatedAt") + .HasColumnType("INTEGER"); + + b.Property("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("UUID") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("DisplayName") + .HasColumnType("TEXT"); + + b.Property("Email") + .HasColumnType("TEXT"); + + b.Property("EmailVerified") + .HasColumnType("INTEGER"); + + b.Property("IsBanned") + .HasColumnType("INTEGER"); + + b.Property("LastLogin") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Roles") + .HasColumnType("INTEGER"); + + b.Property("UID") + .HasColumnType("INTEGER"); + + b.Property("Username") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("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("UserUUID") + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("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 + } + } +} diff --git a/SharpbinV3.Server/Migrations/20260618231408_uniqueEmails.cs b/SharpbinV3.Server/Migrations/20260618231408_uniqueEmails.cs new file mode 100644 index 0000000..b22cdc2 --- /dev/null +++ b/SharpbinV3.Server/Migrations/20260618231408_uniqueEmails.cs @@ -0,0 +1,45 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SharpbinV3.Server.Migrations +{ + /// + public partial class uniqueEmails : Migration + { + /// + 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"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_Users_Email", + table: "Users"); + } + } +} diff --git a/SharpbinV3.Server/Migrations/AppDbContextModelSnapshot.cs b/SharpbinV3.Server/Migrations/AppDbContextModelSnapshot.cs index 2031808..2b1c3f5 100644 --- a/SharpbinV3.Server/Migrations/AppDbContextModelSnapshot.cs +++ b/SharpbinV3.Server/Migrations/AppDbContextModelSnapshot.cs @@ -132,6 +132,9 @@ namespace SharpbinV3.Server.Migrations b.Property("ExpiresAt") .HasColumnType("INTEGER"); + b.Property("TargetEmail") + .HasColumnType("TEXT"); + b.Property("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") diff --git a/SharpbinV3.Server/Services/AuthService.cs b/SharpbinV3.Server/Services/AuthService.cs index afe6c67..cff0254 100644 --- a/SharpbinV3.Server/Services/AuthService.cs +++ b/SharpbinV3.Server/Services/AuthService.cs @@ -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 jwtOptions, IOptions authOptions, IOptions 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 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 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 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 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 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}"; } } diff --git a/SharpbinV3.Server/Services/EmailTemplates.cs b/SharpbinV3.Server/Services/EmailTemplates.cs index eb48f57..c03354d 100644 --- a/SharpbinV3.Server/Services/EmailTemplates.cs +++ b/SharpbinV3.Server/Services/EmailTemplates.cs @@ -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 { { "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 + { + { "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 + { + { "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 { { "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 { { "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 { { "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 { { "USERNAME", username } }; + + return RenderTemplate("Account Deleted", contentTemplate, replacements); + } } } diff --git a/SharpbinV3.Server/Services/UserService.cs b/SharpbinV3.Server/Services/UserService.cs index e09811f..a33ef70 100644 --- a/SharpbinV3.Server/Services/UserService.cs +++ b/SharpbinV3.Server/Services/UserService.cs @@ -35,20 +35,33 @@ namespace SharpbinV3.Server.Services public Task GetByEmail(string email, bool withPastes = false) { + var normalizedEmail = NormalizeEmail(email); + if (normalizedEmail == null) + return Task.FromResult(null); + IQueryable 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 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(); + } } } diff --git a/SharpbinV3.Server/Utilities.cs b/SharpbinV3.Server/Utilities.cs index fc454af..a7d2511 100644 --- a/SharpbinV3.Server/Utilities.cs +++ b/SharpbinV3.Server/Utilities.cs @@ -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")}"; + } } }