chore: format via csharpier

This commit is contained in:
2026-01-09 15:13:57 -05:00
parent 284c5e927e
commit 7a2eb699f4
35 changed files with 784 additions and 464 deletions
+80 -46
View File
@@ -19,8 +19,14 @@ namespace SharpbinV3.Server.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class AuthController(UserService userService, AuthService authService, IOptions<AuthSettings> options,
VerificationService verification, TotpVerificationProvider totp, AppDbContext db) : ControllerBase
public class AuthController(
UserService userService,
AuthService authService,
IOptions<AuthSettings> 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<IActionResult> 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<IActionResult> 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<IActionResult> 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<IActionResult> 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);
+178 -89
View File
@@ -12,7 +12,13 @@ namespace SharpbinV3.Server.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class PasteController(PasteService pasteService, VerificationService verificationService, AuthService authService, IOptions<PasteSettings> options, IOptions<AuthSettings> authSettings) : ControllerBase
public class PasteController(
PasteService pasteService,
VerificationService verificationService,
AuthService authService,
IOptions<PasteSettings> options,
IOptions<AuthSettings> 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<IActionResult> CreatePaste(string title = "", string syntax = "plaintext", int visibility = 0, long expiresAt = 0, string? token = null)
public async Task<IActionResult> 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<IActionResult> 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<IActionResult> 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<IActionResult> 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<IActionResult> ModifyPasteMetadata(string id, [FromBody] UpdatePasteDto request)
public async Task<IActionResult> 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<IActionResult> 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<IActionResult> 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);
}
+59 -27
View File
@@ -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> authSettings) : ControllerBase
public class UserController(
UserService userService,
AppDbContext db,
TotpVerificationProvider totp,
VerificationService verificationService,
IOptions<AuthSettings> 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<IActionResult> UpdateByUUID(Guid uuid, [FromBody] UpdateUserDto updatedUser)
public async Task<IActionResult> 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<IActionResult> 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<object> 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,
};
}
}