feat: password resets

fix: frontend docker file
chore: format via csharpier again
This commit is contained in:
2026-06-18 21:15:34 -04:00
parent 67ccee736a
commit d4976ac9aa
34 changed files with 3236 additions and 26 deletions
+251 -3
View File
@@ -52,9 +52,11 @@ namespace SharpbinV3.Server.Controllers
var existingUser = await _userService.GetByUsername(request.Username);
if (existingUser != null)
return Conflict(new { success = false, message = "Username already exists." });
if (!string.IsNullOrEmpty(request.Email))
var normalizedEmail = UserService.NormalizeEmail(request.Email);
if (normalizedEmail != null)
{
var existingEmailUser = await _userService.GetByEmail(request.Email);
var existingEmailUser = await _userService.GetByEmail(normalizedEmail);
if (existingEmailUser != null)
return Conflict(new { success = false, message = "Email already in use." });
}
@@ -64,13 +66,16 @@ namespace SharpbinV3.Server.Controllers
User user;
try
{
user = await _authService.CreateUser(request.Username, request.Password, request.Email, request.DisplayName);
user = await _authService.CreateUser(request.Username, request.Password, normalizedEmail, request.DisplayName);
}
catch (DbUpdateException)
{
if (await _userService.GetByUsername(request.Username) != null)
return Conflict(new { success = false, message = "Username already exists." });
if (normalizedEmail != null && await _userService.GetByEmail(normalizedEmail) != null)
return Conflict(new { success = false, message = "Email already in use." });
throw;
}
@@ -178,6 +183,7 @@ namespace SharpbinV3.Server.Controllers
{
cf_turnstile_site_key = string.IsNullOrEmpty(authSettings.CF_Turnstile_SiteKey) ? null : authSettings.CF_Turnstile_SiteKey,
registration_enabled = authSettings.Registration_Enabled,
admins_require_2fa = authSettings.Admins_Require_2FA,
}
);
}
@@ -349,5 +355,247 @@ namespace SharpbinV3.Server.Controllers
else
return BadRequest(new { success = false, message });
}
[HttpPost]
[EnableRateLimiting("Strict")]
[Route("password/forgot")]
public async Task<IActionResult> RequestPasswordReset([FromBody] PasswordResetRequestDto request)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
if (!await _verification.VerifyAsync(new VerificationContext { Token = request.Token, Ip = HttpContext.GetRequestIP() }))
return BadRequest(new { success = false, message = "Verification failed." });
var result = await _authService.RequestPasswordResetForEmail(request.Email);
if (!result.success)
return Ok(new { success = true, message = "If an account exists for that email, a reset link has been sent." });
return Ok(new { success = true, message = result.message });
}
[HttpGet]
[Route("password/reset-info")]
public async Task<IActionResult> GetPasswordResetInfo([FromQuery] string token)
{
var info = await _authService.GetPasswordResetTokenInfo(token);
if (!info.success || info.user == null)
return BadRequest(new { success = false, message = info.message });
if (info.blocked)
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
return Ok(
new
{
success = true,
username = info.username,
requiresTotp = info.requiresTotp,
}
);
}
[HttpPost]
[Route("password/reset")]
[EnableRateLimiting("Sensitive")]
public async Task<IActionResult> ResetPassword([FromBody] PasswordResetDto request)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
var result = await _authService.ResetPasswordWithToken(request.Token, request.NewPassword, request.TotpCode);
if (!result.success)
{
if (result.message == "2FA is required to perform this action.")
return StatusCode(403, new { success = false, message = result.message });
return BadRequest(new { success = false, message = result.message });
}
return Ok(new { success = true, message = result.message });
}
[HttpPost]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
[Route("password/change")]
[EnableRateLimiting("Sensitive")]
public async Task<IActionResult> ChangePassword([FromBody] PasswordChangeDto request)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
var user = await _authService.GetUserFromHttpContext(HttpContext);
if (user == null)
return BadRequest(new { success = false, message = "User not found." });
var result = await _authService.ChangeOwnPassword(user, request.CurrentPassword, request.NewPassword, request.TotpCode);
if (!result.success)
{
if (result.message == "2FA is required to perform this action.")
return StatusCode(403, new { success = false, message = result.message });
return BadRequest(new { success = false, message = result.message });
}
return Ok(new { success = true, message = result.message });
}
[HttpPost]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
[Route("password/admin-reset-link/{uuid}")]
[EnableRateLimiting("Sensitive")]
public async Task<IActionResult> AdminGeneratePasswordResetLink(Guid uuid, [FromBody] AdminPasswordResetLinkDto request)
{
var jwtUser = HttpContext.GetJwtUser()!;
if (!jwtUser.Roles.HasFlag(Role.Admin))
return StatusCode(403, new { success = false, message = "You do not have permission to perform this action." });
var targetUser = await _userService.GetByUUID(uuid);
if (targetUser == null)
return NotFound(new { success = false, message = "User not found." });
if (jwtUser.TotpEnabled)
{
if (
string.IsNullOrWhiteSpace(request.TotpCode)
|| !await _totp.VerifyAsync(new VerificationContext { UserUUID = jwtUser.UUID, Code = request.TotpCode })
)
{
return Unauthorized(new { success = false, message = "Invalid TOTP code." });
}
}
else if (options.Value.Admins_Require_2FA)
{
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
}
var result = await _authService.GeneratePasswordResetLink(targetUser, sendEmail: !string.IsNullOrWhiteSpace(targetUser.Email));
if (!result.success)
{
if (result.retryAfter.HasValue)
{
Response.Headers.RetryAfter = Math.Ceiling(result.retryAfter.Value / 1000d).ToString();
return StatusCode(
StatusCodes.Status429TooManyRequests,
new
{
success = false,
message = result.message,
retryAfter = result.retryAfter,
}
);
}
return BadRequest(
new
{
success = false,
message = result.message,
retryAfter = result.retryAfter,
}
);
}
return Ok(
new
{
success = true,
message = result.message,
resetLink = result.resetLink,
}
);
}
[HttpPost]
[Authorize(Policy = "JwtOnly")]
[EnableRateLimiting("Sensitive")]
[Route("email/resend-verification")]
public async Task<IActionResult> ResendEmailVerification()
{
var user = await _authService.GetUserFromHttpContext(HttpContext);
if (user == null)
return BadRequest(new { success = false, message = "User not found." });
var result = await _authService.ResendEmailVerification(user);
if (!result.success)
{
if (result.retryAfter.HasValue)
{
Response.Headers.RetryAfter = Math.Ceiling(result.retryAfter.Value / 1000d).ToString();
return StatusCode(
StatusCodes.Status429TooManyRequests,
new
{
success = false,
message = result.message,
retryAfter = result.retryAfter,
}
);
}
return BadRequest(
new
{
success = false,
message = result.message,
retryAfter = result.retryAfter,
}
);
}
return Ok(new { success = true, message = result.message });
}
[HttpPost]
[Authorize(Policy = "JwtOnly")]
[EnableRateLimiting("Sensitive")]
[Route("email/change")]
public async Task<IActionResult> ChangeEmail([FromBody] ChangeEmailDto request)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
var user = await _authService.GetUserFromHttpContext(HttpContext);
if (user == null)
return BadRequest(new { success = false, message = "User not found." });
var totpEnabled = await _db.UserTotps.AnyAsync(t => t.UserUUID == user.UUID);
if (totpEnabled)
{
if (
string.IsNullOrWhiteSpace(request.TotpCode)
|| !await _totp.VerifyAsync(new VerificationContext { UserUUID = user.UUID, Code = request.TotpCode })
)
{
return Unauthorized(new { success = false, message = "Invalid TOTP code." });
}
}
var result = await _authService.RequestEmailChange(user, request.Email);
if (!result.success)
{
if (result.retryAfter.HasValue)
{
Response.Headers.RetryAfter = Math.Ceiling(result.retryAfter.Value / 1000d).ToString();
return StatusCode(
StatusCodes.Status429TooManyRequests,
new
{
success = false,
message = result.message,
retryAfter = result.retryAfter,
}
);
}
return BadRequest(
new
{
success = false,
message = result.message,
retryAfter = result.retryAfter,
}
);
}
return Ok(new { success = true, message = result.message });
}
}
}
+62 -11
View File
@@ -22,6 +22,7 @@ namespace SharpbinV3.Server.Controllers
[Route("api/[controller]")]
public class UserController(
UserService userService,
AuthService authService,
AppDbContext db,
TotpVerificationProvider totp,
VerificationService verificationService,
@@ -30,6 +31,7 @@ namespace SharpbinV3.Server.Controllers
) : ControllerBase
{
private readonly UserService _userService = userService;
private readonly AuthService _authService = authService;
private readonly AppDbContext _db = db;
private readonly TotpVerificationProvider _totp = totp;
private readonly VerificationService _verificationService = verificationService;
@@ -130,12 +132,12 @@ namespace SharpbinV3.Server.Controllers
if ((updatedUser.Roles.HasValue || updatedUser.IsBanned.HasValue) && !actorIsAdmin)
return StatusCode(403, new { success = false, message = "You do not have permission to modify this user." });
if (updatedUser.Email != null)
return BadRequest(new { success = false, message = "Use the email change endpoint to update email addresses." });
bool isSensitiveUpdate =
(updatedUser.Roles.HasValue && updatedUser.Roles.Value != targetUser.Roles) // updating roles
|| (updatedUser.IsBanned.HasValue && updatedUser.IsBanned.Value != targetUser.IsBanned) // updating ban status
|| (
updatedUser.Email != null && updatedUser.Email != targetUser.Email // updating email
);
|| (updatedUser.IsBanned.HasValue && updatedUser.IsBanned.Value != targetUser.IsBanned); // updating ban status
if (actorIsAdmin && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA && isSensitiveUpdate)
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
@@ -167,7 +169,6 @@ namespace SharpbinV3.Server.Controllers
targetUser.DisplayName = updatedUser.DisplayName ?? targetUser.DisplayName;
if (actorIsAdmin || isSelfUpdate)
{
targetUser.Email = updatedUser.Email ?? targetUser.Email;
targetUser.Visibility = updatedUser.Visibility ?? targetUser.Visibility;
}
if (actorIsAdmin)
@@ -193,6 +194,8 @@ namespace SharpbinV3.Server.Controllers
if (!jwtUser.Roles.HasFlag(Role.Admin) && user.UUID != jwtUser.UUID)
return StatusCode(403, new { success = false, message = "You do not have permission to delete this user." });
var isSelfDelete = user.UUID == jwtUser.UUID;
if (jwtUser.Roles.HasFlag(Role.Admin) && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA)
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
if (user.Roles.HasFlag(Role.Admin))
@@ -208,22 +211,70 @@ namespace SharpbinV3.Server.Controllers
return Unauthorized(new { message = "Invalid TOTP code." });
}
}
else
else if (isSelfDelete && user.EmailVerified && !string.IsNullOrWhiteSpace(user.Email))
{
if (
string.IsNullOrEmpty(dto.Token)
|| !await _verificationService.VerifyAsync(new VerificationContext { Token = dto.Token, Ip = HttpContext.GetRequestIP() })
)
if (string.IsNullOrEmpty(dto.Token) || !await _authService.VerifyAccountDeletionToken(user, dto.Token))
{
return Unauthorized(new { message = "Invalid verification token." });
return Unauthorized(new { message = "Invalid account deletion verification token." });
}
}
var deletedEmail = user.EmailVerified ? user.Email : null;
var deletedUsername = user.Username;
_db.Users.Remove(user);
await _db.SaveChangesAsync();
if (!string.IsNullOrWhiteSpace(deletedEmail))
await _authService.SendAccountDeletedNotification(deletedEmail, deletedUsername);
return Ok(new { message = "User deleted successfully." });
}
[HttpPost("uuid/{uuid}/delete-verification")]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
[EnableRateLimiting("Sensitive")]
public async Task<IActionResult> RequestDeleteVerification(Guid uuid)
{
var jwtUser = HttpContext.GetJwtUser()!;
if (jwtUser.UUID != uuid)
return StatusCode(403, new { success = false, message = "You do not have permission to delete this user." });
var user = await _userService.GetByUUID(uuid);
if (user == null)
return NotFound(new { success = false, message = "User not found." });
if (user.Roles.HasFlag(Role.Admin))
return StatusCode(403, new { success = false, message = "You cannot delete an admin user." });
if (jwtUser.TotpEnabled)
return BadRequest(new { success = false, message = "Use TOTP to delete this account." });
if (!user.EmailVerified || string.IsNullOrWhiteSpace(user.Email))
return BadRequest(new { success = false, message = "A verified email address is required for email deletion verification." });
var result = await _authService.RequestAccountDeletionVerification(user);
if (!result.success)
{
if (result.retryAfter.HasValue)
{
Response.Headers.RetryAfter = Math.Ceiling(result.retryAfter.Value / 1000d).ToString();
return StatusCode(
StatusCodes.Status429TooManyRequests,
new
{
success = false,
message = result.message,
retryAfter = result.retryAfter,
}
);
}
return BadRequest(new { success = false, message = result.message });
}
return Ok(new { success = true, message = result.message });
}
private async Task<IActionResult> BuildUserResponse(User user, int page = 1)
{
var isRequestedUser = HttpContext.User?.FindFirst("uuid")?.Value == user.UUID.ToString();
@@ -0,0 +1,7 @@
namespace SharpbinV3.Server.DTOs.Auth
{
public sealed class AdminPasswordResetLinkDto
{
public string? TotpCode { get; set; }
}
}
@@ -0,0 +1,13 @@
using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.Server.DTOs.Auth
{
public sealed class ChangeEmailDto
{
[Required]
[EmailAddress]
public string Email { get; set; } = string.Empty;
public string? TotpCode { get; set; }
}
}
@@ -0,0 +1,16 @@
using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.Server.DTOs.Auth
{
public sealed class PasswordChangeDto
{
[Required]
public string CurrentPassword { get; set; } = string.Empty;
[Required]
[StringLength(128, MinimumLength = 8)]
public string NewPassword { get; set; } = string.Empty;
public string? TotpCode { get; set; }
}
}
@@ -0,0 +1,16 @@
using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.Server.DTOs.Auth
{
public sealed class PasswordResetDto
{
[Required]
public string Token { get; set; } = string.Empty;
[Required]
[StringLength(128, MinimumLength = 8)]
public string NewPassword { get; set; } = string.Empty;
public string? TotpCode { get; set; }
}
}
@@ -0,0 +1,13 @@
using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.Server.DTOs.Auth
{
public sealed class PasswordResetRequestDto
{
[Required]
[EmailAddress]
public string Email { get; set; } = string.Empty;
public string? Token { get; set; }
}
}
+4
View File
@@ -43,6 +43,10 @@ namespace SharpbinV3.Server.Data
.HasIndex(r => r.TokenHash)
.IsUnique();
modelBuilder.Entity<User>()
.HasIndex(u => u.Email)
.IsUnique()
.HasFilter("\"Email\" IS NOT NULL");
modelBuilder.Entity<UserTotp>()
.HasOne(t => t.User)
@@ -17,6 +17,7 @@ namespace SharpbinV3.Server.Data.Entities
public required Guid UserUUID { get; set; }
public User User { get; set; } = null!;
public required string TokenHash { get; set; }
public string? TargetEmail { get; set; }
public long CreatedAt { get; set; } = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
public long ExpiresAt { get; set; }
public required EmailTokenType Type { get; set; }
@@ -3,6 +3,7 @@ namespace SharpbinV3.Server.Data.Enums
public enum SecurityAction
{
UpdateRoles = 1,
DeleteUser = 2
DeleteUser = 2,
GeneratePasswordResetLink = 3
}
}
@@ -0,0 +1,4 @@
<h2>Account Deleted</h2>
<p>Hi <strong>{{USERNAME}}</strong>,</p>
<p>Your Sharpbin account and all associated data have been permanently deleted.</p>
<p>No further action is needed.</p>
@@ -0,0 +1,6 @@
<h2>Confirm Account Deletion</h2>
<p>Hi <strong>{{USERNAME}}</strong>,</p>
<p>A request was made to permanently delete your Sharpbin account and all associated data.</p>
<p>Use this verification code to confirm account deletion:</p>
<div class="link-box">{{DELETE_TOKEN}}</div>
<p>This code expires in 24 hours. If you did not request this, do not share this code.</p>
@@ -0,0 +1,5 @@
<h2>Email Change Requested</h2>
<p>Hi <strong>{{USERNAME}}</strong>,</p>
<p>Your Sharpbin account email is being changed from <strong>{{OLD_EMAIL}}</strong> to <strong>{{NEW_EMAIL}}</strong>.</p>
<p>If you made this change, no action is needed.</p>
<p>If you did not request this change, secure your account immediately by changing your password and reviewing your active sessions.</p>
@@ -0,0 +1,5 @@
<h2>Email Address Changed</h2>
<p>Hi <strong>{{USERNAME}}</strong>,</p>
<p>Your Sharpbin account email was changed from <strong>{{OLD_EMAIL}}</strong> to <strong>{{NEW_EMAIL}}</strong>.</p>
<p>If you made this change, no action is needed.</p>
<p>If you did not make this change, secure your account immediately by changing your password and reviewing your active sessions.</p>
@@ -0,0 +1,5 @@
<h2>Password Changed</h2>
<p>Hi <strong>{{USERNAME}}</strong>,</p>
<p>The password for your Sharpbin account was just changed.</p>
<p>If you made this change, no action is needed.</p>
<p>If you did not make this change, secure your account immediately by changing your password again and reviewing active sessions.</p>
@@ -0,0 +1,12 @@
<h2>Reset Your Password</h2>
<p>Hi <strong>{{USERNAME}}</strong>,</p>
<p>We received a request to reset the password for your Sharpbin account.</p>
<p style="text-align: center;">
<a href="{{RESET_URL}}" class="button">Reset Password</a>
</p>
<p>If the button doesn't work, you can copy and paste this link into your browser:</p>
<div class="link-box">
<a href="{{RESET_URL}}">{{RESET_URL}}</a>
</div>
<p><strong>This link will expire in 24 hours.</strong></p>
<p>If you didn't request a password reset, you can ignore this email.</p>
@@ -0,0 +1,12 @@
<h2>Verify Your New Email Address</h2>
<p>Hi <strong>{{USERNAME}}</strong>,</p>
<p>Confirm this email address for your Sharpbin account by clicking the button below.</p>
<p style="text-align: center;">
<a href="{{VERIFICATION_URL}}" class="button">Verify Email Address</a>
</p>
<p>If the button doesn't work, you can copy and paste this link into your browser:</p>
<div class="link-box">
<a href="{{VERIFICATION_URL}}">{{VERIFICATION_URL}}</a>
</div>
<p><strong>This link will expire in 24 hours.</strong></p>
<p>If you did not request this change, you can ignore this email.</p>
@@ -0,0 +1,629 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SharpbinV3.Server.Data;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20260618030444_EmailChangeTokens")]
partial class EmailChangeTokens
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.3");
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<string>("KeyHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long?>("LastUsedAt")
.HasColumnType("INTEGER");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("UUID");
b.HasIndex("UserUUID");
b.ToTable("ApiKeys");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<byte[]>("Content")
.HasMaxLength(5000)
.HasColumnType("BLOB");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<bool>("IsCompressed")
.HasColumnType("INTEGER");
b.Property<long>("OriginalSize")
.HasColumnType("INTEGER");
b.Property<long?>("ParentCommentID")
.HasColumnType("INTEGER");
b.Property<long>("PastePID")
.HasColumnType("INTEGER");
b.Property<long>("StoredSize")
.HasColumnType("INTEGER");
b.Property<long?>("UpdatedAt")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("ParentCommentID");
b.HasIndex("PastePID");
b.HasIndex("UserUUID");
b.ToTable("Comments");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.CommentInteraction", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("CommentID")
.HasColumnType("INTEGER");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("CommentID", "Type");
b.HasIndex("CommentID", "UserUUID")
.IsUnique();
b.ToTable("CommentInteractions");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("TargetEmail")
.HasColumnType("TEXT");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<bool>("Used")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("UUID");
b.HasIndex("UserUUID");
b.ToTable("EmailVerificationTokens");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.Property<long>("PID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<Guid?>("AuthorUUID")
.HasColumnType("TEXT");
b.Property<byte[]>("Content")
.IsRequired()
.HasColumnType("BLOB");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long?>("EditedAt")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("ID")
.HasColumnType("TEXT");
b.Property<bool>("IsCompressed")
.HasColumnType("INTEGER");
b.Property<long>("OriginalSize")
.HasColumnType("INTEGER");
b.Property<long>("StoredSize")
.HasColumnType("INTEGER");
b.Property<string>("Syntax")
.HasColumnType("TEXT");
b.Property<string>("Title")
.HasColumnType("TEXT");
b.Property<Guid>("UUID")
.HasColumnType("TEXT");
b.Property<int>("Views")
.HasColumnType("INTEGER");
b.Property<int>("Visibility")
.HasColumnType("INTEGER");
b.HasKey("PID");
b.HasIndex("AuthorUUID");
b.HasIndex("ExpiresAt");
b.HasIndex("ID")
.IsUnique();
b.HasIndex("StoredSize");
b.HasIndex("Syntax");
b.HasIndex("UUID");
b.HasIndex("Views");
b.ToTable("Pastes");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteInteraction", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long>("PasteID")
.HasColumnType("INTEGER");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("PasteID", "Type");
b.HasIndex("PasteID", "UserUUID")
.IsUnique();
b.ToTable("PasteInteractions");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("PastePID")
.HasColumnType("INTEGER");
b.Property<long>("ViewedAt")
.HasColumnType("INTEGER");
b.Property<string>("ViewerHash")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("PastePID", "ViewerHash")
.IsUnique();
b.ToTable("PasteViews");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("TEXT");
b.Property<DateTimeOffset>("ExpiresAt")
.HasColumnType("TEXT");
b.Property<string>("JwtId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("ReplacedByToken")
.HasColumnType("TEXT");
b.Property<bool>("Revoked")
.HasColumnType("INTEGER");
b.Property<byte[]>("RowVersion")
.IsRequired()
.HasColumnType("BLOB");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<bool>("Used")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("TokenHash")
.IsUnique();
b.HasIndex("UserUUID");
b.ToTable("RefreshTokens");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b =>
{
b.Property<int>("ReportID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long?>("CommentID")
.HasColumnType("INTEGER");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<string>("Description")
.HasMaxLength(1000)
.HasColumnType("TEXT");
b.Property<long?>("PastePID")
.HasColumnType("INTEGER");
b.Property<Guid>("ReporterUUID")
.HasColumnType("TEXT");
b.Property<int>("Status")
.HasColumnType("INTEGER");
b.Property<int>("TargetType")
.HasColumnType("INTEGER");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<long?>("UpdatedAt")
.HasColumnType("INTEGER");
b.Property<Guid?>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("ReportID");
b.HasIndex("CommentID");
b.HasIndex("PastePID");
b.HasIndex("ReportID")
.IsUnique();
b.HasIndex("ReporterUUID");
b.HasIndex("TargetType");
b.HasIndex("UserUUID");
b.ToTable("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<string>("DisplayName")
.HasColumnType("TEXT");
b.Property<string>("Email")
.HasColumnType("TEXT");
b.Property<bool>("EmailVerified")
.HasColumnType("INTEGER");
b.Property<bool>("IsBanned")
.HasColumnType("INTEGER");
b.Property<long?>("LastLogin")
.HasColumnType("INTEGER");
b.Property<string>("PasswordHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Roles")
.HasColumnType("INTEGER");
b.Property<long?>("UID")
.HasColumnType("INTEGER");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Visibility")
.HasColumnType("INTEGER");
b.HasKey("UUID");
b.HasIndex("UID");
b.HasIndex("UUID")
.IsUnique();
b.HasIndex("Username")
.IsUnique();
b.ToTable("Users");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b =>
{
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<byte[]>("EncryptedSecret")
.IsRequired()
.HasColumnType("BLOB");
b.HasKey("UserUUID");
b.ToTable("UserTotps");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("ApiKeys")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Comment", "ParentComment")
.WithMany("Replies")
.HasForeignKey("ParentCommentID")
.OnDelete(DeleteBehavior.Restrict);
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("Comments")
.HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Comments")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("ParentComment");
b.Navigation("Paste");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.CommentInteraction", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Comment", "Comment")
.WithMany("Interactions")
.HasForeignKey("CommentID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Comment");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("EmailVerificationTokens")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Pastes")
.HasForeignKey("AuthorUUID")
.OnDelete(DeleteBehavior.Cascade);
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteInteraction", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("Interactions")
.HasForeignKey("PasteID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Paste");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("PasteViews")
.HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Paste");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("RefreshTokens")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Comment", null)
.WithMany("Reports")
.HasForeignKey("CommentID")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("Reports")
.HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Reports")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.SetNull);
b.Navigation("Paste");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithOne("Totp")
.HasForeignKey("SharpbinV3.Server.Data.Entities.UserTotp", "UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b =>
{
b.Navigation("Interactions");
b.Navigation("Replies");
b.Navigation("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.Navigation("Comments");
b.Navigation("Interactions");
b.Navigation("PasteViews");
b.Navigation("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Navigation("ApiKeys");
b.Navigation("Comments");
b.Navigation("EmailVerificationTokens");
b.Navigation("Pastes");
b.Navigation("RefreshTokens");
b.Navigation("Reports");
b.Navigation("Totp");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,28 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
/// <inheritdoc />
public partial class EmailChangeTokens : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "TargetEmail",
table: "EmailVerificationTokens",
type: "TEXT",
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "TargetEmail",
table: "EmailVerificationTokens");
}
}
}
@@ -0,0 +1,633 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SharpbinV3.Server.Data;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20260618231408_uniqueEmails")]
partial class uniqueEmails
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.3");
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<string>("KeyHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long?>("LastUsedAt")
.HasColumnType("INTEGER");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("UUID");
b.HasIndex("UserUUID");
b.ToTable("ApiKeys");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<byte[]>("Content")
.HasMaxLength(5000)
.HasColumnType("BLOB");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<bool>("IsCompressed")
.HasColumnType("INTEGER");
b.Property<long>("OriginalSize")
.HasColumnType("INTEGER");
b.Property<long?>("ParentCommentID")
.HasColumnType("INTEGER");
b.Property<long>("PastePID")
.HasColumnType("INTEGER");
b.Property<long>("StoredSize")
.HasColumnType("INTEGER");
b.Property<long?>("UpdatedAt")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("ParentCommentID");
b.HasIndex("PastePID");
b.HasIndex("UserUUID");
b.ToTable("Comments");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.CommentInteraction", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("CommentID")
.HasColumnType("INTEGER");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("CommentID", "Type");
b.HasIndex("CommentID", "UserUUID")
.IsUnique();
b.ToTable("CommentInteractions");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("TargetEmail")
.HasColumnType("TEXT");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<bool>("Used")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("UUID");
b.HasIndex("UserUUID");
b.ToTable("EmailVerificationTokens");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.Property<long>("PID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<Guid?>("AuthorUUID")
.HasColumnType("TEXT");
b.Property<byte[]>("Content")
.IsRequired()
.HasColumnType("BLOB");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long?>("EditedAt")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("ID")
.HasColumnType("TEXT");
b.Property<bool>("IsCompressed")
.HasColumnType("INTEGER");
b.Property<long>("OriginalSize")
.HasColumnType("INTEGER");
b.Property<long>("StoredSize")
.HasColumnType("INTEGER");
b.Property<string>("Syntax")
.HasColumnType("TEXT");
b.Property<string>("Title")
.HasColumnType("TEXT");
b.Property<Guid>("UUID")
.HasColumnType("TEXT");
b.Property<int>("Views")
.HasColumnType("INTEGER");
b.Property<int>("Visibility")
.HasColumnType("INTEGER");
b.HasKey("PID");
b.HasIndex("AuthorUUID");
b.HasIndex("ExpiresAt");
b.HasIndex("ID")
.IsUnique();
b.HasIndex("StoredSize");
b.HasIndex("Syntax");
b.HasIndex("UUID");
b.HasIndex("Views");
b.ToTable("Pastes");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteInteraction", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long>("PasteID")
.HasColumnType("INTEGER");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("PasteID", "Type");
b.HasIndex("PasteID", "UserUUID")
.IsUnique();
b.ToTable("PasteInteractions");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("PastePID")
.HasColumnType("INTEGER");
b.Property<long>("ViewedAt")
.HasColumnType("INTEGER");
b.Property<string>("ViewerHash")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("PastePID", "ViewerHash")
.IsUnique();
b.ToTable("PasteViews");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("TEXT");
b.Property<DateTimeOffset>("ExpiresAt")
.HasColumnType("TEXT");
b.Property<string>("JwtId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("ReplacedByToken")
.HasColumnType("TEXT");
b.Property<bool>("Revoked")
.HasColumnType("INTEGER");
b.Property<byte[]>("RowVersion")
.IsRequired()
.HasColumnType("BLOB");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<bool>("Used")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("TokenHash")
.IsUnique();
b.HasIndex("UserUUID");
b.ToTable("RefreshTokens");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b =>
{
b.Property<int>("ReportID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long?>("CommentID")
.HasColumnType("INTEGER");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<string>("Description")
.HasMaxLength(1000)
.HasColumnType("TEXT");
b.Property<long?>("PastePID")
.HasColumnType("INTEGER");
b.Property<Guid>("ReporterUUID")
.HasColumnType("TEXT");
b.Property<int>("Status")
.HasColumnType("INTEGER");
b.Property<int>("TargetType")
.HasColumnType("INTEGER");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<long?>("UpdatedAt")
.HasColumnType("INTEGER");
b.Property<Guid?>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("ReportID");
b.HasIndex("CommentID");
b.HasIndex("PastePID");
b.HasIndex("ReportID")
.IsUnique();
b.HasIndex("ReporterUUID");
b.HasIndex("TargetType");
b.HasIndex("UserUUID");
b.ToTable("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<string>("DisplayName")
.HasColumnType("TEXT");
b.Property<string>("Email")
.HasColumnType("TEXT");
b.Property<bool>("EmailVerified")
.HasColumnType("INTEGER");
b.Property<bool>("IsBanned")
.HasColumnType("INTEGER");
b.Property<long?>("LastLogin")
.HasColumnType("INTEGER");
b.Property<string>("PasswordHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Roles")
.HasColumnType("INTEGER");
b.Property<long?>("UID")
.HasColumnType("INTEGER");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Visibility")
.HasColumnType("INTEGER");
b.HasKey("UUID");
b.HasIndex("Email")
.IsUnique()
.HasFilter("\"Email\" IS NOT NULL");
b.HasIndex("UID");
b.HasIndex("UUID")
.IsUnique();
b.HasIndex("Username")
.IsUnique();
b.ToTable("Users");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b =>
{
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<byte[]>("EncryptedSecret")
.IsRequired()
.HasColumnType("BLOB");
b.HasKey("UserUUID");
b.ToTable("UserTotps");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("ApiKeys")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Comment", "ParentComment")
.WithMany("Replies")
.HasForeignKey("ParentCommentID")
.OnDelete(DeleteBehavior.Restrict);
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("Comments")
.HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Comments")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("ParentComment");
b.Navigation("Paste");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.CommentInteraction", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Comment", "Comment")
.WithMany("Interactions")
.HasForeignKey("CommentID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Comment");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("EmailVerificationTokens")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Pastes")
.HasForeignKey("AuthorUUID")
.OnDelete(DeleteBehavior.Cascade);
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteInteraction", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("Interactions")
.HasForeignKey("PasteID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Paste");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("PasteViews")
.HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Paste");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("RefreshTokens")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Comment", null)
.WithMany("Reports")
.HasForeignKey("CommentID")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("Reports")
.HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Reports")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.SetNull);
b.Navigation("Paste");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithOne("Totp")
.HasForeignKey("SharpbinV3.Server.Data.Entities.UserTotp", "UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b =>
{
b.Navigation("Interactions");
b.Navigation("Replies");
b.Navigation("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.Navigation("Comments");
b.Navigation("Interactions");
b.Navigation("PasteViews");
b.Navigation("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Navigation("ApiKeys");
b.Navigation("Comments");
b.Navigation("EmailVerificationTokens");
b.Navigation("Pastes");
b.Navigation("RefreshTokens");
b.Navigation("Reports");
b.Navigation("Totp");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,45 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
/// <inheritdoc />
public partial class uniqueEmails : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql(
"""
UPDATE "Users"
SET "Email" = NULL, "EmailVerified" = 0
WHERE "Email" IS NULL OR trim("Email") = '';
"""
);
migrationBuilder.Sql(
"""
UPDATE "Users"
SET "Email" = lower(trim("Email"))
WHERE "Email" IS NOT NULL;
"""
);
migrationBuilder.CreateIndex(
name: "IX_Users_Email",
table: "Users",
column: "Email",
unique: true,
filter: "\"Email\" IS NOT NULL");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_Users_Email",
table: "Users");
}
}
}
@@ -132,6 +132,9 @@ namespace SharpbinV3.Server.Migrations
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("TargetEmail")
.HasColumnType("TEXT");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("TEXT");
@@ -418,6 +421,10 @@ namespace SharpbinV3.Server.Migrations
b.HasKey("UUID");
b.HasIndex("Email")
.IsUnique()
.HasFilter("\"Email\" IS NOT NULL");
b.HasIndex("UID");
b.HasIndex("UUID")
+407 -5
View File
@@ -6,8 +6,11 @@ using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.DTOs;
using SharpbinV3.Server.DTOs.Auth;
using SharpbinV3.Server.Extensions;
using SharpbinV3.Server.Services.Verification;
using SharpbinV3.Server.Services.Verification.Providers;
using SharpbinV3.Server.Settings;
using Bcrypt = BCrypt.Net.BCrypt;
@@ -27,6 +30,7 @@ namespace SharpbinV3.Server.Services
public sealed class AuthService(
AppDbContext db,
EmailService email,
TotpVerificationProvider totp,
IOptions<JWTSettings> jwtOptions,
IOptions<AuthSettings> authOptions,
IOptions<AppSettings> appSettings,
@@ -35,11 +39,15 @@ namespace SharpbinV3.Server.Services
{
private readonly AppDbContext _db = db;
private readonly EmailService _email = email;
private readonly TotpVerificationProvider _totp = totp;
private readonly JWTSettings _jwtSettings = jwtOptions.Value;
private readonly AuthSettings _authSettings = authOptions.Value;
private readonly AppSettings _appSettings = appSettings.Value;
private readonly ILogger _logger = logger;
private const int EmailVerificationTokenLength = 64;
private static readonly TimeSpan EmailActionCooldown = TimeSpan.FromHours(12);
private static readonly TimeSpan EmailVerificationLifetime = TimeSpan.FromDays(1);
private static readonly TimeSpan PasswordResetLifetime = TimeSpan.FromDays(1);
public async Task<User> CreateUser(string username, string password, string? email, string? displayName)
{
@@ -47,7 +55,7 @@ namespace SharpbinV3.Server.Services
{
Username = UserService.NormalizeUsername(username),
PasswordHash = Bcrypt.HashPassword(password),
Email = email,
Email = UserService.NormalizeEmail(email),
DisplayName = displayName,
UUID = Guid.CreateVersion7(),
};
@@ -185,7 +193,7 @@ namespace SharpbinV3.Server.Services
{
var existingUser = await _db.Users.FirstOrDefaultAsync(u => u.UUID == user.UUID) ?? throw new Exception("User not found");
existingUser.Username = UserService.NormalizeUsername(user.Username);
existingUser.Email = user.Email;
existingUser.Email = UserService.NormalizeEmail(user.Email);
existingUser.DisplayName = user.DisplayName;
existingUser.Roles = user.Roles;
existingUser.LastLogin = user.LastLogin;
@@ -203,6 +211,101 @@ namespace SharpbinV3.Server.Services
await _db.SaveChangesAsync();
}
public async Task<(bool success, string message, long? retryAfter, string? resetLink)> GeneratePasswordResetLink(
User user,
bool sendEmail = true
)
{
return await IssuePasswordResetTokenAsync(user, sendEmail: sendEmail, invalidateExisting: true, exposeLink: true);
}
public async Task<(bool success, string message, bool requiresTotp, bool blocked, string username, User? user)> GetPasswordResetTokenInfo(
string token
)
{
var tokenEntity = await GetValidPasswordResetToken(token);
if (tokenEntity == null)
return (false, "Token is expired or already used.", false, false, string.Empty, null);
var user = tokenEntity.User;
if (user == null)
return (false, "Token is expired or already used.", false, false, string.Empty, null);
var state = await GetPasswordResetTwoFactorState(user);
return (true, "Token is valid.", state.requiresTotp, state.blocked, user.Username, user);
}
public async Task<(bool success, string message)> ChangeOwnPassword(User user, string currentPassword, string newPassword, string? totpCode)
{
if (!Bcrypt.Verify(currentPassword, user.PasswordHash))
return (false, "Current password is incorrect.");
var totpState = await GetPasswordResetTwoFactorState(user);
if (totpState.blocked)
return (false, "2FA is required to perform this action.");
if (totpState.requiresTotp)
{
if (
string.IsNullOrWhiteSpace(totpCode) || !await _totp.VerifyAsync(new VerificationContext { UserUUID = user.UUID, Code = totpCode })
)
return (false, "Invalid TOTP code.");
}
if (!RegisterUserDto.ValidatePassword().IsMatch(newPassword))
return (false, "Password should have at least 8 characters, including uppercase, lowercase, and digits.");
var originalEmail = user.Email;
await using var transaction = await _db.Database.BeginTransactionAsync();
await ReplacePasswordAsync(user, newPassword, saveChanges: false);
await _db.SaveChangesAsync();
await transaction.CommitAsync();
if (!string.IsNullOrWhiteSpace(originalEmail))
{
await _email.SendAsync(originalEmail, "Sharpbin Password Changed", EmailTemplates.PasswordChanged(user.Username));
}
return (true, "Password updated successfully.");
}
public async Task<(bool success, string message)> ResetPasswordWithToken(string token, string newPassword, string? totpCode)
{
if (!RegisterUserDto.ValidatePassword().IsMatch(newPassword))
return (false, "Password should have at least 8 characters, including uppercase, lowercase, and digits.");
var tokenEntity = await GetValidPasswordResetToken(token);
if (tokenEntity == null || tokenEntity.User == null)
return (false, "Token is expired or already used.");
var user = tokenEntity.User;
var totpState = await GetPasswordResetTwoFactorState(user);
if (totpState.blocked)
return (false, "2FA is required to perform this action.");
if (totpState.requiresTotp)
{
if (
string.IsNullOrWhiteSpace(totpCode) || !await _totp.VerifyAsync(new VerificationContext { UserUUID = user.UUID, Code = totpCode })
)
return (false, "Invalid TOTP code.");
}
await using var transaction = await _db.Database.BeginTransactionAsync();
var originalEmail = user.Email;
tokenEntity.Used = true;
await ReplacePasswordAsync(user, newPassword, saveChanges: false);
await _db.SaveChangesAsync();
await transaction.CommitAsync();
if (!string.IsNullOrWhiteSpace(originalEmail))
{
await _email.SendAsync(originalEmail, "Sharpbin Password Changed", EmailTemplates.PasswordChanged(user.Username));
}
return (true, "Password reset successfully.");
}
public async Task<User?> GetUserFromHttpContext(HttpContext context)
{
var apiKey = context.GetApiKeyFromContext();
@@ -216,15 +319,165 @@ namespace SharpbinV3.Server.Services
return await _db.Users.FirstOrDefaultAsync(u => u.UUID == userUUID);
}
public async Task SendEmailVerification(User user)
public async Task<(bool success, string message, long? retryAfter)> ResendEmailVerification(User user)
{
if (string.IsNullOrWhiteSpace(user.Email))
return (false, "No email address is set for this account.", null);
if (user.EmailVerified)
return (false, "Email is already verified.", null);
var cooldown = await GetEmailTokenCooldown(user.UUID, EmailTokenType.VerifyEmail);
if (cooldown > TimeSpan.Zero)
return (
false,
$"Please wait {Utilities.FormatDuration(cooldown)} before requesting another verification email.",
Utilities.TimeSpanToMilliseconds(cooldown)
);
await SendEmailVerification(user, invalidateExisting: true);
return (true, "Verification email sent.", null);
}
public async Task<(bool success, string message, long? retryAfter)> RequestPasswordResetForEmail(string email)
{
var normalizedEmail = UserService.NormalizeEmail(email);
if (normalizedEmail == null)
return (true, "If an account exists for that email, a reset link has been sent.", null);
var user = await _db.Users.FirstOrDefaultAsync(u => u.Email == normalizedEmail);
if (user == null)
return (true, "If an account exists for that email, a reset link has been sent.", null);
await IssuePasswordResetTokenAsync(user, sendEmail: true, invalidateExisting: true, exposeLink: false);
return (true, "If an account exists for that email, a reset link has been sent.", null);
}
public async Task<(bool success, string message, long? retryAfter)> RequestAccountDeletionVerification(User user)
{
if (string.IsNullOrWhiteSpace(user.Email) || !user.EmailVerified)
return (false, "A verified email address is required for email deletion verification.", null);
var cooldown = await GetEmailTokenCooldown(user.UUID, EmailTokenType.DeleteAccount);
if (cooldown > TimeSpan.Zero)
return (
false,
$"Please wait {Utilities.FormatDuration(cooldown)} before requesting another account deletion email.",
Utilities.TimeSpanToMilliseconds(cooldown)
);
await InvalidateActiveTokens(user.UUID, EmailTokenType.DeleteAccount);
var token = Utilities.GenerateSecureRandomString(EmailVerificationTokenLength);
var tokenHash = Utilities.ComputeSha256(token);
var emailBody = EmailTemplates.DeleteAccountVerification(user.Username, token);
await _email.SendAsync(user.Email, "Confirm Account Deletion - Sharpbin", emailBody);
await _db.EmailVerificationTokens.AddAsync(
new EmailVerificationToken
{
TokenHash = tokenHash,
UserUUID = user.UUID,
User = user,
ExpiresAt = DateTimeOffset.UtcNow.Add(EmailVerificationLifetime).ToUnixTimeMilliseconds(),
Type = EmailTokenType.DeleteAccount,
}
);
await _db.SaveChangesAsync();
return (true, "Account deletion verification email sent.", null);
}
public async Task<bool> VerifyAccountDeletionToken(User user, string token)
{
if (token.Length != EmailVerificationTokenLength)
return false;
var tokenHash = Utilities.ComputeSha256(token);
var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
var tokenEntity = await _db.EmailVerificationTokens.FirstOrDefaultAsync(t =>
t.UserUUID == user.UUID && t.TokenHash == tokenHash && t.Type == EmailTokenType.DeleteAccount && !t.Used && t.ExpiresAt >= now
);
if (tokenEntity == null)
return false;
tokenEntity.Used = true;
await _db.SaveChangesAsync();
return true;
}
public async Task SendAccountDeletedNotification(string email, string username)
{
if (string.IsNullOrWhiteSpace(email))
return;
await _email.SendAsync(email, "Sharpbin Account Deleted", EmailTemplates.AccountDeleted(username));
}
public async Task<(bool success, string message, long? retryAfter)> RequestEmailChange(User user, string requestedEmail)
{
var newEmail = UserService.NormalizeEmail(requestedEmail);
if (newEmail == null)
return (false, "Email is required.", null);
if (string.Equals(user.Email, newEmail, StringComparison.OrdinalIgnoreCase))
return (false, "That email is already on your account.", null);
var existingEmailUser = await _db.Users.FirstOrDefaultAsync(u => u.Email == newEmail && u.UUID != user.UUID);
if (existingEmailUser != null)
return (false, "Email already in use.", null);
var cooldown = await GetEmailTokenCooldown(user.UUID, EmailTokenType.ChangeEmail);
if (cooldown > TimeSpan.Zero)
return (
false,
$"Please wait {Utilities.FormatDuration(cooldown)} before changing your email again.",
Utilities.TimeSpanToMilliseconds(cooldown)
);
await InvalidateActiveEmailTokens(user.UUID);
var token = Utilities.GenerateSecureRandomString(EmailVerificationTokenLength);
var tokenHash = Utilities.ComputeSha256(token);
var verificationUrl = BuildVerificationUrl(token);
var emailBody = EmailTemplates.VerifyChangedEmail(verificationUrl, user.Username);
await _email.SendAsync(newEmail, "Verify Your New Email - Sharpbin", emailBody);
if (!string.IsNullOrWhiteSpace(user.Email))
{
var notificationBody = EmailTemplates.EmailChangeRequested(user.Username, user.Email, newEmail);
await _email.SendAsync(user.Email, "Sharpbin Email Change Requested", notificationBody);
}
var verificationToken = new EmailVerificationToken
{
TokenHash = tokenHash,
UserUUID = user.UUID,
User = user,
TargetEmail = newEmail,
ExpiresAt = DateTimeOffset.UtcNow.Add(EmailVerificationLifetime).ToUnixTimeMilliseconds(),
Type = EmailTokenType.ChangeEmail,
};
await _db.EmailVerificationTokens.AddAsync(verificationToken);
await _db.SaveChangesAsync();
return (true, "Verification email sent to the new address.", null);
}
public async Task SendEmailVerification(User user, bool invalidateExisting = true)
{
if (string.IsNullOrWhiteSpace(user.Email))
return;
if (invalidateExisting)
await InvalidateActiveEmailTokens(user.UUID);
string token = Utilities.GenerateSecureRandomString(EmailVerificationTokenLength);
string tokenHash = Utilities.ComputeSha256(token);
string verificationUrl = $"{(_appSettings.Https ? "https" : "http")}://{_appSettings.Domain}/verify-email?token={token}";
string verificationUrl = BuildVerificationUrl(token);
string emailBody = EmailTemplates.VerifyEmail(verificationUrl, user.Username);
await _email.SendAsync(user.Email, "Verify Your Email - Sharpbin", emailBody);
@@ -233,13 +486,59 @@ namespace SharpbinV3.Server.Services
TokenHash = tokenHash,
UserUUID = user.UUID,
User = user,
ExpiresAt = DateTimeOffset.UtcNow.AddDays(1).ToUnixTimeMilliseconds(),
ExpiresAt = DateTimeOffset.UtcNow.Add(EmailVerificationLifetime).ToUnixTimeMilliseconds(),
Type = EmailTokenType.VerifyEmail,
};
await _db.EmailVerificationTokens.AddAsync(verificationToken);
await _db.SaveChangesAsync();
}
public async Task<(bool success, string message, long? retryAfter, string? resetLink)> IssuePasswordResetTokenAsync(
User user,
bool sendEmail,
bool invalidateExisting,
bool exposeLink
)
{
if (string.IsNullOrWhiteSpace(user.Email) && sendEmail)
return (false, "No email address is set for this account.", null, null);
var cooldown = await GetEmailTokenCooldown(user.UUID, EmailTokenType.ResetPassword);
if (cooldown > TimeSpan.Zero)
return (
false,
$"Please wait {Utilities.FormatDuration(cooldown)} before requesting another password reset link.",
Utilities.TimeSpanToMilliseconds(cooldown),
null
);
if (invalidateExisting)
await InvalidateActiveTokens(user.UUID, EmailTokenType.ResetPassword);
var token = Utilities.GenerateSecureRandomString(EmailVerificationTokenLength);
var tokenHash = Utilities.ComputeSha256(token);
var resetLink = BuildResetPasswordUrl(token);
if (sendEmail && !string.IsNullOrWhiteSpace(user.Email))
{
var emailBody = EmailTemplates.ResetPassword(user.Username, resetLink);
await _email.SendAsync(user.Email, "Reset Your Password - Sharpbin", emailBody);
}
var verificationToken = new EmailVerificationToken
{
TokenHash = tokenHash,
UserUUID = user.UUID,
User = user,
ExpiresAt = DateTimeOffset.UtcNow.Add(PasswordResetLifetime).ToUnixTimeMilliseconds(),
Type = EmailTokenType.ResetPassword,
};
await _db.EmailVerificationTokens.AddAsync(verificationToken);
await _db.SaveChangesAsync();
return (true, sendEmail ? "Password reset email sent." : "Password reset link generated.", null, exposeLink ? resetLink : null);
}
public async Task<(bool success, string message)> VerifyEmailVerificationToken(string token)
{
if (token.Length != EmailVerificationTokenLength)
@@ -258,13 +557,116 @@ namespace SharpbinV3.Server.Services
if (verificationToken != null && !verificationToken.Used)
{
if (verificationToken.Type == EmailTokenType.ChangeEmail)
{
if (string.IsNullOrWhiteSpace(verificationToken.TargetEmail))
return (false, "Token is invalid.");
var normalizedTargetEmail = UserService.NormalizeEmail(verificationToken.TargetEmail);
if (normalizedTargetEmail == null)
return (false, "Token is invalid.");
var existingEmailUser = await _db.Users.FirstOrDefaultAsync(u =>
u.Email == normalizedTargetEmail && u.UUID != verificationToken.UserUUID
);
if (existingEmailUser != null)
return (false, "Email already in use.");
if (!string.IsNullOrWhiteSpace(verificationToken.User.Email))
{
var notificationBody = EmailTemplates.EmailChanged(
verificationToken.User.Username,
verificationToken.User.Email,
normalizedTargetEmail
);
await _email.SendAsync(verificationToken.User.Email, "Sharpbin Email Address Changed", notificationBody);
}
verificationToken.User.Email = normalizedTargetEmail;
}
verificationToken.Used = true;
verificationToken.User.EmailVerified = true;
await InvalidateActiveEmailTokens(verificationToken.UserUUID);
await _db.SaveChangesAsync();
}
await _db.SaveChangesAsync();
return (true, "Email successfully verified.");
}
private async Task ReplacePasswordAsync(User user, string newPassword, bool saveChanges = true)
{
var existingUser = await _db.Users.FirstOrDefaultAsync(u => u.UUID == user.UUID) ?? throw new Exception("User not found");
existingUser.PasswordHash = Bcrypt.HashPassword(newPassword);
await _db
.RefreshTokens.Where(rt => rt.UserUUID == user.UUID && !rt.Revoked)
.ExecuteUpdateAsync(setters => setters.SetProperty(rt => rt.Revoked, true).SetProperty(rt => rt.Used, true));
await InvalidateActiveTokens(user.UUID, EmailTokenType.ResetPassword);
_db.Users.Update(existingUser);
if (saveChanges)
await _db.SaveChangesAsync();
}
private async Task<EmailVerificationToken?> GetValidPasswordResetToken(string token)
{
if (token.Length != EmailVerificationTokenLength)
return null;
var tokenHash = Utilities.ComputeSha256(token);
return await _db
.EmailVerificationTokens.Include(t => t.User)
.FirstOrDefaultAsync(t => t.TokenHash == tokenHash && t.Type == EmailTokenType.ResetPassword);
}
private async Task<(bool requiresTotp, bool blocked)> GetPasswordResetTwoFactorState(User user)
{
var totpEnabled = await _db.UserTotps.AnyAsync(t => t.UserUUID == user.UUID);
var blocked = user.Roles.HasFlag(Role.Admin) && _authSettings.Admins_Require_2FA && !totpEnabled;
return (totpEnabled, blocked);
}
private async Task InvalidateActiveTokens(Guid userUUID, params EmailTokenType[] types)
{
var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
var tokenTypes = types.Length > 0 ? types : [EmailTokenType.VerifyEmail, EmailTokenType.ChangeEmail, EmailTokenType.ResetPassword];
await _db
.EmailVerificationTokens.Where(t => t.UserUUID == userUUID && !t.Used && t.ExpiresAt >= now && tokenTypes.Contains(t.Type))
.ExecuteUpdateAsync(setters => setters.SetProperty(t => t.Used, true));
}
private async Task InvalidateActiveEmailTokens(Guid userUUID)
{
await InvalidateActiveTokens(userUUID, EmailTokenType.VerifyEmail, EmailTokenType.ChangeEmail);
}
private async Task InvalidateActivePasswordResetTokens(Guid userUUID)
{
await InvalidateActiveTokens(userUUID, EmailTokenType.ResetPassword);
}
private async Task<TimeSpan> GetEmailTokenCooldown(Guid userUUID, EmailTokenType type)
{
var lastCreatedAt = await _db
.EmailVerificationTokens.Where(t => t.UserUUID == userUUID && t.Type == type)
.OrderByDescending(t => t.CreatedAt)
.Select(t => (long?)t.CreatedAt)
.FirstOrDefaultAsync();
if (lastCreatedAt == null)
return TimeSpan.Zero;
var nextAllowedAt = DateTimeOffset.FromUnixTimeMilliseconds(lastCreatedAt.Value).Add(EmailActionCooldown);
var remaining = nextAllowedAt - DateTimeOffset.UtcNow;
return remaining > TimeSpan.Zero ? remaining : TimeSpan.Zero;
}
private string BuildVerificationUrl(string token) =>
$"{(_appSettings.Https ? "https" : "http")}://{_appSettings.Domain}/verify-email?token={token}";
private string BuildResetPasswordUrl(string token) =>
$"{(_appSettings.Https ? "https" : "http")}://{_appSettings.Domain}/reset-password?token={token}";
}
}
@@ -37,5 +37,71 @@ namespace SharpbinV3.Server.Services
return RenderTemplate("Verify Your Email", contentTemplate, replacements);
}
public static string VerifyChangedEmail(string verificationUrl, string username)
{
var contentTemplate = LoadEmbeddedResource("SharpbinV3.Server.EmailTemplates.VerifyChangedEmail.html");
var replacements = new Dictionary<string, string> { { "USERNAME", username }, { "VERIFICATION_URL", verificationUrl } };
return RenderTemplate("Verify Your New Email", contentTemplate, replacements);
}
public static string EmailChangeRequested(string username, string oldEmail, string newEmail)
{
var contentTemplate = LoadEmbeddedResource("SharpbinV3.Server.EmailTemplates.EmailChangeRequested.html");
var replacements = new Dictionary<string, string>
{
{ "USERNAME", username },
{ "OLD_EMAIL", oldEmail },
{ "NEW_EMAIL", newEmail },
};
return RenderTemplate("Email Change Requested", contentTemplate, replacements);
}
public static string EmailChanged(string username, string oldEmail, string newEmail)
{
var contentTemplate = LoadEmbeddedResource("SharpbinV3.Server.EmailTemplates.EmailChanged.html");
var replacements = new Dictionary<string, string>
{
{ "USERNAME", username },
{ "OLD_EMAIL", oldEmail },
{ "NEW_EMAIL", newEmail },
};
return RenderTemplate("Email Address Changed", contentTemplate, replacements);
}
public static string ResetPassword(string username, string resetUrl)
{
var contentTemplate = LoadEmbeddedResource("SharpbinV3.Server.EmailTemplates.ResetPassword.html");
var replacements = new Dictionary<string, string> { { "USERNAME", username }, { "RESET_URL", resetUrl } };
return RenderTemplate("Reset Your Password", contentTemplate, replacements);
}
public static string PasswordChanged(string username)
{
var contentTemplate = LoadEmbeddedResource("SharpbinV3.Server.EmailTemplates.PasswordChanged.html");
var replacements = new Dictionary<string, string> { { "USERNAME", username } };
return RenderTemplate("Password Changed", contentTemplate, replacements);
}
public static string DeleteAccountVerification(string username, string deleteToken)
{
var contentTemplate = LoadEmbeddedResource("SharpbinV3.Server.EmailTemplates.DeleteAccountVerification.html");
var replacements = new Dictionary<string, string> { { "USERNAME", username }, { "DELETE_TOKEN", deleteToken } };
return RenderTemplate("Confirm Account Deletion", contentTemplate, replacements);
}
public static string AccountDeleted(string username)
{
var contentTemplate = LoadEmbeddedResource("SharpbinV3.Server.EmailTemplates.AccountDeleted.html");
var replacements = new Dictionary<string, string> { { "USERNAME", username } };
return RenderTemplate("Account Deleted", contentTemplate, replacements);
}
}
}
+14 -1
View File
@@ -35,20 +35,33 @@ namespace SharpbinV3.Server.Services
public Task<User?> GetByEmail(string email, bool withPastes = false)
{
var normalizedEmail = NormalizeEmail(email);
if (normalizedEmail == null)
return Task.FromResult<User?>(null);
IQueryable<User> query = _db.Users;
if (withPastes)
query = query.Include(u => u.Pastes);
return query.FirstOrDefaultAsync(u => u.Email == email);
return query.FirstOrDefaultAsync(u => u.Email == normalizedEmail);
}
public async Task<User> Update(User user)
{
user.Username = NormalizeUsername(user.Username);
user.Email = NormalizeEmail(user.Email);
_db.Users.Update(user);
await _db.SaveChangesAsync();
return user;
}
public static string NormalizeUsername(string username) => username.ToLowerInvariant();
public static string? NormalizeEmail(string? email)
{
if (string.IsNullOrWhiteSpace(email))
return null;
return email.Trim().ToLowerInvariant();
}
}
}
+14
View File
@@ -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")}";
}
}
}