Revert "chore: format via csharpier"

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