From 6bea6c49bef1eea4dfd72d962b4e06e20b64594f Mon Sep 17 00:00:00 2001 From: whoswhip Date: Fri, 9 Jan 2026 15:24:19 -0500 Subject: [PATCH] Revert "chore: format via csharpier" This reverts commit 7a2eb699f476eb909a72bc04191bc5b496a85a79. --- .../Authorization/NotBannedHandler.cs | 14 +- .../Authorization/NotBannedRequirement.cs | 4 +- .../Controllers/AuthController.cs | 126 +++------ .../Controllers/PasteController.cs | 267 ++++++------------ .../Controllers/UserController.cs | 86 ++---- .../DTOs/Auth/RefreshTokenDto.cs | 1 - .../DTOs/Auth/TurnstileResponseDto.cs | 1 - SharpbinV3.Server/DTOs/User/LoginUserDto.cs | 1 - .../DTOs/User/RegisterUserDto.cs | 29 +- SharpbinV3.Server/DTOs/User/UpdateUserDto.cs | 30 +- .../Extensions/HttpContextExtensions.cs | 25 +- .../Migrations/20251125015039_Init.cs | 71 ++--- .../20251125053617_ImprovePastes.cs | 21 +- .../Migrations/20251125055340_PasteContent.cs | 10 +- .../Migrations/20251125061310_GrammarFix.cs | 12 +- .../20251228173503_UserGrammarFix.cs | 17 +- .../20251228175338_LongFileSizes.cs | 10 +- .../Migrations/20251231161600_UserUUIDKey.cs | 104 +++---- .../20260104211956_UserUIDAutoIncrement.cs | 35 +-- .../Migrations/20260104212417_UserUIDIndex.cs | 7 +- .../20260104212733_UserUIDNonUnique.cs | 22 +- .../20260106211303_NullableAuthorUUID.cs | 6 +- .../Migrations/20260107181640_UserTotps.cs | 11 +- SharpbinV3.Server/Program.cs | 78 ++--- SharpbinV3.Server/Services/AuthService.cs | 99 +++---- .../Services/CompressionService.cs | 8 +- .../Services/PasteCleanUpService.cs | 12 +- SharpbinV3.Server/Services/PasteService.cs | 38 +-- SharpbinV3.Server/Services/UserService.cs | 2 +- .../Providers/TotpVerificationProvider.cs | 61 +--- .../TurnstileVerificationProvider.cs | 18 +- .../Verification/VerificationContext.cs | 1 + .../Verification/VerificationService.cs | 5 +- SharpbinV3.Server/SharpbinV3.Server.csproj | 12 +- SharpbinV3.Server/Utilities.cs | 4 +- 35 files changed, 464 insertions(+), 784 deletions(-) diff --git a/SharpbinV3.Server/Authorization/NotBannedHandler.cs b/SharpbinV3.Server/Authorization/NotBannedHandler.cs index 0773926..70a05c8 100644 --- a/SharpbinV3.Server/Authorization/NotBannedHandler.cs +++ b/SharpbinV3.Server/Authorization/NotBannedHandler.cs @@ -1,17 +1,15 @@ -using System.Security.Claims; -using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Authorization; +using System.Security.Claims; namespace SharpbinV3.Server.Authorization { - public sealed class NotBannedHandler(bool requireAuth = false) - : AuthorizationHandler + public sealed class NotBannedHandler(bool requireAuth = false) : AuthorizationHandler { private readonly bool _requireAuth = requireAuth; protected override Task HandleRequirementAsync( AuthorizationHandlerContext context, - NotBannedRequirement requirement - ) + NotBannedRequirement requirement) { var isAuthenticated = context.User.Identity?.IsAuthenticated ?? false; @@ -19,8 +17,8 @@ namespace SharpbinV3.Server.Authorization return Task.CompletedTask; var isBanned = context.User.Claims.Any(c => - (c.Type == ClaimTypes.Role || c.Type == "role") && c.Value == "403" - ); + (c.Type == ClaimTypes.Role || c.Type == "role") && + c.Value == "403"); if (!isBanned) context.Succeed(requirement); diff --git a/SharpbinV3.Server/Authorization/NotBannedRequirement.cs b/SharpbinV3.Server/Authorization/NotBannedRequirement.cs index 28bb17f..cf09026 100644 --- a/SharpbinV3.Server/Authorization/NotBannedRequirement.cs +++ b/SharpbinV3.Server/Authorization/NotBannedRequirement.cs @@ -2,5 +2,7 @@ namespace SharpbinV3.Server.Authorization { - public class NotBannedRequirement : IAuthorizationRequirement { } + public class NotBannedRequirement : IAuthorizationRequirement + { + } } diff --git a/SharpbinV3.Server/Controllers/AuthController.cs b/SharpbinV3.Server/Controllers/AuthController.cs index 5ec6ce9..b4dabf7 100644 --- a/SharpbinV3.Server/Controllers/AuthController.cs +++ b/SharpbinV3.Server/Controllers/AuthController.cs @@ -19,14 +19,8 @@ namespace SharpbinV3.Server.Controllers { [ApiController] [Route("api/[controller]")] - public class AuthController( - UserService userService, - AuthService authService, - IOptions options, - VerificationService verification, - TotpVerificationProvider totp, - AppDbContext db - ) : ControllerBase + public class AuthController(UserService userService, AuthService authService, IOptions options, + VerificationService verification, TotpVerificationProvider totp, AppDbContext db) : ControllerBase { private readonly AuthService _authService = authService; private readonly UserService _userService = userService; @@ -43,15 +37,11 @@ namespace SharpbinV3.Server.Controllers return BadRequest(new { message = "Registration is disabled." }); if (!ModelState.IsValid) return BadRequest(ModelState); - if ( - !await _verification.VerifyAsync( - new VerificationContext - { - Token = request.Token, - Ip = HttpContext.GetRequestIP(), - } - ) - ) + if (!await _verification.VerifyAsync(new VerificationContext + { + Token = request.Token, + Ip = HttpContext.GetRequestIP() + })) return BadRequest(new { message = "Verification failed." }); var existingUser = await _userService.GetByUsername(request.Username); @@ -64,30 +54,22 @@ namespace SharpbinV3.Server.Controllers return Conflict(new { message = "Email already in use." }); } if (!string.IsNullOrEmpty(request.DisplayName) && request.DisplayName.Length > 26) - return BadRequest( - new { message = "Display name should not exceed 26 characters." } - ); + return BadRequest(new { message = "Display name should not exceed 26 characters." }); - var user = await _authService.CreateUser( - request.Username, - request.Password, - request.Email, - request.DisplayName - ); - return Ok( - new + var user = await _authService.CreateUser(request.Username, request.Password, request.Email, request.DisplayName); + return Ok(new + { + message = "User registered successfully.", + user = new { - message = "User registered successfully.", - user = new - { - user.UID, - user.UUID, - user.Username, - user.Email, - user.DisplayName, - user.Roles, - }, + user.UID, + user.UUID, + user.Username, + user.Email, + user.DisplayName, + user.Roles } + } ); } @@ -99,15 +81,11 @@ namespace SharpbinV3.Server.Controllers if (string.IsNullOrEmpty(request.Username) && string.IsNullOrEmpty(request.Email)) return BadRequest(new { message = "Username or email is required." }); - if ( - !await _verification.VerifyAsync( - new VerificationContext - { - Token = request.Token, - Ip = HttpContext.GetRequestIP(), - } - ) - ) + if (!await _verification.VerifyAsync(new VerificationContext + { + Token = request.Token, + Ip = HttpContext.GetRequestIP() + })) return BadRequest(new { message = "Verification failed." }); User? user = null; @@ -116,8 +94,7 @@ namespace SharpbinV3.Server.Controllers if (user == null && !string.IsNullOrEmpty(request.Email)) user = await _userService.GetByEmail(request.Email); - if (user == null) - return BadRequest(new { message = "Invalid username/email or password." }); + if (user == null) return BadRequest(new { message = "Invalid username/email or password." }); if (!Bcrypt.Verify(request.Password, user.PasswordHash)) return BadRequest(new { message = "Invalid username/email or password." }); @@ -126,9 +103,11 @@ namespace SharpbinV3.Server.Controllers { if (string.IsNullOrWhiteSpace(request.TotpCode)) return BadRequest(new { message = "TOTP code is required." }); - var totpValid = await _totp.VerifyAsync( - new VerificationContext { UserUUID = user.UUID, Code = request.TotpCode } - ); + var totpValid = await _totp.VerifyAsync(new VerificationContext + { + UserUUID = user.UUID, + Code = request.TotpCode + }); if (!totpValid) return BadRequest(new { message = "Invalid TOTP code." }); } @@ -136,7 +115,6 @@ namespace SharpbinV3.Server.Controllers await _authService.UpdateLoginTime(user); return Ok(new { token.Result }); } - [HttpPost] [Route("refresh")] [EnableRateLimiting("Sliding")] @@ -144,10 +122,7 @@ namespace SharpbinV3.Server.Controllers { try { - var jwtResult = await _authService.RefreshJWTToken( - request.Token, - request.RefreshToken - ); + var jwtResult = await _authService.RefreshJWTToken(request.Token, request.RefreshToken); return Ok(new { token = jwtResult }); } catch (Exception ex) @@ -161,15 +136,11 @@ namespace SharpbinV3.Server.Controllers public async Task GetSiteInfo() { var authSettings = options.Value; - return Ok( - new - { - cf_turnstile_site_key = string.IsNullOrEmpty(authSettings.CF_Turnstile_SiteKey) - ? null - : authSettings.CF_Turnstile_SiteKey, - registration_enabled = authSettings.Registration_Enabled, - } - ); + return Ok(new + { + cf_turnstile_site_key = string.IsNullOrEmpty(authSettings.CF_Turnstile_SiteKey) ? null : authSettings.CF_Turnstile_SiteKey, + registration_enabled = authSettings.Registration_Enabled + }); } [HttpGet] @@ -178,8 +149,7 @@ namespace SharpbinV3.Server.Controllers public async Task StartTotpEnrollment() { var user = await _authService.GetUserFromHttpContext(HttpContext); - if (user is null) - return BadRequest(new { message = "User not found." }); + if (user is null) return BadRequest(new { message = "User not found." }); var secret = _totp.GenerateSecret(); var secretBase32 = _totp.ToBase32(secret); @@ -194,12 +164,9 @@ namespace SharpbinV3.Server.Controllers public async Task EnableTotp([FromBody] EnableTotpDto request) { var uuidClaim = User.Claims.FirstOrDefault(c => c.Type == "UUID")?.Value; - if (string.IsNullOrEmpty(uuidClaim)) - return Unauthorized(); + if (string.IsNullOrEmpty(uuidClaim)) return Unauthorized(); var uuid = Guid.Parse(uuidClaim); - if ( - string.IsNullOrWhiteSpace(request.Secret) || string.IsNullOrWhiteSpace(request.Code) - ) + if (string.IsNullOrWhiteSpace(request.Secret) || string.IsNullOrWhiteSpace(request.Code)) return BadRequest(new { message = "Secret and code are required." }); if (!_totp.VerifyWithSecretBase32(request.Secret, request.Code)) @@ -228,18 +195,17 @@ namespace SharpbinV3.Server.Controllers public async Task DisableTotp([FromBody] DisableTotpDto dto) { var user = await _authService.GetUserFromHttpContext(HttpContext); - if (user == null) - return BadRequest(new { message = "User not found." }); + if (user == null) return BadRequest(new { message = "User not found." }); if (string.IsNullOrWhiteSpace(dto.Code)) return BadRequest(new { message = "TOTP code is required." }); var existing = await _db.UserTotps.FirstOrDefaultAsync(t => t.UserUUID == user.UUID); if (existing is null) return BadRequest(new { message = "TOTP is not enabled." }); - if ( - !_totp - .VerifyAsync(new VerificationContext { UserUUID = user.UUID, Code = dto.Code }) - .Result - ) + if (!_totp.VerifyAsync(new VerificationContext + { + UserUUID = user.UUID, + Code = dto.Code + }).Result) return BadRequest(new { message = "Invalid TOTP code." }); _db.UserTotps.Remove(existing); diff --git a/SharpbinV3.Server/Controllers/PasteController.cs b/SharpbinV3.Server/Controllers/PasteController.cs index 6b88aa1..2ee31d2 100644 --- a/SharpbinV3.Server/Controllers/PasteController.cs +++ b/SharpbinV3.Server/Controllers/PasteController.cs @@ -12,13 +12,7 @@ namespace SharpbinV3.Server.Controllers { [Route("api/[controller]")] [ApiController] - public class PasteController( - PasteService pasteService, - VerificationService verificationService, - AuthService authService, - IOptions options, - IOptions authSettings - ) : ControllerBase + public class PasteController(PasteService pasteService, VerificationService verificationService, AuthService authService, IOptions options, IOptions authSettings) : ControllerBase { private readonly PasteService _pasteService = pasteService; private readonly VerificationService _verificationService = verificationService; @@ -29,116 +23,77 @@ namespace SharpbinV3.Server.Controllers [HttpPost] [Route("create")] [Authorize(Policy = "NotBanned")] - public async Task CreatePaste( - string title = "", - string syntax = "plaintext", - int visibility = 0, - long expiresAt = 0, - string? token = null - ) + public async Task CreatePaste(string title = "", string syntax = "plaintext", int visibility = 0, long expiresAt = 0, string? token = null) { if (!await _pasteService.ValidateExpiresAt(expiresAt)) return BadRequest(new { message = "Invalid expiration time." }); if (!await _pasteService.ValidateVisibility(visibility)) - return BadRequest( - new { message = "Invalid visibility level. Must be between 0 and 2." } - ); + return BadRequest(new { message = "Invalid visibility level. Must be between 0 and 2." }); if (!await _pasteService.ValidateSyntax(syntax)) return BadRequest(new { message = "Invalid syntax." }); if (!await _pasteService.ValidateTitle(title)) - return BadRequest( - new - { - message = $"Invalid title. Must be less than {_pasteSettings.MaxTitleLength} characters.", - } - ); + return BadRequest(new { message = $"Invalid title. Must be less than {_pasteSettings.MaxTitleLength} characters." }); string content = await new StreamReader(Request.Body).ReadToEndAsync(); if (content.Length == 0) return BadRequest(new { message = "Paste content cannot be empty." }); - if ( - System.Text.Encoding.UTF8.GetByteCount(content) > _pasteSettings.MaxPasteSizeInBytes - ) - return BadRequest( - new - { - message = $"Paste size exceeds the maximum allowed size of {_pasteSettings.MaxPasteSizeInBytes} bytes.", - } - ); + if (System.Text.Encoding.UTF8.GetByteCount(content) > _pasteSettings.MaxPasteSizeInBytes) + return BadRequest(new { message = $"Paste size exceeds the maximum allowed size of {_pasteSettings.MaxPasteSizeInBytes} bytes." }); - if ( - _pasteSettings.RequiresVerfication - && !await _verificationService.VerifyAsync( - new VerificationContext { Token = token, Ip = HttpContext.GetRequestIP() } - ) - ) + if (_pasteSettings.RequiresVerfication && !await _verificationService.VerifyAsync(new VerificationContext + { + Token = token, + Ip = HttpContext.GetRequestIP() + })) return BadRequest(new { message = "Verification failed." }); var user = await _authService.GetUserFromHttpContext(HttpContext); - Paste paste = await _pasteService.Create( - user, - content, - title, - syntax, - visibility, - expiresAt, - _pasteSettings.EnablePasteCompression - ); - return Ok( - new - { - paste.ID, - paste.UUID, - paste.IsCompressed, - paste.Size, - paste.TrueSize, - paste.ExpiresAt, - } - ); + Paste paste = await _pasteService.Create(user, content, title, syntax, visibility, expiresAt, _pasteSettings.EnablePasteCompression); + return Ok(new + { + paste.ID, + paste.UUID, + paste.IsCompressed, + paste.Size, + paste.TrueSize, + paste.ExpiresAt + }); } - [HttpGet] [Route("{id}")] public async Task GetPasteByID(string id) { var paste = await _pasteService.Get(id); - if (paste == null) - return NotFound(); - return Ok( - new + if (paste == null) return NotFound(); + return Ok(new + { + paste.ID, + paste.UUID, + paste.Title, + paste.Size, + paste.TrueSize, + paste.IsCompressed, + paste.Views, + paste.Syntax, + paste.Visibility, + paste.ExpiresAt, + paste.EditedAt, + Author = paste.User != null && paste.User.Visibility == 0 ? new { - paste.ID, - paste.UUID, - paste.Title, - paste.Size, - paste.TrueSize, - paste.IsCompressed, - paste.Views, - paste.Syntax, - paste.Visibility, - paste.ExpiresAt, - paste.EditedAt, - Author = paste.User != null && paste.User.Visibility == 0 - ? new - { - paste.User.UID, - paste.User.UUID, - paste.User.Username, - paste.User.DisplayName, - paste.User.Visibility, - } - : null, - } - ); + paste.User.UID, + paste.User.UUID, + paste.User.Username, + paste.User.DisplayName, + paste.User.Visibility + } : null + }); } - [HttpGet] [Route("{id}/raw")] public async Task GetRawPasteByID(string id) { var paste = await _pasteService.Get(id); - if (paste == null) - return NotFound(); + if (paste == null) return NotFound(); if (paste.IsCompressed) { Response.Headers.Append("Content-Encoding", "gzip"); @@ -156,63 +111,34 @@ namespace SharpbinV3.Server.Controllers public async Task EditPaste(string id) { string content = await new StreamReader(Request.Body).ReadToEndAsync(); - if (content == null || id == null) - return StatusCode(400, new { success = false, message = "Invalid request." }); + if (content == null || id == null) return StatusCode(400, new { success = false, message = "Invalid request." }); var paste = await _pasteService.Get(id); - if (paste == null) - return StatusCode(404, new { success = false, message = "Paste not found." }); + if (paste == null) return StatusCode(404, new { success = false, message = "Paste not found." }); var user = HttpContext.GetJwtUser(); - if (user == null) - return StatusCode( - 403, - new - { - success = false, - message = "You do not have permission to edit this paste.", - } - ); + if (user == null) return StatusCode(403, new { success = false, message = "You do not have permission to edit this paste." }); var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255); if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole) - return StatusCode( - 403, - new - { - success = false, - message = "You do not have permission to edit this paste.", - } - ); + return StatusCode(403, new { success = false, message = "You do not have permission to edit this paste." }); if (user.Roles.Contains(255) && !user.TotpEnabled && _authSettings.Admins_Require_2FA) - return StatusCode( - 403, - new { success = false, message = "2FA is required to perform this action." } - ); + return StatusCode(403, new { success = false, message = "2FA is required to perform this action." }); bool result = await _pasteService.EditText(paste, content); - if (!result) - return StatusCode( - 500, - new { success = false, message = "An error occurred while editing the paste." } - ); + if (!result) return StatusCode(500, new { success = false, message = "An error occurred while editing the paste." }); return Ok(new { message = "Paste edited successfully." }); } [HttpPatch] [Route("{id}/modify")] [Authorize(Policy = "AuthAndNotBanned")] - public async Task ModifyPasteMetadata( - string id, - [FromBody] UpdatePasteDto request - ) + public async Task ModifyPasteMetadata(string id, [FromBody] UpdatePasteDto request) { var paste = await _pasteService.Get(id); - if (paste == null) - return NotFound(); + if (paste == null) return NotFound(); var user = HttpContext.GetJwtUser(); - if (user == null) - return Forbid(); + if (user == null) return Forbid(); var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255); @@ -232,53 +158,41 @@ namespace SharpbinV3.Server.Controllers if (!await _pasteService.ValidateExpiresAt(paste.ExpiresAt)) return BadRequest(new { message = "Invalid expiration time." }); if (!await _pasteService.ValidateVisibility(paste.Visibility)) - return BadRequest( - new { message = "Invalid visibility level. Must be between 0 and 2." } - ); + return BadRequest(new { message = "Invalid visibility level. Must be between 0 and 2." }); if (!await _pasteService.ValidateSyntax(paste.Syntax ?? "plaintext")) return BadRequest(new { message = "Invalid syntax." }); if (!await _pasteService.ValidateTitle(paste.Title ?? "")) - return BadRequest( - new - { - message = $"Invalid title. Must be less than {_pasteSettings.MaxTitleLength} characters.", - } - ); + return BadRequest(new { message = $"Invalid title. Must be less than {_pasteSettings.MaxTitleLength} characters." }); var newPaste = await _pasteService.Edit(paste); - return Ok( - new + return Ok(new + { + message = "Paste metadata updated successfully.", + paste = new { - message = "Paste metadata updated successfully.", - paste = new - { - newPaste.ID, - newPaste.UUID, - newPaste.Title, - newPaste.Size, - newPaste.TrueSize, - newPaste.IsCompressed, - newPaste.Views, - newPaste.Syntax, - newPaste.Visibility, - newPaste.ExpiresAt, - }, + newPaste.ID, + newPaste.UUID, + newPaste.Title, + newPaste.Size, + newPaste.TrueSize, + newPaste.IsCompressed, + newPaste.Views, + newPaste.Syntax, + newPaste.Visibility, + newPaste.ExpiresAt } - ); + }); } - [HttpDelete] [Route("{id}/delete")] [Authorize(Policy = "AuthAndNotBanned")] public async Task DeletePaste(string id) { var paste = await _pasteService.Get(id); - if (paste == null) - return NotFound(); + if (paste == null) return NotFound(); var user = HttpContext.GetJwtUser(); - if (user == null) - return Forbid(); + if (user == null) return Forbid(); var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255); if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole) @@ -287,8 +201,7 @@ namespace SharpbinV3.Server.Controllers return Forbid(); bool result = await _pasteService.Delete(paste); - if (!result) - return NotFound(); + if (!result) return NotFound(); return Ok(new { message = "Paste deleted successfully." }); } @@ -297,22 +210,20 @@ namespace SharpbinV3.Server.Controllers public async Task GetRecentPastes() { var results = await _pasteService.GetList(0, 50, true); - return Ok( - results.Select(p => new - { - p.ID, - p.UUID, - p.Title, - p.Size, - p.TrueSize, - p.IsCompressed, - p.Views, - p.Syntax, - p.Visibility, - p.ExpiresAt, - p.EditedAt, - }) - ); + return Ok(results.Select(p => new + { + p.ID, + p.UUID, + p.Title, + p.Size, + p.TrueSize, + p.IsCompressed, + p.Views, + p.Syntax, + p.Visibility, + p.ExpiresAt, + p.EditedAt + })); } [HttpGet] @@ -326,11 +237,11 @@ namespace SharpbinV3.Server.Controllers { new { value = 0, displayName = "Public" }, new { value = 1, displayName = "Unlisted" }, - new { value = 2, displayName = "Private" }, + new { value = 2, displayName = "Private" } }, maxTitleLength = _pasteSettings.MaxTitleLength, maxPasteSize = _pasteSettings.MaxPasteSizeInBytes, - requiresVerification = _pasteSettings.RequiresVerfication, + requiresVerification = _pasteSettings.RequiresVerfication }; return Ok(options); } diff --git a/SharpbinV3.Server/Controllers/UserController.cs b/SharpbinV3.Server/Controllers/UserController.cs index 9a59e93..b3fc85a 100644 --- a/SharpbinV3.Server/Controllers/UserController.cs +++ b/SharpbinV3.Server/Controllers/UserController.cs @@ -16,13 +16,7 @@ namespace SharpbinV3.Server.Controllers { [ApiController] [Route("api/[controller]")] - public class UserController( - UserService userService, - AppDbContext db, - TotpVerificationProvider totp, - VerificationService verificationService, - IOptions authSettings - ) : ControllerBase + public class UserController(UserService userService, AppDbContext db, TotpVerificationProvider totp, VerificationService verificationService, IOptions authSettings) : ControllerBase { private readonly UserService _userService = userService; private readonly AppDbContext _db = db; @@ -58,16 +52,12 @@ namespace SharpbinV3.Server.Controllers [HttpPatch("uuid/{uuid}")] [Authorize] - public async Task UpdateByUUID( - Guid uuid, - [FromBody] UpdateUserDto updatedUser - ) + public async Task UpdateByUUID(Guid uuid, [FromBody] UpdateUserDto updatedUser) { if (!ModelState.IsValid) return BadRequest(ModelState); var jwtUser = HttpContext.GetJwtUser(); - if (jwtUser == null) - return Forbid(); + if (jwtUser == null) return Forbid(); var user = await _userService.GetByUUID(uuid); if (user == null) return NotFound(); @@ -75,11 +65,7 @@ namespace SharpbinV3.Server.Controllers return Forbid(); if (user.Roles.Contains(255) && !jwtUser.Roles.Contains(255)) return Forbid(); - if ( - jwtUser.Roles.Contains(255) - && !jwtUser.TotpEnabled - && _authSettings.Admins_Require_2FA - ) + if (jwtUser.Roles.Contains(255) && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA) return Forbid(); user.DisplayName = updatedUser.DisplayName ?? user.DisplayName; @@ -92,16 +78,11 @@ namespace SharpbinV3.Server.Controllers { if (updatedUser.Roles.Contains(255) && jwtUser.TotpEnabled) { - if ( - string.IsNullOrEmpty(updatedUser.TotpCode) - || !await _totp.VerifyAsync( - new VerificationContext - { - UserUUID = jwtUser.UUID, - Code = updatedUser.TotpCode, - } - ) - ) + if (string.IsNullOrEmpty(updatedUser.TotpCode) || !await _totp.VerifyAsync(new VerificationContext + { + UserUUID = jwtUser.UUID, + Code = updatedUser.TotpCode + })) { return Unauthorized(new { message = "Invalid TOTP code." }); } @@ -118,44 +99,32 @@ namespace SharpbinV3.Server.Controllers public async Task DeleteByUUID(Guid uuid, [FromBody] DeleteUserDto dto) { var jwtUser = HttpContext.GetJwtUser(); - if (jwtUser == null) - return Forbid(); + if (jwtUser == null) return Forbid(); var user = await _userService.GetByUUID(uuid); - if (user == null) - return Forbid(); + if (user == null) return Forbid(); if (!jwtUser.Roles.Any(r => r == 255) && user.UUID != jwtUser.UUID) return Forbid(); - if ( - jwtUser.Roles.Contains(255) - && !jwtUser.TotpEnabled - && _authSettings.Admins_Require_2FA - ) + if (jwtUser.Roles.Contains(255) && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA) return Forbid(); if (jwtUser.TotpEnabled) { - if ( - string.IsNullOrEmpty(dto.TotpCode) - || !await _totp.VerifyAsync( - new VerificationContext { UserUUID = jwtUser.UUID, Code = dto.TotpCode } - ) - ) + if (string.IsNullOrEmpty(dto.TotpCode) || !await _totp.VerifyAsync(new VerificationContext + { + UserUUID = jwtUser.UUID, + Code = dto.TotpCode + })) { return Unauthorized(new { message = "Invalid TOTP code." }); } } else { - if ( - string.IsNullOrEmpty(dto.Token) - || !await _verificationService.VerifyAsync( - new VerificationContext - { - Token = dto.Token, - Ip = HttpContext.GetRequestIP(), - } - ) - ) + if (string.IsNullOrEmpty(dto.Token) || !await _verificationService.VerifyAsync(new VerificationContext + { + Token = dto.Token, + Ip = HttpContext.GetRequestIP() + })) { return Unauthorized(new { message = "Invalid verification token." }); } @@ -168,8 +137,7 @@ namespace SharpbinV3.Server.Controllers private async Task BuildUserResponse(User user, int page = 1) { - var isAuthenticatedUser = - HttpContext.User?.FindFirst("UUID")?.Value == user.UUID.ToString(); + var isAuthenticatedUser = HttpContext.User?.FindFirst("UUID")?.Value == user.UUID.ToString(); var pasteQuery = _db.Pastes.AsNoTracking().Where(p => p.AuthorUUID == user.UUID); if (!isAuthenticatedUser) { @@ -202,7 +170,7 @@ namespace SharpbinV3.Server.Controllers p.Views, p.Visibility, p.EditedAt, - p.ExpiresAt, + p.ExpiresAt }) .ToListAsync(); @@ -211,7 +179,7 @@ namespace SharpbinV3.Server.Controllers Page = page, PageSize = pageSize, TotalCount = totalCount, - TotalPages = totalPages, + TotalPages = totalPages }; if (isAuthenticatedUser) @@ -227,7 +195,7 @@ namespace SharpbinV3.Server.Controllers user.Roles, user.Visibility, Pastes = pastes, - Pagination = pagination, + Pagination = pagination }; } @@ -239,7 +207,7 @@ namespace SharpbinV3.Server.Controllers user.DisplayName, user.Roles, Pastes = pastes, - Pagination = pagination, + Pagination = pagination }; } } diff --git a/SharpbinV3.Server/DTOs/Auth/RefreshTokenDto.cs b/SharpbinV3.Server/DTOs/Auth/RefreshTokenDto.cs index 91c25e7..ee4c915 100644 --- a/SharpbinV3.Server/DTOs/Auth/RefreshTokenDto.cs +++ b/SharpbinV3.Server/DTOs/Auth/RefreshTokenDto.cs @@ -6,7 +6,6 @@ namespace SharpbinV3.Server.DTOs.Auth { [Required] public required string Token { get; set; } - [Required] public required string RefreshToken { get; set; } } diff --git a/SharpbinV3.Server/DTOs/Auth/TurnstileResponseDto.cs b/SharpbinV3.Server/DTOs/Auth/TurnstileResponseDto.cs index 5c2629d..22ab315 100644 --- a/SharpbinV3.Server/DTOs/Auth/TurnstileResponseDto.cs +++ b/SharpbinV3.Server/DTOs/Auth/TurnstileResponseDto.cs @@ -6,7 +6,6 @@ namespace SharpbinV3.Server.DTOs.Auth { [JsonPropertyName("success")] public bool Success { get; set; } - [JsonPropertyName("error-codes")] public string[]? ErrorCodes { get; set; } } diff --git a/SharpbinV3.Server/DTOs/User/LoginUserDto.cs b/SharpbinV3.Server/DTOs/User/LoginUserDto.cs index 185d121..c10f5be 100644 --- a/SharpbinV3.Server/DTOs/User/LoginUserDto.cs +++ b/SharpbinV3.Server/DTOs/User/LoginUserDto.cs @@ -7,7 +7,6 @@ namespace SharpbinV3.Server.DTOs.User [StringLength(50, MinimumLength = 3)] public string? Username { get; set; } public string? Email { get; set; } - [StringLength(128, MinimumLength = 6)] public string? Password { get; set; } public string? Token { get; set; } diff --git a/SharpbinV3.Server/DTOs/User/RegisterUserDto.cs b/SharpbinV3.Server/DTOs/User/RegisterUserDto.cs index d3b49df..c59d9a6 100644 --- a/SharpbinV3.Server/DTOs/User/RegisterUserDto.cs +++ b/SharpbinV3.Server/DTOs/User/RegisterUserDto.cs @@ -22,36 +22,16 @@ namespace SharpbinV3.Server.DTOs { var results = new List(); if (!ValidateUsername().IsMatch(Username)) - results.Add( - new ValidationResult( - "Username can only contain letters, numbers, underscores, and dots.", - [nameof(Username)] - ) - ); + results.Add(new ValidationResult("Username can only contain letters, numbers, underscores, and dots.", [nameof(Username)])); if (!ValidatePassword().IsMatch(Password)) - results.Add( - new ValidationResult( - "Password should have at least 8 characters, including uppercase, lowercase, and digits.", - [nameof(Password)] - ) - ); + results.Add(new ValidationResult("Password should have at least 8 characters, including uppercase, lowercase, and digits.", [nameof(Password)])); if (DisplayName != null) { if (DisplayName.Length < 3 || DisplayName.Length > 26) - results.Add( - new ValidationResult( - "DisplayName must be between 3 and 26 characters.", - [nameof(DisplayName)] - ) - ); + results.Add(new ValidationResult("DisplayName must be between 3 and 26 characters.", [nameof(DisplayName)])); if (!ValidateUsername().IsMatch(DisplayName)) - results.Add( - new ValidationResult( - "DisplayName can only contain letters, numbers, underscores, and dots.", - [nameof(DisplayName)] - ) - ); + results.Add(new ValidationResult("DisplayName can only contain letters, numbers, underscores, and dots.", [nameof(DisplayName)])); } if (Email != null) { @@ -64,7 +44,6 @@ namespace SharpbinV3.Server.DTOs [GeneratedRegex("^[A-Za-z0-9_.]+$")] private static partial Regex ValidateUsername(); - [GeneratedRegex("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).{8,}$")] public static partial Regex ValidatePassword(); } diff --git a/SharpbinV3.Server/DTOs/User/UpdateUserDto.cs b/SharpbinV3.Server/DTOs/User/UpdateUserDto.cs index 1b5c8fd..ff24814 100644 --- a/SharpbinV3.Server/DTOs/User/UpdateUserDto.cs +++ b/SharpbinV3.Server/DTOs/User/UpdateUserDto.cs @@ -17,19 +17,9 @@ namespace SharpbinV3.Server.DTOs if (DisplayName != null) { if (DisplayName.Length < 3 || DisplayName.Length > 26) - results.Add( - new ValidationResult( - "DisplayName must be between 3 and 26 characters.", - [nameof(DisplayName)] - ) - ); + results.Add(new ValidationResult("DisplayName must be between 3 and 26 characters.", [nameof(DisplayName)])); if (!ValidateDisplayname().IsMatch(DisplayName)) - results.Add( - new ValidationResult( - "DisplayName can only contain letters, numbers, underscores, and dots.", - [nameof(DisplayName)] - ) - ); + results.Add(new ValidationResult("DisplayName can only contain letters, numbers, underscores, and dots.", [nameof(DisplayName)])); } if (Email != null) { @@ -40,27 +30,19 @@ namespace SharpbinV3.Server.DTOs if (Visibility != null) { if (Visibility < 0 || Visibility > 2) - results.Add( - new ValidationResult( - "Visibility must be between 0 and 2.", - [nameof(Visibility)] - ) - ); + results.Add(new ValidationResult("Visibility must be between 0 and 2.", [nameof(Visibility)])); } if (Roles != null) { if (Roles.Length == 0) - results.Add( - new ValidationResult("Roles cannot be an empty array.", [nameof(Roles)]) - ); + results.Add(new ValidationResult("Roles cannot be an empty array.", [nameof(Roles)])); int[] validRoles = [0, 1, 255, 403]; foreach (var role in Roles) { if (!validRoles.Contains(role)) - results.Add( - new ValidationResult($"Invalid role: {role}.", [nameof(Roles)]) - ); + results.Add(new ValidationResult($"Invalid role: {role}.", [nameof(Roles)])); } + } return results; } diff --git a/SharpbinV3.Server/Extensions/HttpContextExtensions.cs b/SharpbinV3.Server/Extensions/HttpContextExtensions.cs index b8b9f36..330b8bb 100644 --- a/SharpbinV3.Server/Extensions/HttpContextExtensions.cs +++ b/SharpbinV3.Server/Extensions/HttpContextExtensions.cs @@ -1,21 +1,20 @@ -using System.IdentityModel.Tokens.Jwt; +using SharpbinV3.Server.Services; +using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; -using SharpbinV3.Server.Services; namespace SharpbinV3.Server.Extensions { public static class HttpContextExtensions { - public static readonly string[] ipHeaders = + public readonly static string[] ipHeaders = [ "X-Forwarded-For", "X-Real-IP", "CF-Connecting-IP", "True-Client-IP", "X-Cluster-Client-IP", - "X-ProxyUser-IP", + "X-ProxyUser-IP" ]; - public static JwtUser? GetJwtUser(this HttpContext context) { if (context.User == null || !context.User.Identity?.IsAuthenticated == true) @@ -37,10 +36,9 @@ namespace SharpbinV3.Server.Extensions .ToArray(); var expClaim = claims.FirstOrDefault(c => c.Type == JwtRegisteredClaimNames.Exp)?.Value; - var expires = - expClaim != null && long.TryParse(expClaim, out var expUnix) - ? DateTimeOffset.FromUnixTimeSeconds(expUnix).UtcDateTime - : DateTime.UtcNow.AddMinutes(15); + var expires = expClaim != null && long.TryParse(expClaim, out var expUnix) + ? DateTimeOffset.FromUnixTimeSeconds(expUnix).UtcDateTime + : DateTime.UtcNow.AddMinutes(15); return new JwtUser { @@ -49,7 +47,7 @@ namespace SharpbinV3.Server.Extensions DisplayName = displayName, TotpEnabled = totpEnabled, Roles = roles.Length > 0 ? roles : [0], - Expires = expires, + Expires = expires }; } @@ -57,12 +55,7 @@ namespace SharpbinV3.Server.Extensions { foreach (var header in ipHeaders) { - if ( - context.Request.Headers.TryGetValue( - header, - out Microsoft.Extensions.Primitives.StringValues value - ) - ) + if (context.Request.Headers.TryGetValue(header, out Microsoft.Extensions.Primitives.StringValues value)) { var ip = value.FirstOrDefault(); if (!string.IsNullOrEmpty(ip)) diff --git a/SharpbinV3.Server/Migrations/20251125015039_Init.cs b/SharpbinV3.Server/Migrations/20251125015039_Init.cs index 8dc8445..3fcd97f 100644 --- a/SharpbinV3.Server/Migrations/20251125015039_Init.cs +++ b/SharpbinV3.Server/Migrations/20251125015039_Init.cs @@ -14,8 +14,7 @@ namespace SharpbinV3.Server.Migrations name: "Users", columns: table => new { - UID = table - .Column(type: "INTEGER", nullable: false) + UID = table.Column(type: "INTEGER", nullable: false) .Annotation("Sqlite:Autoincrement", true), UUID = table.Column(type: "TEXT", nullable: false), Username = table.Column(type: "TEXT", nullable: false), @@ -24,20 +23,18 @@ namespace SharpbinV3.Server.Migrations DisplayName = table.Column(type: "TEXT", nullable: true), LastLogin = table.Column(type: "INTEGER", nullable: true), Roles = table.Column(type: "TEXT", nullable: false), - Visiblity = table.Column(type: "INTEGER", nullable: false), + Visiblity = table.Column(type: "INTEGER", nullable: false) }, constraints: table => { table.PrimaryKey("PK_Users", x => x.UID); - } - ); + }); migrationBuilder.CreateTable( name: "Pastes", columns: table => new { - PID = table - .Column(type: "INTEGER", nullable: false) + PID = table.Column(type: "INTEGER", nullable: false) .Annotation("Sqlite:Autoincrement", true), UUID = table.Column(type: "TEXT", nullable: false), ID = table.Column(type: "TEXT", nullable: true), @@ -51,7 +48,7 @@ namespace SharpbinV3.Server.Migrations Views = table.Column(type: "INTEGER", nullable: false), Syntax = table.Column(type: "TEXT", nullable: true), Visiblity = table.Column(type: "INTEGER", nullable: false), - ExpiresAt = table.Column(type: "INTEGER", nullable: false), + ExpiresAt = table.Column(type: "INTEGER", nullable: false) }, constraints: table => { @@ -60,10 +57,8 @@ namespace SharpbinV3.Server.Migrations name: "FK_Pastes_Users_UserUID", column: x => x.UserUID, principalTable: "Users", - principalColumn: "UID" - ); - } - ); + principalColumn: "UID"); + }); migrationBuilder.CreateTable( name: "RefreshTokens", @@ -75,7 +70,7 @@ namespace SharpbinV3.Server.Migrations CreatedAt = table.Column(type: "INTEGER", nullable: false), ExpiresAt = table.Column(type: "INTEGER", nullable: false), Used = table.Column(type: "INTEGER", nullable: false), - UserUID = table.Column(type: "INTEGER", nullable: true), + UserUID = table.Column(type: "INTEGER", nullable: true) }, constraints: table => { @@ -84,87 +79,81 @@ namespace SharpbinV3.Server.Migrations name: "FK_RefreshTokens_Users_UserUID", column: x => x.UserUID, principalTable: "Users", - principalColumn: "UID" - ); - } - ); + principalColumn: "UID"); + }); migrationBuilder.CreateIndex( name: "IX_Pastes_AuthorUUID", table: "Pastes", - column: "AuthorUUID" - ); + column: "AuthorUUID"); migrationBuilder.CreateIndex( name: "IX_Pastes_ExpiresAt", table: "Pastes", - column: "ExpiresAt" - ); + column: "ExpiresAt"); migrationBuilder.CreateIndex( name: "IX_Pastes_ID", table: "Pastes", column: "ID", - unique: true - ); + unique: true); migrationBuilder.CreateIndex( name: "IX_Pastes_PID", table: "Pastes", column: "PID", - unique: true - ); + unique: true); migrationBuilder.CreateIndex( name: "IX_Pastes_UserUID", table: "Pastes", - column: "UserUID" - ); + column: "UserUID"); migrationBuilder.CreateIndex( name: "IX_Pastes_UUID", table: "Pastes", column: "UUID", - unique: true - ); + unique: true); - migrationBuilder.CreateIndex(name: "IX_Pastes_Views", table: "Pastes", column: "Views"); + migrationBuilder.CreateIndex( + name: "IX_Pastes_Views", + table: "Pastes", + column: "Views"); migrationBuilder.CreateIndex( name: "IX_Pastes_Visiblity", table: "Pastes", - column: "Visiblity" - ); + column: "Visiblity"); migrationBuilder.CreateIndex( name: "IX_RefreshTokens_UserUID", table: "RefreshTokens", - column: "UserUID" - ); + column: "UserUID"); migrationBuilder.CreateIndex( name: "IX_Users_UID", table: "Users", column: "UID", - unique: true - ); + unique: true); migrationBuilder.CreateIndex( name: "IX_Users_UUID", table: "Users", column: "UUID", - unique: true - ); + unique: true); } /// protected override void Down(MigrationBuilder migrationBuilder) { - migrationBuilder.DropTable(name: "Pastes"); + migrationBuilder.DropTable( + name: "Pastes"); - migrationBuilder.DropTable(name: "RefreshTokens"); + migrationBuilder.DropTable( + name: "RefreshTokens"); - migrationBuilder.DropTable(name: "Users"); + migrationBuilder.DropTable( + name: "Users"); } } } diff --git a/SharpbinV3.Server/Migrations/20251125053617_ImprovePastes.cs b/SharpbinV3.Server/Migrations/20251125053617_ImprovePastes.cs index 8697ace..c0e0a08 100644 --- a/SharpbinV3.Server/Migrations/20251125053617_ImprovePastes.cs +++ b/SharpbinV3.Server/Migrations/20251125053617_ImprovePastes.cs @@ -10,39 +10,42 @@ namespace SharpbinV3.Server.Migrations /// protected override void Up(MigrationBuilder migrationBuilder) { - migrationBuilder.DropColumn(name: "FilePath", table: "Pastes"); + migrationBuilder.DropColumn( + name: "FilePath", + table: "Pastes"); migrationBuilder.AddColumn( name: "Data", table: "Pastes", type: "BLOB", nullable: false, - defaultValue: new byte[0] - ); + defaultValue: new byte[0]); migrationBuilder.AddColumn( name: "IsCompressed", table: "Pastes", type: "INTEGER", nullable: false, - defaultValue: false - ); + defaultValue: false); } /// protected override void Down(MigrationBuilder migrationBuilder) { - migrationBuilder.DropColumn(name: "Data", table: "Pastes"); + migrationBuilder.DropColumn( + name: "Data", + table: "Pastes"); - migrationBuilder.DropColumn(name: "IsCompressed", table: "Pastes"); + migrationBuilder.DropColumn( + name: "IsCompressed", + table: "Pastes"); migrationBuilder.AddColumn( name: "FilePath", table: "Pastes", type: "TEXT", nullable: false, - defaultValue: "" - ); + defaultValue: ""); } } } diff --git a/SharpbinV3.Server/Migrations/20251125055340_PasteContent.cs b/SharpbinV3.Server/Migrations/20251125055340_PasteContent.cs index 759e8bc..6d7fd57 100644 --- a/SharpbinV3.Server/Migrations/20251125055340_PasteContent.cs +++ b/SharpbinV3.Server/Migrations/20251125055340_PasteContent.cs @@ -10,13 +10,19 @@ namespace SharpbinV3.Server.Migrations /// protected override void Up(MigrationBuilder migrationBuilder) { - migrationBuilder.RenameColumn(name: "Data", table: "Pastes", newName: "Content"); + migrationBuilder.RenameColumn( + name: "Data", + table: "Pastes", + newName: "Content"); } /// protected override void Down(MigrationBuilder migrationBuilder) { - migrationBuilder.RenameColumn(name: "Content", table: "Pastes", newName: "Data"); + migrationBuilder.RenameColumn( + name: "Content", + table: "Pastes", + newName: "Data"); } } } diff --git a/SharpbinV3.Server/Migrations/20251125061310_GrammarFix.cs b/SharpbinV3.Server/Migrations/20251125061310_GrammarFix.cs index c58ef49..1ddcf70 100644 --- a/SharpbinV3.Server/Migrations/20251125061310_GrammarFix.cs +++ b/SharpbinV3.Server/Migrations/20251125061310_GrammarFix.cs @@ -13,14 +13,12 @@ namespace SharpbinV3.Server.Migrations migrationBuilder.RenameColumn( name: "Visiblity", table: "Pastes", - newName: "Visibility" - ); + newName: "Visibility"); migrationBuilder.RenameIndex( name: "IX_Pastes_Visiblity", table: "Pastes", - newName: "IX_Pastes_Visibility" - ); + newName: "IX_Pastes_Visibility"); } /// @@ -29,14 +27,12 @@ namespace SharpbinV3.Server.Migrations migrationBuilder.RenameColumn( name: "Visibility", table: "Pastes", - newName: "Visiblity" - ); + newName: "Visiblity"); migrationBuilder.RenameIndex( name: "IX_Pastes_Visibility", table: "Pastes", - newName: "IX_Pastes_Visiblity" - ); + newName: "IX_Pastes_Visiblity"); } } } diff --git a/SharpbinV3.Server/Migrations/20251228173503_UserGrammarFix.cs b/SharpbinV3.Server/Migrations/20251228173503_UserGrammarFix.cs index d1096c1..c460750 100644 --- a/SharpbinV3.Server/Migrations/20251228173503_UserGrammarFix.cs +++ b/SharpbinV3.Server/Migrations/20251228173503_UserGrammarFix.cs @@ -10,22 +10,29 @@ namespace SharpbinV3.Server.Migrations /// protected override void Up(MigrationBuilder migrationBuilder) { - migrationBuilder.DropIndex(name: "IX_Users_UID", table: "Users"); + migrationBuilder.DropIndex( + name: "IX_Users_UID", + table: "Users"); - migrationBuilder.RenameColumn(name: "Visiblity", table: "Users", newName: "Visibility"); + migrationBuilder.RenameColumn( + name: "Visiblity", + table: "Users", + newName: "Visibility"); } /// protected override void Down(MigrationBuilder migrationBuilder) { - migrationBuilder.RenameColumn(name: "Visibility", table: "Users", newName: "Visiblity"); + migrationBuilder.RenameColumn( + name: "Visibility", + table: "Users", + newName: "Visiblity"); migrationBuilder.CreateIndex( name: "IX_Users_UID", table: "Users", column: "UID", - unique: true - ); + unique: true); } } } diff --git a/SharpbinV3.Server/Migrations/20251228175338_LongFileSizes.cs b/SharpbinV3.Server/Migrations/20251228175338_LongFileSizes.cs index 863dee9..7e66958 100644 --- a/SharpbinV3.Server/Migrations/20251228175338_LongFileSizes.cs +++ b/SharpbinV3.Server/Migrations/20251228175338_LongFileSizes.cs @@ -8,9 +8,15 @@ namespace SharpbinV3.Server.Migrations public partial class LongFileSizes : Migration { /// - protected override void Up(MigrationBuilder migrationBuilder) { } + protected override void Up(MigrationBuilder migrationBuilder) + { + + } /// - protected override void Down(MigrationBuilder migrationBuilder) { } + protected override void Down(MigrationBuilder migrationBuilder) + { + + } } } diff --git a/SharpbinV3.Server/Migrations/20251231161600_UserUUIDKey.cs b/SharpbinV3.Server/Migrations/20251231161600_UserUUIDKey.cs index f2f8cfe..8638de1 100644 --- a/SharpbinV3.Server/Migrations/20251231161600_UserUUIDKey.cs +++ b/SharpbinV3.Server/Migrations/20251231161600_UserUUIDKey.cs @@ -10,35 +10,47 @@ namespace SharpbinV3.Server.Migrations /// protected override void Up(MigrationBuilder migrationBuilder) { - migrationBuilder.DropForeignKey(name: "FK_Pastes_Users_UserUID", table: "Pastes"); + migrationBuilder.DropForeignKey( + name: "FK_Pastes_Users_UserUID", + table: "Pastes"); migrationBuilder.DropForeignKey( name: "FK_RefreshTokens_Users_UserUID", - table: "RefreshTokens" - ); + table: "RefreshTokens"); - migrationBuilder.DropPrimaryKey(name: "PK_Users", table: "Users"); + migrationBuilder.DropPrimaryKey( + name: "PK_Users", + table: "Users"); - migrationBuilder.DropIndex(name: "IX_RefreshTokens_UserUID", table: "RefreshTokens"); + migrationBuilder.DropIndex( + name: "IX_RefreshTokens_UserUID", + table: "RefreshTokens"); - migrationBuilder.DropIndex(name: "IX_Pastes_UserUID", table: "Pastes"); + migrationBuilder.DropIndex( + name: "IX_Pastes_UserUID", + table: "Pastes"); - migrationBuilder.DropColumn(name: "UserUID", table: "RefreshTokens"); + migrationBuilder.DropColumn( + name: "UserUID", + table: "RefreshTokens"); - migrationBuilder.DropColumn(name: "UserUID", table: "Pastes"); + migrationBuilder.DropColumn( + name: "UserUID", + table: "Pastes"); - migrationBuilder - .AlterColumn( - name: "UID", - table: "Users", - type: "INTEGER", - nullable: false, - oldClrType: typeof(int), - oldType: "INTEGER" - ) + migrationBuilder.AlterColumn( + name: "UID", + table: "Users", + type: "INTEGER", + nullable: false, + oldClrType: typeof(int), + oldType: "INTEGER") .OldAnnotation("Sqlite:Autoincrement", true); - migrationBuilder.AddPrimaryKey(name: "PK_Users", table: "Users", column: "UUID"); + migrationBuilder.AddPrimaryKey( + name: "PK_Users", + table: "Users", + column: "UUID"); migrationBuilder.AddForeignKey( name: "FK_Pastes_Users_AuthorUUID", @@ -46,8 +58,7 @@ namespace SharpbinV3.Server.Migrations column: "AuthorUUID", principalTable: "Users", principalColumn: "UUID", - onDelete: ReferentialAction.Cascade - ); + onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_RefreshTokens_Users_UserUUID", @@ -55,76 +66,73 @@ namespace SharpbinV3.Server.Migrations column: "UserUUID", principalTable: "Users", principalColumn: "UUID", - onDelete: ReferentialAction.Cascade - ); + onDelete: ReferentialAction.Cascade); } /// protected override void Down(MigrationBuilder migrationBuilder) { - migrationBuilder.DropForeignKey(name: "FK_Pastes_Users_AuthorUUID", table: "Pastes"); + migrationBuilder.DropForeignKey( + name: "FK_Pastes_Users_AuthorUUID", + table: "Pastes"); migrationBuilder.DropForeignKey( name: "FK_RefreshTokens_Users_UserUUID", - table: "RefreshTokens" - ); + table: "RefreshTokens"); - migrationBuilder.DropPrimaryKey(name: "PK_Users", table: "Users"); + migrationBuilder.DropPrimaryKey( + name: "PK_Users", + table: "Users"); - migrationBuilder - .AlterColumn( - name: "UID", - table: "Users", - type: "INTEGER", - nullable: false, - oldClrType: typeof(int), - oldType: "INTEGER" - ) + migrationBuilder.AlterColumn( + name: "UID", + table: "Users", + type: "INTEGER", + nullable: false, + oldClrType: typeof(int), + oldType: "INTEGER") .Annotation("Sqlite:Autoincrement", true); migrationBuilder.AddColumn( name: "UserUID", table: "RefreshTokens", type: "INTEGER", - nullable: true - ); + nullable: true); migrationBuilder.AddColumn( name: "UserUID", table: "Pastes", type: "INTEGER", - nullable: true - ); + nullable: true); - migrationBuilder.AddPrimaryKey(name: "PK_Users", table: "Users", column: "UID"); + migrationBuilder.AddPrimaryKey( + name: "PK_Users", + table: "Users", + column: "UID"); migrationBuilder.CreateIndex( name: "IX_RefreshTokens_UserUID", table: "RefreshTokens", - column: "UserUID" - ); + column: "UserUID"); migrationBuilder.CreateIndex( name: "IX_Pastes_UserUID", table: "Pastes", - column: "UserUID" - ); + column: "UserUID"); migrationBuilder.AddForeignKey( name: "FK_Pastes_Users_UserUID", table: "Pastes", column: "UserUID", principalTable: "Users", - principalColumn: "UID" - ); + principalColumn: "UID"); migrationBuilder.AddForeignKey( name: "FK_RefreshTokens_Users_UserUID", table: "RefreshTokens", column: "UserUID", principalTable: "Users", - principalColumn: "UID" - ); + principalColumn: "UID"); } } } diff --git a/SharpbinV3.Server/Migrations/20260104211956_UserUIDAutoIncrement.cs b/SharpbinV3.Server/Migrations/20260104211956_UserUIDAutoIncrement.cs index e859461..87c5612 100644 --- a/SharpbinV3.Server/Migrations/20260104211956_UserUIDAutoIncrement.cs +++ b/SharpbinV3.Server/Migrations/20260104211956_UserUIDAutoIncrement.cs @@ -10,30 +10,25 @@ namespace SharpbinV3.Server.Migrations /// protected override void Up(MigrationBuilder migrationBuilder) { - migrationBuilder.Sql( - """ - CREATE TRIGGER Users_UID_AutoIncrement - AFTER INSERT ON Users - BEGIN - UPDATE Users - SET UID = ( - SELECT IFNULL(MAX(UID), 0) + 1 FROM Users - ) - WHERE rowid = NEW.rowid AND NEW.UID IS NULL; - END; - """, - suppressTransaction: true - ); - } + migrationBuilder.Sql(""" + CREATE TRIGGER Users_UID_AutoIncrement + AFTER INSERT ON Users + BEGIN + UPDATE Users + SET UID = ( + SELECT IFNULL(MAX(UID), 0) + 1 FROM Users + ) + WHERE rowid = NEW.rowid AND NEW.UID IS NULL; + END; + """, suppressTransaction: true); + } /// protected override void Down(MigrationBuilder migrationBuilder) { - migrationBuilder.Sql( - """ - DROP TRIGGER IF EXISTS Users_UID_AutoIncrement; - """ - ); + migrationBuilder.Sql(""" + DROP TRIGGER IF EXISTS Users_UID_AutoIncrement; + """); } } } diff --git a/SharpbinV3.Server/Migrations/20260104212417_UserUIDIndex.cs b/SharpbinV3.Server/Migrations/20260104212417_UserUIDIndex.cs index 247b3c0..84a03ba 100644 --- a/SharpbinV3.Server/Migrations/20260104212417_UserUIDIndex.cs +++ b/SharpbinV3.Server/Migrations/20260104212417_UserUIDIndex.cs @@ -14,14 +14,15 @@ namespace SharpbinV3.Server.Migrations name: "IX_Users_UID", table: "Users", column: "UID", - unique: true - ); + unique: true); } /// protected override void Down(MigrationBuilder migrationBuilder) { - migrationBuilder.DropIndex(name: "IX_Users_UID", table: "Users"); + migrationBuilder.DropIndex( + name: "IX_Users_UID", + table: "Users"); } } } diff --git a/SharpbinV3.Server/Migrations/20260104212733_UserUIDNonUnique.cs b/SharpbinV3.Server/Migrations/20260104212733_UserUIDNonUnique.cs index 1dd45f5..21b1635 100644 --- a/SharpbinV3.Server/Migrations/20260104212733_UserUIDNonUnique.cs +++ b/SharpbinV3.Server/Migrations/20260104212733_UserUIDNonUnique.cs @@ -10,7 +10,9 @@ namespace SharpbinV3.Server.Migrations /// protected override void Up(MigrationBuilder migrationBuilder) { - migrationBuilder.DropIndex(name: "IX_Users_UID", table: "Users"); + migrationBuilder.DropIndex( + name: "IX_Users_UID", + table: "Users"); migrationBuilder.AlterColumn( name: "UID", @@ -18,16 +20,20 @@ namespace SharpbinV3.Server.Migrations type: "INTEGER", nullable: true, oldClrType: typeof(int), - oldType: "INTEGER" - ); + oldType: "INTEGER"); - migrationBuilder.CreateIndex(name: "IX_Users_UID", table: "Users", column: "UID"); + migrationBuilder.CreateIndex( + name: "IX_Users_UID", + table: "Users", + column: "UID"); } /// protected override void Down(MigrationBuilder migrationBuilder) { - migrationBuilder.DropIndex(name: "IX_Users_UID", table: "Users"); + migrationBuilder.DropIndex( + name: "IX_Users_UID", + table: "Users"); migrationBuilder.AlterColumn( name: "UID", @@ -37,15 +43,13 @@ namespace SharpbinV3.Server.Migrations defaultValue: 0, oldClrType: typeof(int), oldType: "INTEGER", - oldNullable: true - ); + oldNullable: true); migrationBuilder.CreateIndex( name: "IX_Users_UID", table: "Users", column: "UID", - unique: true - ); + unique: true); } } } diff --git a/SharpbinV3.Server/Migrations/20260106211303_NullableAuthorUUID.cs b/SharpbinV3.Server/Migrations/20260106211303_NullableAuthorUUID.cs index 33a3347..06191b8 100644 --- a/SharpbinV3.Server/Migrations/20260106211303_NullableAuthorUUID.cs +++ b/SharpbinV3.Server/Migrations/20260106211303_NullableAuthorUUID.cs @@ -16,8 +16,7 @@ namespace SharpbinV3.Server.Migrations type: "TEXT", nullable: true, oldClrType: typeof(Guid), - oldType: "TEXT" - ); + oldType: "TEXT"); } /// @@ -31,8 +30,7 @@ namespace SharpbinV3.Server.Migrations defaultValue: new Guid("00000000-0000-0000-0000-000000000000"), oldClrType: typeof(Guid), oldType: "TEXT", - oldNullable: true - ); + oldNullable: true); } } } diff --git a/SharpbinV3.Server/Migrations/20260107181640_UserTotps.cs b/SharpbinV3.Server/Migrations/20260107181640_UserTotps.cs index 21b0b8c..6de9e6d 100644 --- a/SharpbinV3.Server/Migrations/20260107181640_UserTotps.cs +++ b/SharpbinV3.Server/Migrations/20260107181640_UserTotps.cs @@ -16,7 +16,7 @@ namespace SharpbinV3.Server.Migrations { UserUUID = table.Column(type: "TEXT", nullable: false), EncryptedSecret = table.Column(type: "BLOB", nullable: false), - CreatedAt = table.Column(type: "INTEGER", nullable: false), + CreatedAt = table.Column(type: "INTEGER", nullable: false) }, constraints: table => { @@ -26,16 +26,15 @@ namespace SharpbinV3.Server.Migrations column: x => x.UserUUID, principalTable: "Users", principalColumn: "UUID", - onDelete: ReferentialAction.Cascade - ); - } - ); + onDelete: ReferentialAction.Cascade); + }); } /// protected override void Down(MigrationBuilder migrationBuilder) { - migrationBuilder.DropTable(name: "UserTotps"); + migrationBuilder.DropTable( + name: "UserTotps"); } } } diff --git a/SharpbinV3.Server/Program.cs b/SharpbinV3.Server/Program.cs index 8ed15a5..a754d9d 100644 --- a/SharpbinV3.Server/Program.cs +++ b/SharpbinV3.Server/Program.cs @@ -1,5 +1,3 @@ -using System.Text; -using System.Threading.RateLimiting; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.DataProtection; @@ -12,6 +10,8 @@ using SharpbinV3.Server.Services; using SharpbinV3.Server.Services.Verification; using SharpbinV3.Server.Services.Verification.Providers; using SharpbinV3.Server.Settings; +using System.Text; +using System.Threading.RateLimiting; namespace SharpbinV3.Server { @@ -40,10 +40,11 @@ namespace SharpbinV3.Server builder.Services.AddHttpClient(); builder.Services.AddMemoryCache(); - builder.Services.AddHealthChecks().AddDbContextCheck("Database"); + builder.Services.AddHealthChecks() + .AddDbContextCheck("Database"); - builder - .Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) + builder.Services + .AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(jwt => { var jwtSettings = builder.Configuration.GetSection("JwtSettings"); @@ -66,58 +67,44 @@ namespace SharpbinV3.Server ClockSkew = TimeSpan.Zero, RequireSignedTokens = true, - ValidAlgorithms = [SecurityAlgorithms.HmacSha256], + ValidAlgorithms = [SecurityAlgorithms.HmacSha256] }; }); - builder - .Services.AddAuthorizationBuilder() - .AddPolicy( - "NotBanned", - policy => policy.Requirements.Add(new NotBannedRequirement()) - ); - builder - .Services.AddAuthorizationBuilder() - .AddPolicy( - "AuthAndNotBanned", - policy => policy.Requirements.Add(new NotBannedRequirement()) - ); + builder.Services.AddAuthorizationBuilder() + .AddPolicy("NotBanned", policy => + policy.Requirements.Add(new NotBannedRequirement())); + builder.Services.AddAuthorizationBuilder() + .AddPolicy("AuthAndNotBanned", policy => + policy.Requirements.Add(new NotBannedRequirement())); builder.Services.AddSingleton(new NotBannedHandler(false)); builder.Services.AddSingleton(new NotBannedHandler(true)); + builder.Services.AddRateLimiter(options => { - options.AddSlidingWindowLimiter( - "Sliding", - opt => - { - opt.Window = TimeSpan.FromSeconds(10); - opt.PermitLimit = 10; - opt.QueueLimit = 2; - opt.SegmentsPerWindow = 5; - opt.QueueProcessingOrder = QueueProcessingOrder.OldestFirst; - } - ); + options.AddSlidingWindowLimiter("Sliding", opt => + { + opt.Window = TimeSpan.FromSeconds(10); + opt.PermitLimit = 10; + opt.QueueLimit = 2; + opt.SegmentsPerWindow = 5; + opt.QueueProcessingOrder = QueueProcessingOrder.OldestFirst; + }); options.RejectionStatusCode = StatusCodes.Status429TooManyRequests; }); builder.Services.AddCors(o => { o.AddDefaultPolicy(p => - p.WithOrigins("http://localhost:5173").AllowAnyHeader().AllowAnyMethod() - ); + p.WithOrigins("http://localhost:5173") + .AllowAnyHeader() + .AllowAnyMethod()); }); - builder.Services.Configure( - builder.Configuration.GetSection("PasteSettings") - ); - builder.Services.Configure( - builder.Configuration.GetSection("JWTSettings") - ); - builder.Services.Configure( - builder.Configuration.GetSection("AuthSettings") - ); + builder.Services.Configure(builder.Configuration.GetSection("PasteSettings")); + builder.Services.Configure(builder.Configuration.GetSection("JWTSettings")); + builder.Services.Configure(builder.Configuration.GetSection("AuthSettings")); - builder - .Services.AddDataProtection() + builder.Services.AddDataProtection() .PersistKeysToFileSystem(GetDataProtectionKeyDirectory(builder.Environment)) .SetApplicationName("SharpbinV3"); @@ -143,8 +130,7 @@ namespace SharpbinV3.Server db.Database.Migrate(); // this is temporary since the migration doesnt seem to work properly - db.Database.ExecuteSql( - $""" + db.Database.ExecuteSql($""" CREATE TRIGGER IF NOT EXISTS Users_UID_AutoIncrement AFTER INSERT ON Users BEGIN @@ -154,15 +140,13 @@ namespace SharpbinV3.Server ) WHERE rowid = NEW.rowid AND NEW.UID IS NULL; END; - """ - ); + """); } app.MapHealthChecks("/health"); app.Run(); } - static DirectoryInfo GetDataProtectionKeyDirectory(IHostEnvironment env) { var overridepath = Environment.GetEnvironmentVariable("DATA_PROTECTION_KEY_PATH"); diff --git a/SharpbinV3.Server/Services/AuthService.cs b/SharpbinV3.Server/Services/AuthService.cs index 02174a6..0f567c0 100644 --- a/SharpbinV3.Server/Services/AuthService.cs +++ b/SharpbinV3.Server/Services/AuthService.cs @@ -1,13 +1,13 @@ -using System.IdentityModel.Tokens.Jwt; -using System.Security.Claims; -using System.Text; -using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using SharpbinV3.Server.Data; using SharpbinV3.Server.Data.Entities; using SharpbinV3.Server.DTOs.Auth; using SharpbinV3.Server.Settings; +using System.IdentityModel.Tokens.Jwt; +using System.Security.Claims; +using System.Text; using Bcrypt = BCrypt.Net.BCrypt; namespace SharpbinV3.Server.Services @@ -21,23 +21,13 @@ namespace SharpbinV3.Server.Services public int[] Roles { get; set; } = []; public DateTime Expires { get; set; } } - - public sealed class AuthService( - AppDbContext db, - IOptions jwtOptions, - IOptions authOptions - ) + public sealed class AuthService(AppDbContext db, IOptions jwtOptions, IOptions authOptions) { private readonly AppDbContext _db = db; private readonly JWTSettings _jwtSettings = jwtOptions.Value; private readonly AuthSettings _authSettings = authOptions.Value; - public async Task CreateUser( - string username, - string password, - string? email, - string? displayName - ) + public async Task CreateUser(string username, string password, string? email, string? displayName) { var user = new User { @@ -45,7 +35,7 @@ namespace SharpbinV3.Server.Services PasswordHash = Bcrypt.HashPassword(password), Email = email, DisplayName = displayName, - UUID = Guid.CreateVersion7(), + UUID = Guid.CreateVersion7() }; if (_authSettings.First_User_Admin && !await _db.Users.AnyAsync()) @@ -55,7 +45,6 @@ namespace SharpbinV3.Server.Services await _db.SaveChangesAsync(); return user; } - public async Task GenerateJWTToken(User user) { var jwtHandler = new JwtSecurityTokenHandler(); @@ -68,7 +57,7 @@ namespace SharpbinV3.Server.Services new("Username", user.Username), new("DisplayName", user.DisplayName ?? ""), new("TOTP_Enabled", totpEnabled.ToString()), - new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), + new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) }; if (user.Roles != null) @@ -90,24 +79,20 @@ namespace SharpbinV3.Server.Services SigningCredentials = new SigningCredentials( new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature - ), + ) }; var token = jwtHandler.CreateToken(descriptor); var jwtToken = jwtHandler.WriteToken(token); - var existingToken = await _db.RefreshTokens.FirstOrDefaultAsync(rt => - rt.UserUUID == user.UUID - ); + var existingToken = await _db.RefreshTokens.FirstOrDefaultAsync(rt => rt.UserUUID == user.UUID); if (existingToken != null) { existingToken.JwtId = token.Id; existingToken.Used = false; existingToken.CreatedAt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); - existingToken.ExpiresAt = DateTimeOffset - .UtcNow.AddMonths(6) - .ToUnixTimeMilliseconds(); + existingToken.ExpiresAt = DateTimeOffset.UtcNow.AddMonths(6).ToUnixTimeMilliseconds(); existingToken.Token = Utilities.GenerateRandomString(36) + Guid.NewGuid(); _db.RefreshTokens.Update(existingToken); } @@ -121,7 +106,7 @@ namespace SharpbinV3.Server.Services UserUUID = user.UUID, CreatedAt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), ExpiresAt = DateTimeOffset.UtcNow.AddMonths(6).ToUnixTimeMilliseconds(), - Token = Utilities.GenerateRandomString(36) + Guid.NewGuid(), + Token = Utilities.GenerateRandomString(36) + Guid.NewGuid() }; await _db.RefreshTokens.AddAsync(refreshToken); } @@ -132,9 +117,7 @@ namespace SharpbinV3.Server.Services { Token = jwtToken, Success = true, - RefreshToken = - existingToken?.Token - ?? (await _db.RefreshTokens.FirstAsync(rt => rt.UserUUID == user.UUID)).Token, + RefreshToken = existingToken?.Token ?? (await _db.RefreshTokens.FirstAsync(rt => rt.UserUUID == user.UUID)).Token }; } @@ -144,39 +127,28 @@ namespace SharpbinV3.Server.Services var key = Encoding.UTF8.GetBytes(_jwtSettings.Secret); try { - var principal = jwtHandler.ValidateToken( - token, - new TokenValidationParameters - { - ValidateIssuerSigningKey = true, - IssuerSigningKey = new SymmetricSecurityKey(key), - ValidateIssuer = true, - ValidIssuer = _jwtSettings.Issuer, - ValidateAudience = true, - ValidAudience = _jwtSettings.Audience, - ClockSkew = TimeSpan.Zero, - ValidateLifetime = false, - RequireSignedTokens = true, - ValidAlgorithms = [SecurityAlgorithms.HmacSha256], - }, - out SecurityToken validatedToken - ); + var principal = jwtHandler.ValidateToken(token, new TokenValidationParameters + { + ValidateIssuerSigningKey = true, + IssuerSigningKey = new SymmetricSecurityKey(key), + ValidateIssuer = true, + ValidIssuer = _jwtSettings.Issuer, + ValidateAudience = true, + ValidAudience = _jwtSettings.Audience, + ClockSkew = TimeSpan.Zero, + ValidateLifetime = false, + RequireSignedTokens = true, + ValidAlgorithms = [SecurityAlgorithms.HmacSha256] + }, out SecurityToken validatedToken); var jwtId = validatedToken.Id; - var storedRefreshToken = await _db.RefreshTokens.FirstOrDefaultAsync(rt => - rt.Token == refreshToken - ); - if ( - storedRefreshToken == null + var storedRefreshToken = await _db.RefreshTokens + .FirstOrDefaultAsync(rt => rt.Token == refreshToken); + if (storedRefreshToken == null || storedRefreshToken.Used || storedRefreshToken.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - || storedRefreshToken.JwtId != jwtId - ) + || storedRefreshToken.JwtId != jwtId) { - return new CreateJWT() - { - Success = false, - Errors = ["Invalid refresh token, possibly already used or expired."], - }; + return new CreateJWT() { Success = false, Errors = ["Invalid refresh token, possibly already used or expired."] }; } storedRefreshToken.Used = true; await _db.SaveChangesAsync(); @@ -195,9 +167,7 @@ namespace SharpbinV3.Server.Services public async Task UpdateUser(User user) { - var existingUser = - await _db.Users.FirstOrDefaultAsync(u => u.UUID == user.UUID) - ?? throw new Exception("User not found"); + var existingUser = await _db.Users.FirstOrDefaultAsync(u => u.UUID == user.UUID) ?? throw new Exception("User not found"); existingUser.Username = user.Username; existingUser.Email = user.Email; existingUser.DisplayName = user.DisplayName; @@ -208,12 +178,9 @@ namespace SharpbinV3.Server.Services await _db.SaveChangesAsync(); return user; } - public async Task UpdateLoginTime(User user) { - var existingUser = - await _db.Users.FirstOrDefaultAsync(u => u.UUID == user.UUID) - ?? throw new Exception("User not found"); + var existingUser = await _db.Users.FirstOrDefaultAsync(u => u.UUID == user.UUID) ?? throw new Exception("User not found"); existingUser.LastLogin = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); _db.Users.Update(existingUser); await _db.SaveChangesAsync(); diff --git a/SharpbinV3.Server/Services/CompressionService.cs b/SharpbinV3.Server/Services/CompressionService.cs index 8ee5056..28796bb 100644 --- a/SharpbinV3.Server/Services/CompressionService.cs +++ b/SharpbinV3.Server/Services/CompressionService.cs @@ -1,5 +1,6 @@ using System.IO.Compression; + namespace SharpbinV3.Server.Services { public class CompressionService : ICompressionService @@ -20,21 +21,16 @@ namespace SharpbinV3.Server.Services return data; } - public byte[] Compress(string data) { ArgumentNullException.ThrowIfNull(data); return Compress(System.Text.Encoding.UTF8.GetBytes(data)); } - public byte[] Decompress(byte[] compressedData) { ArgumentNullException.ThrowIfNull(compressedData); if (!IsCompressed(compressedData)) - throw new ArgumentException( - "Data is not in a valid compressed format.", - nameof(compressedData) - ); + throw new ArgumentException("Data is not in a valid compressed format.", nameof(compressedData)); using (MemoryStream ms = new()) { diff --git a/SharpbinV3.Server/Services/PasteCleanUpService.cs b/SharpbinV3.Server/Services/PasteCleanUpService.cs index 899e7d2..6c5adc5 100644 --- a/SharpbinV3.Server/Services/PasteCleanUpService.cs +++ b/SharpbinV3.Server/Services/PasteCleanUpService.cs @@ -3,21 +3,14 @@ using SharpbinV3.Server.Data; namespace SharpbinV3.Server.Services { - public class PasteCleanUpService( - IServiceProvider serviceProvider, - ILogger logger - ) : BackgroundService + public class PasteCleanUpService(IServiceProvider serviceProvider, ILogger logger) : BackgroundService { private readonly TimeSpan _period = TimeSpan.FromMinutes(5); - protected override async Task ExecuteAsync(CancellationToken stoppingToken) { using var timer = new PeriodicTimer(_period); await Cleanup(stoppingToken); - while ( - !stoppingToken.IsCancellationRequested - && await timer.WaitForNextTickAsync(stoppingToken) - ) + while (!stoppingToken.IsCancellationRequested && await timer.WaitForNextTickAsync(stoppingToken)) { try { @@ -43,6 +36,7 @@ namespace SharpbinV3.Server.Services await db.SaveChangesAsync(stoppingToken); logger.LogInformation("Deleted {Count} expired pastes", deletedCount); } + } } } diff --git a/SharpbinV3.Server/Services/PasteService.cs b/SharpbinV3.Server/Services/PasteService.cs index d583b9b..c352b64 100644 --- a/SharpbinV3.Server/Services/PasteService.cs +++ b/SharpbinV3.Server/Services/PasteService.cs @@ -1,31 +1,19 @@ -using System.Text; -using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; using SharpbinV3.Server.Data; using SharpbinV3.Server.Data.Entities; using SharpbinV3.Server.Settings; +using System.Text; namespace SharpbinV3.Server.Services { - public sealed class PasteService( - AppDbContext db, - ICompressionService cs, - IOptions options - ) + public sealed class PasteService(AppDbContext db, ICompressionService cs, IOptions options) { private readonly AppDbContext _db = db; private readonly ICompressionService _cs = cs; private readonly PasteSettings _pasteSettings = options.Value; - public async Task Create( - User? author, - string content, - string title, - string syntax, - int visibility, - long expiresAt, - bool shouldCompress - ) + public async Task Create(User? author, string content, string title, string syntax, int visibility, long expiresAt, bool shouldCompress) { var data = Encoding.UTF8.GetBytes(content); if (shouldCompress) @@ -62,24 +50,20 @@ namespace SharpbinV3.Server.Services var result = await _db.SaveChangesAsync(); return result > 0; } - public async Task Edit(Paste paste) { _db.Pastes.Update(paste); await _db.SaveChangesAsync(); return paste; } - public async Task Exists(string id) { return await _db.Pastes.AnyAsync(p => p.ID == id); } - public async Task Exists(Guid uuid) { return await _db.Pastes.AnyAsync(p => p.UUID == uuid); } - public async Task EditText(Paste paste, string text) { var data = Encoding.UTF8.GetBytes(text); @@ -95,41 +79,39 @@ namespace SharpbinV3.Server.Services var result = await _db.SaveChangesAsync(); return result > 0; } - public async Task Get(string id) { var paste = await _db.Pastes.Include(p => p.User).FirstOrDefaultAsync(p => p.ID == id); return paste ?? null; } - public async Task> GetList(int offset, int count, bool publicOnly = false) { var query = _db.Pastes.AsQueryable(); if (publicOnly) query = query.Where(p => p.Visibility == 0); - return await query.OrderByDescending(p => p.PID).Skip(offset).Take(count).ToListAsync(); + return await query + .OrderByDescending(p => p.PID) + .Skip(offset) + .Take(count) + .ToListAsync(); } public async Task ValidateSyntax(string syntax) { return await Task.FromResult(_pasteSettings.ValidSyntaxLanguages.Contains(syntax)); } - public async Task ValidateTitle(string title) { return await Task.FromResult(title.Length <= _pasteSettings.MaxTitleLength); } - public async Task ValidateVisibility(int visibility) { return await Task.FromResult(visibility >= 0 && visibility <= 2); } - public async Task ValidateExpiresAt(long expiresAt) { - if (expiresAt == 0) - return true; + if (expiresAt == 0) return true; var currentTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); return await Task.FromResult(expiresAt > currentTime - 1000); } diff --git a/SharpbinV3.Server/Services/UserService.cs b/SharpbinV3.Server/Services/UserService.cs index 7f781c0..f61bd9a 100644 --- a/SharpbinV3.Server/Services/UserService.cs +++ b/SharpbinV3.Server/Services/UserService.cs @@ -2,12 +2,12 @@ using SharpbinV3.Server.Data; using SharpbinV3.Server.Data.Entities; + namespace SharpbinV3.Server.Services { public sealed class UserService(AppDbContext db) { private readonly AppDbContext _db = db; - public Task GetByUID(int uid, bool withPastes = false) { IQueryable query = _db.Users; diff --git a/SharpbinV3.Server/Services/Verification/Providers/TotpVerificationProvider.cs b/SharpbinV3.Server/Services/Verification/Providers/TotpVerificationProvider.cs index 60a1c0d..10622fe 100644 --- a/SharpbinV3.Server/Services/Verification/Providers/TotpVerificationProvider.cs +++ b/SharpbinV3.Server/Services/Verification/Providers/TotpVerificationProvider.cs @@ -12,11 +12,7 @@ namespace SharpbinV3.Server.Services.Verification.Providers private readonly IDataProtector _protector; private readonly IMemoryCache _cache; - public TotpVerificationProvider( - AppDbContext db, - IDataProtectionProvider dataProtectionProvider, - IMemoryCache cache - ) + public TotpVerificationProvider(AppDbContext db, IDataProtectionProvider dataProtectionProvider, IMemoryCache cache) { _db = db; _protector = dataProtectionProvider.CreateProtector("TotpSecret-v1"); @@ -28,16 +24,11 @@ namespace SharpbinV3.Server.Services.Verification.Providers public async Task VerifyAsync(VerificationContext ctx) { - if (ctx.UserUUID is null) - return false; - if (string.IsNullOrWhiteSpace(ctx.Code)) - return false; + if (ctx.UserUUID is null) return false; + if (string.IsNullOrWhiteSpace(ctx.Code)) return false; - var userTotp = await _db.UserTotps.FirstOrDefaultAsync(t => - t.UserUUID == ctx.UserUUID.Value - ); - if (userTotp is null) - return false; + var userTotp = await _db.UserTotps.FirstOrDefaultAsync(t => t.UserUUID == ctx.UserUUID.Value); + if (userTotp is null) return false; var secret = _protector.Unprotect(userTotp.EncryptedSecret); if (!VerifyCode(secret, ctx.Code, out var step)) @@ -53,58 +44,30 @@ namespace SharpbinV3.Server.Services.Verification.Providers public string ToBase32(byte[] data) => Base32Encoding.ToString(data); - public byte[] FromBase32(string base32) => - string.IsNullOrWhiteSpace(base32) ? [] : Base32Encoding.ToBytes(base32); + public byte[] FromBase32(string base32) => string.IsNullOrWhiteSpace(base32) ? [] : Base32Encoding.ToBytes(base32); - public string BuildOtpAuthUri( - string issuer, - string accountName, - string secretBase32, - int digits = 6, - int period = 30, - string algorithm = "SHA1" - ) + public string BuildOtpAuthUri(string issuer, string accountName, string secretBase32, int digits = 6, int period = 30, string algorithm = "SHA1") { var label = Uri.EscapeDataString($"{issuer}:{accountName}"); - var query = - $"secret={secretBase32}&issuer={Uri.EscapeDataString(issuer)}&algorithm={algorithm}&digits={digits}&period={period}"; + var query = $"secret={secretBase32}&issuer={Uri.EscapeDataString(issuer)}&algorithm={algorithm}&digits={digits}&period={period}"; return $"otpauth://totp/{label}?{query}"; } public byte[] Protect(byte[] secret) => _protector.Protect(secret); - public byte[] Unprotect(byte[] protectedSecret) => _protector.Unprotect(protectedSecret); - public bool VerifyWithSecretBase32( - string secretBase32, - string code, - int digits = 6, - int period = 30, - int window = 1 - ) + public bool VerifyWithSecretBase32(string secretBase32, string code, int digits = 6, int period = 30, int window = 1) { var secret = FromBase32(secretBase32); return VerifyCode(secret, code, out _, digits, period, window); } - private bool VerifyCode( - byte[] secret, - string code, - out long matchedStep, - int digits = 6, - int period = 30, - int window = 1 - ) + private bool VerifyCode(byte[] secret, string code, out long matchedStep, int digits = 6, int period = 30, int window = 1) { var totp = new Totp(secret, step: period, mode: OtpHashMode.Sha1, totpSize: digits); - return totp.VerifyTotp( - code, - out matchedStep, - new VerificationWindow(previous: window, future: window) - ); + return totp.VerifyTotp(code, out matchedStep, new VerificationWindow(previous: window, future: window)); } - private string ComputeCode(byte[] key, long timestep, int digits) => - new Totp(key, totpSize: digits).ComputeTotp(DateTime.UtcNow); + private string ComputeCode(byte[] key, long timestep, int digits) => new Totp(key, totpSize: digits).ComputeTotp(DateTime.UtcNow); } } diff --git a/SharpbinV3.Server/Services/Verification/Providers/TurnstileVerificationProvider.cs b/SharpbinV3.Server/Services/Verification/Providers/TurnstileVerificationProvider.cs index ea08228..75b3c7d 100644 --- a/SharpbinV3.Server/Services/Verification/Providers/TurnstileVerificationProvider.cs +++ b/SharpbinV3.Server/Services/Verification/Providers/TurnstileVerificationProvider.cs @@ -1,23 +1,17 @@ -using System.Text.Json; -using Microsoft.Extensions.Options; +using Microsoft.Extensions.Options; using SharpbinV3.Server.DTOs.Auth; using SharpbinV3.Server.Settings; +using System.Text.Json; namespace SharpbinV3.Server.Services.Verification.Providers { - public sealed class TurnstileVerificationProvider( - IOptions options, - HttpClient httpClient - ) : IVerificationProvider + public sealed class TurnstileVerificationProvider(IOptions options, HttpClient httpClient) : IVerificationProvider { private readonly AuthSettings _authSettings = options.Value; - private const string SiteverifyUrl = - "https://challenges.cloudflare.com/turnstile/v0/siteverify"; + private const string SiteverifyUrl = "https://challenges.cloudflare.com/turnstile/v0/siteverify"; public int Priority => 1; - public bool IsConfigured => - !string.IsNullOrEmpty(_authSettings.CF_Turnstile_SecretKey) - && !string.IsNullOrEmpty(_authSettings.CF_Turnstile_SiteKey); + public bool IsConfigured => !string.IsNullOrEmpty(_authSettings.CF_Turnstile_SecretKey) && !string.IsNullOrEmpty(_authSettings.CF_Turnstile_SiteKey); public async Task VerifyAsync(VerificationContext ctx) { @@ -29,7 +23,7 @@ namespace SharpbinV3.Server.Services.Verification.Providers var parameters = new Dictionary { { "secret", _authSettings.CF_Turnstile_SecretKey }, - { "response", ctx.Token }, + { "response", ctx.Token } }; if (!string.IsNullOrEmpty(ctx.Ip)) diff --git a/SharpbinV3.Server/Services/Verification/VerificationContext.cs b/SharpbinV3.Server/Services/Verification/VerificationContext.cs index a3e224b..e4beed8 100644 --- a/SharpbinV3.Server/Services/Verification/VerificationContext.cs +++ b/SharpbinV3.Server/Services/Verification/VerificationContext.cs @@ -8,4 +8,5 @@ public Guid? UserUUID { get; init; } public string? Code { get; init; } } + } diff --git a/SharpbinV3.Server/Services/Verification/VerificationService.cs b/SharpbinV3.Server/Services/Verification/VerificationService.cs index 5a38b57..8b5670d 100644 --- a/SharpbinV3.Server/Services/Verification/VerificationService.cs +++ b/SharpbinV3.Server/Services/Verification/VerificationService.cs @@ -14,10 +14,7 @@ namespace SharpbinV3.Server.Services.Verification .FirstOrDefault(); } - public async Task VerifyAsync( - VerificationContext context, - IVerificationProvider? provider = null - ) + public async Task VerifyAsync(VerificationContext context, IVerificationProvider? provider = null) { var activeProvider = provider ?? GetActiveProvider(); diff --git a/SharpbinV3.Server/SharpbinV3.Server.csproj b/SharpbinV3.Server/SharpbinV3.Server.csproj index e7f210c..555aaac 100644 --- a/SharpbinV3.Server/SharpbinV3.Server.csproj +++ b/SharpbinV3.Server/SharpbinV3.Server.csproj @@ -1,4 +1,5 @@ + net10.0 enable @@ -24,15 +25,10 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive - - + + + diff --git a/SharpbinV3.Server/Utilities.cs b/SharpbinV3.Server/Utilities.cs index 44ccd8c..c4ddbf6 100644 --- a/SharpbinV3.Server/Utilities.cs +++ b/SharpbinV3.Server/Utilities.cs @@ -6,9 +6,7 @@ { const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; var random = new Random(); - return new string([ - .. Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)]), - ]); + return new string([.. Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)])]); } } }