diff --git a/SharpbinV3.Server/Authorization/NotBannedHandler.cs b/SharpbinV3.Server/Authorization/NotBannedHandler.cs index 70a05c8..0773926 100644 --- a/SharpbinV3.Server/Authorization/NotBannedHandler.cs +++ b/SharpbinV3.Server/Authorization/NotBannedHandler.cs @@ -1,15 +1,17 @@ -using Microsoft.AspNetCore.Authorization; -using System.Security.Claims; +using System.Security.Claims; +using Microsoft.AspNetCore.Authorization; 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; @@ -17,8 +19,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 cf09026..28bb17f 100644 --- a/SharpbinV3.Server/Authorization/NotBannedRequirement.cs +++ b/SharpbinV3.Server/Authorization/NotBannedRequirement.cs @@ -2,7 +2,5 @@ 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 b4dabf7..5ec6ce9 100644 --- a/SharpbinV3.Server/Controllers/AuthController.cs +++ b/SharpbinV3.Server/Controllers/AuthController.cs @@ -19,8 +19,14 @@ 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; @@ -37,11 +43,15 @@ 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); @@ -54,22 +64,30 @@ 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 - { - message = "User registered successfully.", - user = new + var user = await _authService.CreateUser( + request.Username, + request.Password, + request.Email, + request.DisplayName + ); + return Ok( + new { - user.UID, - user.UUID, - user.Username, - user.Email, - user.DisplayName, - user.Roles + message = "User registered successfully.", + user = new + { + user.UID, + user.UUID, + user.Username, + user.Email, + user.DisplayName, + user.Roles, + }, } - } ); } @@ -81,11 +99,15 @@ 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; @@ -94,7 +116,8 @@ 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." }); @@ -103,11 +126,9 @@ 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." }); } @@ -115,6 +136,7 @@ namespace SharpbinV3.Server.Controllers await _authService.UpdateLoginTime(user); return Ok(new { token.Result }); } + [HttpPost] [Route("refresh")] [EnableRateLimiting("Sliding")] @@ -122,7 +144,10 @@ 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) @@ -136,11 +161,15 @@ 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] @@ -149,7 +178,8 @@ 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); @@ -164,9 +194,12 @@ 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)) @@ -195,17 +228,18 @@ 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 2ee31d2..6b88aa1 100644 --- a/SharpbinV3.Server/Controllers/PasteController.cs +++ b/SharpbinV3.Server/Controllers/PasteController.cs @@ -12,7 +12,13 @@ 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; @@ -23,77 +29,116 @@ 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 - { - 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 + if (paste == null) + return NotFound(); + return Ok( + new { - paste.User.UID, - paste.User.UUID, - paste.User.Username, - paste.User.DisplayName, - paste.User.Visibility - } : null - }); + 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, + } + ); } + [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"); @@ -111,34 +156,63 @@ 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); @@ -158,41 +232,53 @@ 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 - { - message = "Paste metadata updated successfully.", - paste = new + return Ok( + new { - newPaste.ID, - newPaste.UUID, - newPaste.Title, - newPaste.Size, - newPaste.TrueSize, - newPaste.IsCompressed, - newPaste.Views, - newPaste.Syntax, - newPaste.Visibility, - newPaste.ExpiresAt + 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, + }, } - }); + ); } + [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) @@ -201,7 +287,8 @@ 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." }); } @@ -210,20 +297,22 @@ 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] @@ -237,11 +326,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 b3fc85a..9a59e93 100644 --- a/SharpbinV3.Server/Controllers/UserController.cs +++ b/SharpbinV3.Server/Controllers/UserController.cs @@ -16,7 +16,13 @@ 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; @@ -52,12 +58,16 @@ 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(); @@ -65,7 +75,11 @@ 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; @@ -78,11 +92,16 @@ 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." }); } @@ -99,32 +118,44 @@ 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." }); } @@ -137,7 +168,8 @@ 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) { @@ -170,7 +202,7 @@ namespace SharpbinV3.Server.Controllers p.Views, p.Visibility, p.EditedAt, - p.ExpiresAt + p.ExpiresAt, }) .ToListAsync(); @@ -179,7 +211,7 @@ namespace SharpbinV3.Server.Controllers Page = page, PageSize = pageSize, TotalCount = totalCount, - TotalPages = totalPages + TotalPages = totalPages, }; if (isAuthenticatedUser) @@ -195,7 +227,7 @@ namespace SharpbinV3.Server.Controllers user.Roles, user.Visibility, Pastes = pastes, - Pagination = pagination + Pagination = pagination, }; } @@ -207,7 +239,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 ee4c915..91c25e7 100644 --- a/SharpbinV3.Server/DTOs/Auth/RefreshTokenDto.cs +++ b/SharpbinV3.Server/DTOs/Auth/RefreshTokenDto.cs @@ -6,6 +6,7 @@ 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 22ab315..5c2629d 100644 --- a/SharpbinV3.Server/DTOs/Auth/TurnstileResponseDto.cs +++ b/SharpbinV3.Server/DTOs/Auth/TurnstileResponseDto.cs @@ -6,6 +6,7 @@ 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 c10f5be..185d121 100644 --- a/SharpbinV3.Server/DTOs/User/LoginUserDto.cs +++ b/SharpbinV3.Server/DTOs/User/LoginUserDto.cs @@ -7,6 +7,7 @@ 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 c59d9a6..d3b49df 100644 --- a/SharpbinV3.Server/DTOs/User/RegisterUserDto.cs +++ b/SharpbinV3.Server/DTOs/User/RegisterUserDto.cs @@ -22,16 +22,36 @@ 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) { @@ -44,6 +64,7 @@ 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 ff24814..1b5c8fd 100644 --- a/SharpbinV3.Server/DTOs/User/UpdateUserDto.cs +++ b/SharpbinV3.Server/DTOs/User/UpdateUserDto.cs @@ -17,9 +17,19 @@ 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) { @@ -30,19 +40,27 @@ 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 330b8bb..b8b9f36 100644 --- a/SharpbinV3.Server/Extensions/HttpContextExtensions.cs +++ b/SharpbinV3.Server/Extensions/HttpContextExtensions.cs @@ -1,20 +1,21 @@ -using SharpbinV3.Server.Services; -using System.IdentityModel.Tokens.Jwt; +using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; +using SharpbinV3.Server.Services; namespace SharpbinV3.Server.Extensions { public static class HttpContextExtensions { - public readonly static string[] ipHeaders = + public static readonly 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) @@ -36,9 +37,10 @@ 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 { @@ -47,7 +49,7 @@ namespace SharpbinV3.Server.Extensions DisplayName = displayName, TotpEnabled = totpEnabled, Roles = roles.Length > 0 ? roles : [0], - Expires = expires + Expires = expires, }; } @@ -55,7 +57,12 @@ 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 3fcd97f..8dc8445 100644 --- a/SharpbinV3.Server/Migrations/20251125015039_Init.cs +++ b/SharpbinV3.Server/Migrations/20251125015039_Init.cs @@ -14,7 +14,8 @@ 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), @@ -23,18 +24,20 @@ 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), @@ -48,7 +51,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 => { @@ -57,8 +60,10 @@ namespace SharpbinV3.Server.Migrations name: "FK_Pastes_Users_UserUID", column: x => x.UserUID, principalTable: "Users", - principalColumn: "UID"); - }); + principalColumn: "UID" + ); + } + ); migrationBuilder.CreateTable( name: "RefreshTokens", @@ -70,7 +75,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 => { @@ -79,81 +84,87 @@ 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 c0e0a08..8697ace 100644 --- a/SharpbinV3.Server/Migrations/20251125053617_ImprovePastes.cs +++ b/SharpbinV3.Server/Migrations/20251125053617_ImprovePastes.cs @@ -10,42 +10,39 @@ 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 6d7fd57..759e8bc 100644 --- a/SharpbinV3.Server/Migrations/20251125055340_PasteContent.cs +++ b/SharpbinV3.Server/Migrations/20251125055340_PasteContent.cs @@ -10,19 +10,13 @@ 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 1ddcf70..c58ef49 100644 --- a/SharpbinV3.Server/Migrations/20251125061310_GrammarFix.cs +++ b/SharpbinV3.Server/Migrations/20251125061310_GrammarFix.cs @@ -13,12 +13,14 @@ 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" + ); } /// @@ -27,12 +29,14 @@ 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 c460750..d1096c1 100644 --- a/SharpbinV3.Server/Migrations/20251228173503_UserGrammarFix.cs +++ b/SharpbinV3.Server/Migrations/20251228173503_UserGrammarFix.cs @@ -10,29 +10,22 @@ 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 7e66958..863dee9 100644 --- a/SharpbinV3.Server/Migrations/20251228175338_LongFileSizes.cs +++ b/SharpbinV3.Server/Migrations/20251228175338_LongFileSizes.cs @@ -8,15 +8,9 @@ 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 8638de1..f2f8cfe 100644 --- a/SharpbinV3.Server/Migrations/20251231161600_UserUUIDKey.cs +++ b/SharpbinV3.Server/Migrations/20251231161600_UserUUIDKey.cs @@ -10,47 +10,35 @@ 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", @@ -58,7 +46,8 @@ namespace SharpbinV3.Server.Migrations column: "AuthorUUID", principalTable: "Users", principalColumn: "UUID", - onDelete: ReferentialAction.Cascade); + onDelete: ReferentialAction.Cascade + ); migrationBuilder.AddForeignKey( name: "FK_RefreshTokens_Users_UserUUID", @@ -66,73 +55,76 @@ 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 87c5612..e859461 100644 --- a/SharpbinV3.Server/Migrations/20260104211956_UserUIDAutoIncrement.cs +++ b/SharpbinV3.Server/Migrations/20260104211956_UserUIDAutoIncrement.cs @@ -10,25 +10,30 @@ 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 84a03ba..247b3c0 100644 --- a/SharpbinV3.Server/Migrations/20260104212417_UserUIDIndex.cs +++ b/SharpbinV3.Server/Migrations/20260104212417_UserUIDIndex.cs @@ -14,15 +14,14 @@ 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 21b1635..1dd45f5 100644 --- a/SharpbinV3.Server/Migrations/20260104212733_UserUIDNonUnique.cs +++ b/SharpbinV3.Server/Migrations/20260104212733_UserUIDNonUnique.cs @@ -10,9 +10,7 @@ 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", @@ -20,20 +18,16 @@ 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", @@ -43,13 +37,15 @@ 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 06191b8..33a3347 100644 --- a/SharpbinV3.Server/Migrations/20260106211303_NullableAuthorUUID.cs +++ b/SharpbinV3.Server/Migrations/20260106211303_NullableAuthorUUID.cs @@ -16,7 +16,8 @@ namespace SharpbinV3.Server.Migrations type: "TEXT", nullable: true, oldClrType: typeof(Guid), - oldType: "TEXT"); + oldType: "TEXT" + ); } /// @@ -30,7 +31,8 @@ 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 6de9e6d..21b0b8c 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,15 +26,16 @@ 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 a754d9d..8ed15a5 100644 --- a/SharpbinV3.Server/Program.cs +++ b/SharpbinV3.Server/Program.cs @@ -1,3 +1,5 @@ +using System.Text; +using System.Threading.RateLimiting; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.DataProtection; @@ -10,8 +12,6 @@ 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,11 +40,10 @@ 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"); @@ -67,44 +66,58 @@ 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"); @@ -130,7 +143,8 @@ 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 @@ -140,13 +154,15 @@ 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 0f567c0..02174a6 100644 --- a/SharpbinV3.Server/Services/AuthService.cs +++ b/SharpbinV3.Server/Services/AuthService.cs @@ -1,13 +1,13 @@ -using Microsoft.EntityFrameworkCore; +using System.IdentityModel.Tokens.Jwt; +using System.Security.Claims; +using System.Text; +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,13 +21,23 @@ 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 { @@ -35,7 +45,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()) @@ -45,6 +55,7 @@ namespace SharpbinV3.Server.Services await _db.SaveChangesAsync(); return user; } + public async Task GenerateJWTToken(User user) { var jwtHandler = new JwtSecurityTokenHandler(); @@ -57,7 +68,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) @@ -79,20 +90,24 @@ 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); } @@ -106,7 +121,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); } @@ -117,7 +132,9 @@ 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, }; } @@ -127,28 +144,39 @@ 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(); @@ -167,7 +195,9 @@ 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; @@ -178,9 +208,12 @@ 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 28796bb..8ee5056 100644 --- a/SharpbinV3.Server/Services/CompressionService.cs +++ b/SharpbinV3.Server/Services/CompressionService.cs @@ -1,6 +1,5 @@ using System.IO.Compression; - namespace SharpbinV3.Server.Services { public class CompressionService : ICompressionService @@ -21,16 +20,21 @@ 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 6c5adc5..899e7d2 100644 --- a/SharpbinV3.Server/Services/PasteCleanUpService.cs +++ b/SharpbinV3.Server/Services/PasteCleanUpService.cs @@ -3,14 +3,21 @@ 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 { @@ -36,7 +43,6 @@ 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 c352b64..d583b9b 100644 --- a/SharpbinV3.Server/Services/PasteService.cs +++ b/SharpbinV3.Server/Services/PasteService.cs @@ -1,19 +1,31 @@ -using Microsoft.EntityFrameworkCore; +using System.Text; +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) @@ -50,20 +62,24 @@ 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); @@ -79,39 +95,41 @@ 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 f61bd9a..7f781c0 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 10622fe..60a1c0d 100644 --- a/SharpbinV3.Server/Services/Verification/Providers/TotpVerificationProvider.cs +++ b/SharpbinV3.Server/Services/Verification/Providers/TotpVerificationProvider.cs @@ -12,7 +12,11 @@ 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"); @@ -24,11 +28,16 @@ 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)) @@ -44,30 +53,58 @@ 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 75b3c7d..ea08228 100644 --- a/SharpbinV3.Server/Services/Verification/Providers/TurnstileVerificationProvider.cs +++ b/SharpbinV3.Server/Services/Verification/Providers/TurnstileVerificationProvider.cs @@ -1,17 +1,23 @@ -using Microsoft.Extensions.Options; +using System.Text.Json; +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) { @@ -23,7 +29,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 e4beed8..a3e224b 100644 --- a/SharpbinV3.Server/Services/Verification/VerificationContext.cs +++ b/SharpbinV3.Server/Services/Verification/VerificationContext.cs @@ -8,5 +8,4 @@ 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 8b5670d..5a38b57 100644 --- a/SharpbinV3.Server/Services/Verification/VerificationService.cs +++ b/SharpbinV3.Server/Services/Verification/VerificationService.cs @@ -14,7 +14,10 @@ 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 555aaac..e7f210c 100644 --- a/SharpbinV3.Server/SharpbinV3.Server.csproj +++ b/SharpbinV3.Server/SharpbinV3.Server.csproj @@ -1,5 +1,4 @@ - net10.0 enable @@ -25,10 +24,15 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive - - + + - diff --git a/SharpbinV3.Server/Utilities.cs b/SharpbinV3.Server/Utilities.cs index c4ddbf6..44ccd8c 100644 --- a/SharpbinV3.Server/Utilities.cs +++ b/SharpbinV3.Server/Utilities.cs @@ -6,7 +6,9 @@ { 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)]), + ]); } } }