diff --git a/.gitignore b/.gitignore index 4a06601..8e0a7e6 100644 --- a/.gitignore +++ b/.gitignore @@ -326,4 +326,5 @@ FodyWeavers.xsd **/*.sqlite Data -!SharpbinV3.Server/Data \ No newline at end of file +!SharpbinV3.Server/Data +.idea \ No newline at end of file diff --git a/SharpbinV3.Server/.gitignore b/SharpbinV3.Server/.gitignore index 4af4d6b..9fb8d41 100644 --- a/SharpbinV3.Server/.gitignore +++ b/SharpbinV3.Server/.gitignore @@ -1 +1,2 @@ -SharpbinV3 \ No newline at end of file +SharpbinV3 +.idea \ No newline at end of file diff --git a/SharpbinV3.Server/Controllers/AuthController.cs b/SharpbinV3.Server/Controllers/AuthController.cs index b4dabf7..be2b2b0 100644 --- a/SharpbinV3.Server/Controllers/AuthController.cs +++ b/SharpbinV3.Server/Controllers/AuthController.cs @@ -34,7 +34,7 @@ namespace SharpbinV3.Server.Controllers public async Task Register([FromBody] RegisterUserDto request) { if (!options.Value.Registration_Enabled) - return BadRequest(new { message = "Registration is disabled." }); + return BadRequest(new { success = false, message = "Registration is disabled." }); if (!ModelState.IsValid) return BadRequest(ModelState); if (!await _verification.VerifyAsync(new VerificationContext @@ -42,19 +42,19 @@ namespace SharpbinV3.Server.Controllers Token = request.Token, Ip = HttpContext.GetRequestIP() })) - return BadRequest(new { message = "Verification failed." }); + return BadRequest(new { success = false, message = "Verification failed." }); var existingUser = await _userService.GetByUsername(request.Username); if (existingUser != null) - return Conflict(new { message = "Username already exists." }); + return Conflict(new { success = false, message = "Username already exists." }); if (!string.IsNullOrEmpty(request.Email)) { var existingEmailUser = await _userService.GetByEmail(request.Email); if (existingEmailUser != null) - return Conflict(new { message = "Email already in use." }); + return Conflict(new { success = false, 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 { success = false, message = "Display name should not exceed 26 characters." }); var user = await _authService.CreateUser(request.Username, request.Password, request.Email, request.DisplayName); return Ok(new @@ -79,41 +79,40 @@ namespace SharpbinV3.Server.Controllers public async Task Login([FromBody] LoginUserDto request) { if (string.IsNullOrEmpty(request.Username) && string.IsNullOrEmpty(request.Email)) - return BadRequest(new { message = "Username or email is required." }); + return BadRequest(new { success = false, message = "Username or email is required." }); if (!await _verification.VerifyAsync(new VerificationContext { Token = request.Token, Ip = HttpContext.GetRequestIP() })) - return BadRequest(new { message = "Verification failed." }); + return BadRequest(new { success = false, message = "Verification failed." }); User? user = null; if (!string.IsNullOrEmpty(request.Username)) user = await _userService.GetByUsername(request.Username); 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 (!Bcrypt.Verify(request.Password, user.PasswordHash)) - return BadRequest(new { message = "Invalid username/email or password." }); + + if (user == null || !Bcrypt.Verify(request.Password, user.PasswordHash)) + return BadRequest(new { success = false, message = "Invalid username/email or password." }); var totpEnabled = await _db.UserTotps.AnyAsync(t => t.UserUUID == user.UUID); if (totpEnabled) { if (string.IsNullOrWhiteSpace(request.TotpCode)) - return BadRequest(new { message = "TOTP code is required." }); + return BadRequest(new { success = false, message = "TOTP code is required." }); var totpValid = await _totp.VerifyAsync(new VerificationContext { UserUUID = user.UUID, Code = request.TotpCode }); if (!totpValid) - return BadRequest(new { message = "Invalid TOTP code." }); + return BadRequest(new { success = false, message = "Invalid TOTP code." }); } var token = _authService.GenerateJWTToken(user); await _authService.UpdateLoginTime(user); - return Ok(new { token.Result }); + return Ok(new { success = true, token.Result }); } [HttpPost] [Route("refresh")] @@ -123,17 +122,26 @@ namespace SharpbinV3.Server.Controllers try { var jwtResult = await _authService.RefreshJWTToken(request.Token, request.RefreshToken); - return Ok(new { token = jwtResult }); + return Ok(new + { + success = jwtResult?.Success, + message = jwtResult?.Errors != null && jwtResult.Errors.Count > 0 ? string.Join("; ", jwtResult.Errors) : "Token refreshed successfully.", + token = new + { + jwtResult?.Token, + jwtResult?.RefreshToken + } + }); } catch (Exception ex) { - return BadRequest(new { message = ex.Message }); + return BadRequest(new { success = false, message = ex.Message }); } } [HttpGet] [Route("info")] - public async Task GetSiteInfo() + public IActionResult GetSiteInfo() { var authSettings = options.Value; return Ok(new @@ -149,13 +157,13 @@ 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 { success = false, message = "User not found." }); var secret = _totp.GenerateSecret(); var secretBase32 = _totp.ToBase32(secret); var account = string.IsNullOrWhiteSpace(user.Email) ? user.Username : user.Email!; var uri = _totp.BuildOtpAuthUri("SharpbinV3", account, secretBase32); - return Ok(new { secret = secretBase32, otpauth = uri }); + return Ok(new { success = true, secret = secretBase32, otpauth = uri }); } [HttpPost] @@ -164,13 +172,15 @@ 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(new { success = false, message = "Invalid token." }); + var uuid = Guid.Parse(uuidClaim); if (string.IsNullOrWhiteSpace(request.Secret) || string.IsNullOrWhiteSpace(request.Code)) - return BadRequest(new { message = "Secret and code are required." }); + return BadRequest(new { success = false, message = "Secret and code are required." }); if (!_totp.VerifyWithSecretBase32(request.Secret, request.Code)) - return BadRequest(new { message = "Invalid TOTP code." }); + return BadRequest(new { success = false, message = "Invalid TOTP code." }); var secretBytes = _totp.FromBase32(request.Secret); var protectedBytes = _totp.Protect(secretBytes); @@ -186,7 +196,7 @@ namespace SharpbinV3.Server.Controllers _db.UserTotps.Update(existing); } await _db.SaveChangesAsync(); - return Ok(new { message = "TOTP enabled." }); + return Ok(new { success = true, message = "TOTP enabled." }); } [HttpPost] @@ -195,22 +205,22 @@ 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 { success = false, message = "User not found." }); if (string.IsNullOrWhiteSpace(dto.Code)) - return BadRequest(new { message = "TOTP code is required." }); + return BadRequest(new { success = false, 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." }); + return BadRequest(new { success = false, message = "TOTP is not enabled." }); if (!_totp.VerifyAsync(new VerificationContext { UserUUID = user.UUID, Code = dto.Code }).Result) - return BadRequest(new { message = "Invalid TOTP code." }); + return BadRequest(new { success = false, message = "Invalid TOTP code." }); _db.UserTotps.Remove(existing); await _db.SaveChangesAsync(); - return Ok(new { message = "TOTP disabled." }); + return Ok(new { success = true, message = "TOTP disabled." }); } } } diff --git a/SharpbinV3.Server/Controllers/PasteController.cs b/SharpbinV3.Server/Controllers/PasteController.cs index 2ee31d2..8e31190 100644 --- a/SharpbinV3.Server/Controllers/PasteController.cs +++ b/SharpbinV3.Server/Controllers/PasteController.cs @@ -26,26 +26,26 @@ namespace SharpbinV3.Server.Controllers 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." }); + return BadRequest(new { success = false, 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 { success = false, message = "Invalid visibility level. Must be between 0 and 2." }); if (!await _pasteService.ValidateSyntax(syntax)) - return BadRequest(new { message = "Invalid syntax." }); + return BadRequest(new { success = false, message = "Invalid syntax." }); if (!await _pasteService.ValidateTitle(title)) - return BadRequest(new { message = $"Invalid title. Must be less than {_pasteSettings.MaxTitleLength} characters." }); + return BadRequest(new { success = false, 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." }); + return BadRequest(new { success = false, 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." }); + return BadRequest(new { success = false, 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() })) - return BadRequest(new { message = "Verification failed." }); + return BadRequest(new { success = false, message = "Verification failed." }); var user = await _authService.GetUserFromHttpContext(HttpContext); Paste paste = await _pasteService.Create(user, content, title, syntax, visibility, expiresAt, _pasteSettings.EnablePasteCompression); @@ -111,12 +111,16 @@ 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 Unauthorized(new { success = false, message = "Invalid token." }); var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255); if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole) @@ -135,17 +139,19 @@ namespace SharpbinV3.Server.Controllers 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(new { success = false, message = "Paste not found." }); var user = HttpContext.GetJwtUser(); - if (user == null) return Forbid(); + if (user == null) + return Unauthorized(new { success = false, message = "Invalid token." }); var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255); if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole) - return Forbid(); + return StatusCode(403, new { success = false, message = "You do not have permission to modify this paste." }); if (user.Roles.Contains(255) && !user.TotpEnabled && _authSettings.Admins_Require_2FA) - return Forbid(); + return StatusCode(403, new { success = false, message = "2FA is required to perform this action." }); if (request.Title != null) paste.Title = request.Title; if (request.Syntax != null) @@ -156,17 +162,18 @@ namespace SharpbinV3.Server.Controllers paste.ExpiresAt = request.ExpiresAt.Value; if (!await _pasteService.ValidateExpiresAt(paste.ExpiresAt)) - return BadRequest(new { message = "Invalid expiration time." }); + return BadRequest(new { success = false, 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 { success = false, message = "Invalid visibility level. Must be between 0 and 2." }); if (!await _pasteService.ValidateSyntax(paste.Syntax ?? "plaintext")) - return BadRequest(new { message = "Invalid syntax." }); + return BadRequest(new { success = false, 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 { success = false, message = $"Invalid title. Must be less than {_pasteSettings.MaxTitleLength} characters." }); var newPaste = await _pasteService.Edit(paste); return Ok(new { + success = true, message = "Paste metadata updated successfully.", paste = new { @@ -189,20 +196,21 @@ namespace SharpbinV3.Server.Controllers public async Task DeletePaste(string id) { var paste = await _pasteService.Get(id); - if (paste == null) return NotFound(); + if (paste == null) return NotFound(new { success = false, message = "Paste not found." }); var user = HttpContext.GetJwtUser(); - if (user == null) return Forbid(); + if (user == null) + return Unauthorized(new { success = false, message = "Invalid token." }); var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255); if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole) - return Forbid(); + return StatusCode(403, new { success = false, message = "You do not have permission to delete this paste." }); if (user.Roles.Contains(255) && !user.TotpEnabled && _authSettings.Admins_Require_2FA) - return Forbid(); + return StatusCode(403, new { success = false, message = "2FA is required to perform this action." }); bool result = await _pasteService.Delete(paste); - if (!result) return NotFound(); - return Ok(new { message = "Paste deleted successfully." }); + if (!result) return StatusCode(500, new { success = false, message = "An error occurred while deleting the paste." }); + return Ok(new { success = true, message = "Paste deleted successfully." }); } [HttpGet] diff --git a/SharpbinV3.Server/Controllers/UserController.cs b/SharpbinV3.Server/Controllers/UserController.cs index b3fc85a..0e03fd2 100644 --- a/SharpbinV3.Server/Controllers/UserController.cs +++ b/SharpbinV3.Server/Controllers/UserController.cs @@ -28,14 +28,14 @@ namespace SharpbinV3.Server.Controllers public async Task GetByUsername(string username, [FromQuery] int page = 1) { var user = await _userService.GetByUsername(username, withPastes: true); - return user == null ? NotFound() : Ok(await BuildUserResponse(user, page)); + return user == null ? NotFound(new { success = false, message = "User not found." }) : Ok(await BuildUserResponse(user, page)); } [HttpGet("uuid/{uuid}")] public async Task GetByUUID(Guid uuid, [FromQuery] int page = 1) { var user = await _userService.GetByUUID(uuid, withPastes: true); - return user == null ? NotFound() : Ok(await BuildUserResponse(user, page)); + return user == null ? NotFound(new { success = false, message = "User not found."}) : Ok(await BuildUserResponse(user, page)); } [HttpGet("me")] @@ -44,10 +44,10 @@ namespace SharpbinV3.Server.Controllers { var userUUID = HttpContext.User?.FindFirst("UUID")?.Value; if (userUUID is null) - return Unauthorized(new { message = "Invalid token." }); + return Unauthorized(new { success = false, message = "Invalid token." }); var user = await _userService.GetByUUID(Guid.Parse(userUUID), withPastes: true); - return user == null ? NotFound() : Ok(await BuildUserResponse(user, page)); + return user == null ? NotFound(new { success = false, message = "User not found."}) : Ok(await BuildUserResponse(user, page)); } [HttpPatch("uuid/{uuid}")] @@ -56,17 +56,20 @@ namespace SharpbinV3.Server.Controllers { if (!ModelState.IsValid) return BadRequest(ModelState); + var jwtUser = HttpContext.GetJwtUser(); - if (jwtUser == null) return Forbid(); + if (jwtUser == null) + return Unauthorized(new { success = false, message = "Invalid token." }); + var user = await _userService.GetByUUID(uuid); if (user == null) - return NotFound(); - if (!jwtUser.Roles.Any(r => r == 1 || r == 255) && user.UUID != jwtUser.UUID) - return Forbid(); - if (user.Roles.Contains(255) && !jwtUser.Roles.Contains(255)) - return Forbid(); + return NotFound(new { success = false, message = "User not found." }); + + if ((user.Roles.Contains(255) && !jwtUser.Roles.Contains(255)) || (!jwtUser.Roles.Any(r => r == 1 || r == 255) && user.UUID != jwtUser.UUID)) + return StatusCode(403, new { success = false, message = "You do not have permission to modify this user." }); + if (jwtUser.Roles.Contains(255) && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA) - return Forbid(); + return StatusCode(403, new { success = false, message = "2FA is required to perform this action." }); user.DisplayName = updatedUser.DisplayName ?? user.DisplayName; if (jwtUser.Roles.Any(r => r == 255) || user.UUID == jwtUser.UUID) // only admins or self @@ -99,13 +102,17 @@ 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 Unauthorized(new { success = false, message = "Invalid token." }); + var user = await _userService.GetByUUID(uuid); - if (user == null) return Forbid(); + if (user == null) + return NotFound(new { success = false, message = "User not found." }); + if (!jwtUser.Roles.Any(r => r == 255) && user.UUID != jwtUser.UUID) - return Forbid(); + return StatusCode(403, new { success = false, message = "You do not have permission to delete this user." }); if (jwtUser.Roles.Contains(255) && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA) - return Forbid(); + return StatusCode(403, new { success = false, message = "2FA is required to perform this action." }); if (jwtUser.TotpEnabled) {