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
@@ -1,15 +1,17 @@
using Microsoft.AspNetCore.Authorization; using System.Security.Claims;
using System.Security.Claims; using Microsoft.AspNetCore.Authorization;
namespace SharpbinV3.Server.Authorization namespace SharpbinV3.Server.Authorization
{ {
public sealed class NotBannedHandler(bool requireAuth = false) : AuthorizationHandler<NotBannedRequirement> public sealed class NotBannedHandler(bool requireAuth = false)
: 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;
@@ -17,8 +19,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.Type == ClaimTypes.Role || c.Type == "role") && c.Value == "403"
c.Value == "403"); );
if (!isBanned) if (!isBanned)
context.Succeed(requirement); context.Succeed(requirement);
@@ -2,7 +2,5 @@
namespace SharpbinV3.Server.Authorization namespace SharpbinV3.Server.Authorization
{ {
public class NotBannedRequirement : IAuthorizationRequirement public class NotBannedRequirement : IAuthorizationRequirement { }
{
}
} }
+67 -33
View File
@@ -19,8 +19,14 @@ namespace SharpbinV3.Server.Controllers
{ {
[ApiController] [ApiController]
[Route("api/[controller]")] [Route("api/[controller]")]
public class AuthController(UserService userService, AuthService authService, IOptions<AuthSettings> options, public class AuthController(
VerificationService verification, TotpVerificationProvider totp, AppDbContext db) : ControllerBase UserService userService,
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;
@@ -37,11 +43,15 @@ 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 (!await _verification.VerifyAsync(new VerificationContext if (
!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);
@@ -54,10 +64,18 @@ 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(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); var user = await _authService.CreateUser(
return Ok(new request.Username,
request.Password,
request.Email,
request.DisplayName
);
return Ok(
new
{ {
message = "User registered successfully.", message = "User registered successfully.",
user = new user = new
@@ -67,8 +85,8 @@ namespace SharpbinV3.Server.Controllers
user.Username, user.Username,
user.Email, user.Email,
user.DisplayName, user.DisplayName,
user.Roles user.Roles,
} },
} }
); );
} }
@@ -81,11 +99,15 @@ 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 (!await _verification.VerifyAsync(new VerificationContext if (
!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;
@@ -94,7 +116,8 @@ 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) 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)) 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." });
@@ -103,11 +126,9 @@ 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(new VerificationContext var totpValid = await _totp.VerifyAsync(
{ 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." });
} }
@@ -115,6 +136,7 @@ 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")]
@@ -122,7 +144,10 @@ namespace SharpbinV3.Server.Controllers
{ {
try try
{ {
var jwtResult = await _authService.RefreshJWTToken(request.Token, request.RefreshToken); var jwtResult = await _authService.RefreshJWTToken(
request.Token,
request.RefreshToken
);
return Ok(new { token = jwtResult }); return Ok(new { token = jwtResult });
} }
catch (Exception ex) catch (Exception ex)
@@ -136,11 +161,15 @@ namespace SharpbinV3.Server.Controllers
public async Task<IActionResult> GetSiteInfo() public async Task<IActionResult> GetSiteInfo()
{ {
var authSettings = options.Value; var authSettings = options.Value;
return Ok(new return Ok(
new
{ {
cf_turnstile_site_key = string.IsNullOrEmpty(authSettings.CF_Turnstile_SiteKey) ? null : authSettings.CF_Turnstile_SiteKey, cf_turnstile_site_key = string.IsNullOrEmpty(authSettings.CF_Turnstile_SiteKey)
registration_enabled = authSettings.Registration_Enabled ? null
}); : authSettings.CF_Turnstile_SiteKey,
registration_enabled = authSettings.Registration_Enabled,
}
);
} }
[HttpGet] [HttpGet]
@@ -149,7 +178,8 @@ 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) return BadRequest(new { message = "User not found." }); if (user is null)
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);
@@ -164,9 +194,12 @@ 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)) return Unauthorized(); if (string.IsNullOrEmpty(uuidClaim))
return Unauthorized();
var uuid = Guid.Parse(uuidClaim); 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." }); return BadRequest(new { message = "Secret and code are required." });
if (!_totp.VerifyWithSecretBase32(request.Secret, request.Code)) if (!_totp.VerifyWithSecretBase32(request.Secret, request.Code))
@@ -195,17 +228,18 @@ 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) return BadRequest(new { message = "User not found." }); if (user == null)
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 (!_totp.VerifyAsync(new VerificationContext if (
{ !_totp
UserUUID = user.UUID, .VerifyAsync(new VerificationContext { UserUUID = user.UUID, Code = dto.Code })
Code = dto.Code .Result
}).Result) )
return BadRequest(new { message = "Invalid TOTP code." }); return BadRequest(new { message = "Invalid TOTP code." });
_db.UserTotps.Remove(existing); _db.UserTotps.Remove(existing);
+133 -44
View File
@@ -12,7 +12,13 @@ namespace SharpbinV3.Server.Controllers
{ {
[Route("api/[controller]")] [Route("api/[controller]")]
[ApiController] [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 PasteService _pasteService = pasteService;
private readonly VerificationService _verificationService = verificationService; private readonly VerificationService _verificationService = verificationService;
@@ -23,49 +29,83 @@ namespace SharpbinV3.Server.Controllers
[HttpPost] [HttpPost]
[Route("create")] [Route("create")]
[Authorize(Policy = "NotBanned")] [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)) 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(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)) 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(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(); 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 (System.Text.Encoding.UTF8.GetByteCount(content) > _pasteSettings.MaxPasteSizeInBytes) if (
return BadRequest(new { message = $"Paste size exceeds the maximum allowed size of {_pasteSettings.MaxPasteSizeInBytes} bytes." }); System.Text.Encoding.UTF8.GetByteCount(content) > _pasteSettings.MaxPasteSizeInBytes
)
if (_pasteSettings.RequiresVerfication && !await _verificationService.VerifyAsync(new VerificationContext return BadRequest(
new
{ {
Token = token, message = $"Paste size exceeds the maximum allowed size of {_pasteSettings.MaxPasteSizeInBytes} bytes.",
Ip = HttpContext.GetRequestIP() }
})) );
if (
_pasteSettings.RequiresVerfication
&& !await _verificationService.VerifyAsync(
new VerificationContext { Token = token, 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(user, content, title, syntax, visibility, expiresAt, _pasteSettings.EnablePasteCompression); Paste paste = await _pasteService.Create(
return Ok(new user,
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) return NotFound(); if (paste == null)
return Ok(new return NotFound();
return Ok(
new
{ {
paste.ID, paste.ID,
paste.UUID, paste.UUID,
@@ -78,22 +118,27 @@ namespace SharpbinV3.Server.Controllers
paste.Visibility, paste.Visibility,
paste.ExpiresAt, paste.ExpiresAt,
paste.EditedAt, paste.EditedAt,
Author = paste.User != null && paste.User.Visibility == 0 ? new Author = paste.User != null && paste.User.Visibility == 0
? 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) return NotFound(); if (paste == null)
return NotFound();
if (paste.IsCompressed) if (paste.IsCompressed)
{ {
Response.Headers.Append("Content-Encoding", "gzip"); Response.Headers.Append("Content-Encoding", "gzip");
@@ -111,34 +156,63 @@ 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) 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); 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(); 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); var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole) 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) 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); 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." }); 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(string id, [FromBody] UpdatePasteDto request) public async Task<IActionResult> ModifyPasteMetadata(
string id,
[FromBody] UpdatePasteDto request
)
{ {
var paste = await _pasteService.Get(id); var paste = await _pasteService.Get(id);
if (paste == null) return NotFound(); if (paste == null)
return NotFound();
var user = HttpContext.GetJwtUser(); var user = HttpContext.GetJwtUser();
if (user == null) return Forbid(); if (user == null)
return Forbid();
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255); var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
@@ -158,14 +232,22 @@ 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(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")) 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(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); var newPaste = await _pasteService.Edit(paste);
return Ok(new return Ok(
new
{ {
message = "Paste metadata updated successfully.", message = "Paste metadata updated successfully.",
paste = new paste = new
@@ -179,20 +261,24 @@ 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) return NotFound(); if (paste == null)
return NotFound();
var user = HttpContext.GetJwtUser(); var user = HttpContext.GetJwtUser();
if (user == null) return Forbid(); if (user == null)
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)
@@ -201,7 +287,8 @@ namespace SharpbinV3.Server.Controllers
return Forbid(); return Forbid();
bool result = await _pasteService.Delete(paste); bool result = await _pasteService.Delete(paste);
if (!result) return NotFound(); if (!result)
return NotFound();
return Ok(new { message = "Paste deleted successfully." }); return Ok(new { message = "Paste deleted successfully." });
} }
@@ -210,7 +297,8 @@ 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(results.Select(p => new return Ok(
results.Select(p => new
{ {
p.ID, p.ID,
p.UUID, p.UUID,
@@ -222,8 +310,9 @@ namespace SharpbinV3.Server.Controllers
p.Syntax, p.Syntax,
p.Visibility, p.Visibility,
p.ExpiresAt, p.ExpiresAt,
p.EditedAt p.EditedAt,
})); })
);
} }
[HttpGet] [HttpGet]
@@ -237,11 +326,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);
} }
+55 -23
View File
@@ -16,7 +16,13 @@ namespace SharpbinV3.Server.Controllers
{ {
[ApiController] [ApiController]
[Route("api/[controller]")] [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 UserService _userService = userService;
private readonly AppDbContext _db = db; private readonly AppDbContext _db = db;
@@ -52,12 +58,16 @@ namespace SharpbinV3.Server.Controllers
[HttpPatch("uuid/{uuid}")] [HttpPatch("uuid/{uuid}")]
[Authorize] [Authorize]
public async Task<IActionResult> UpdateByUUID(Guid uuid, [FromBody] UpdateUserDto updatedUser) public async Task<IActionResult> UpdateByUUID(
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) return Forbid(); if (jwtUser == null)
return Forbid();
var user = await _userService.GetByUUID(uuid); var user = await _userService.GetByUUID(uuid);
if (user == null) if (user == null)
return NotFound(); return NotFound();
@@ -65,7 +75,11 @@ 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 (jwtUser.Roles.Contains(255) && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA) if (
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;
@@ -78,11 +92,16 @@ namespace SharpbinV3.Server.Controllers
{ {
if (updatedUser.Roles.Contains(255) && jwtUser.TotpEnabled) if (updatedUser.Roles.Contains(255) && jwtUser.TotpEnabled)
{ {
if (string.IsNullOrEmpty(updatedUser.TotpCode) || !await _totp.VerifyAsync(new VerificationContext if (
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." });
} }
@@ -99,32 +118,44 @@ 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) return Forbid(); if (jwtUser == null)
return Forbid();
var user = await _userService.GetByUUID(uuid); 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) if (!jwtUser.Roles.Any(r => r == 255) && user.UUID != jwtUser.UUID)
return Forbid(); 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(); return Forbid();
if (jwtUser.TotpEnabled) if (jwtUser.TotpEnabled)
{ {
if (string.IsNullOrEmpty(dto.TotpCode) || !await _totp.VerifyAsync(new VerificationContext if (
{ string.IsNullOrEmpty(dto.TotpCode)
UserUUID = jwtUser.UUID, || !await _totp.VerifyAsync(
Code = dto.TotpCode new VerificationContext { UserUUID = jwtUser.UUID, Code = dto.TotpCode }
})) )
)
{ {
return Unauthorized(new { message = "Invalid TOTP code." }); return Unauthorized(new { message = "Invalid TOTP code." });
} }
} }
else else
{ {
if (string.IsNullOrEmpty(dto.Token) || !await _verificationService.VerifyAsync(new VerificationContext if (
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." });
} }
@@ -137,7 +168,8 @@ 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 = 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); var pasteQuery = _db.Pastes.AsNoTracking().Where(p => p.AuthorUUID == user.UUID);
if (!isAuthenticatedUser) if (!isAuthenticatedUser)
{ {
@@ -170,7 +202,7 @@ namespace SharpbinV3.Server.Controllers
p.Views, p.Views,
p.Visibility, p.Visibility,
p.EditedAt, p.EditedAt,
p.ExpiresAt p.ExpiresAt,
}) })
.ToListAsync(); .ToListAsync();
@@ -179,7 +211,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)
@@ -195,7 +227,7 @@ namespace SharpbinV3.Server.Controllers
user.Roles, user.Roles,
user.Visibility, user.Visibility,
Pastes = pastes, Pastes = pastes,
Pagination = pagination Pagination = pagination,
}; };
} }
@@ -207,7 +239,7 @@ namespace SharpbinV3.Server.Controllers
user.DisplayName, user.DisplayName,
user.Roles, user.Roles,
Pastes = pastes, Pastes = pastes,
Pagination = pagination Pagination = pagination,
}; };
} }
} }
@@ -6,6 +6,7 @@ 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,6 +6,7 @@ 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,6 +7,7 @@ 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; }
+25 -4
View File
@@ -22,16 +22,36 @@ namespace SharpbinV3.Server.DTOs
{ {
var results = new List<ValidationResult>(); var results = new List<ValidationResult>();
if (!ValidateUsername().IsMatch(Username)) if (!ValidateUsername().IsMatch(Username))
results.Add(new ValidationResult("Username can only contain letters, numbers, underscores, and dots.", [nameof(Username)])); results.Add(
new ValidationResult(
"Username can only contain letters, numbers, underscores, and dots.",
[nameof(Username)]
)
);
if (!ValidatePassword().IsMatch(Password)) if (!ValidatePassword().IsMatch(Password))
results.Add(new ValidationResult("Password should have at least 8 characters, including uppercase, lowercase, and digits.", [nameof(Password)])); results.Add(
new ValidationResult(
"Password should have at least 8 characters, including uppercase, lowercase, and digits.",
[nameof(Password)]
)
);
if (DisplayName != null) if (DisplayName != null)
{ {
if (DisplayName.Length < 3 || DisplayName.Length > 26) if (DisplayName.Length < 3 || DisplayName.Length > 26)
results.Add(new ValidationResult("DisplayName must be between 3 and 26 characters.", [nameof(DisplayName)])); results.Add(
new ValidationResult(
"DisplayName must be between 3 and 26 characters.",
[nameof(DisplayName)]
)
);
if (!ValidateUsername().IsMatch(DisplayName)) if (!ValidateUsername().IsMatch(DisplayName))
results.Add(new ValidationResult("DisplayName can only contain letters, numbers, underscores, and dots.", [nameof(DisplayName)])); results.Add(
new ValidationResult(
"DisplayName can only contain letters, numbers, underscores, and dots.",
[nameof(DisplayName)]
)
);
} }
if (Email != null) if (Email != null)
{ {
@@ -44,6 +64,7 @@ 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();
} }
+24 -6
View File
@@ -17,9 +17,19 @@ 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(new ValidationResult("DisplayName must be between 3 and 26 characters.", [nameof(DisplayName)])); results.Add(
new ValidationResult(
"DisplayName must be between 3 and 26 characters.",
[nameof(DisplayName)]
)
);
if (!ValidateDisplayname().IsMatch(DisplayName)) if (!ValidateDisplayname().IsMatch(DisplayName))
results.Add(new ValidationResult("DisplayName can only contain letters, numbers, underscores, and dots.", [nameof(DisplayName)])); results.Add(
new ValidationResult(
"DisplayName can only contain letters, numbers, underscores, and dots.",
[nameof(DisplayName)]
)
);
} }
if (Email != null) if (Email != null)
{ {
@@ -30,19 +40,27 @@ namespace SharpbinV3.Server.DTOs
if (Visibility != null) if (Visibility != null)
{ {
if (Visibility < 0 || Visibility > 2) if (Visibility < 0 || Visibility > 2)
results.Add(new ValidationResult("Visibility must be between 0 and 2.", [nameof(Visibility)])); results.Add(
new ValidationResult(
"Visibility must be between 0 and 2.",
[nameof(Visibility)]
)
);
} }
if (Roles != null) if (Roles != null)
{ {
if (Roles.Length == 0) if (Roles.Length == 0)
results.Add(new ValidationResult("Roles cannot be an empty array.", [nameof(Roles)])); results.Add(
new ValidationResult("Roles cannot be an empty array.", [nameof(Roles)])
);
int[] validRoles = [0, 1, 255, 403]; 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(new ValidationResult($"Invalid role: {role}.", [nameof(Roles)])); results.Add(
new ValidationResult($"Invalid role: {role}.", [nameof(Roles)])
);
} }
} }
return results; return results;
} }
@@ -1,20 +1,21 @@
using SharpbinV3.Server.Services; using System.IdentityModel.Tokens.Jwt;
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 readonly static string[] ipHeaders = public static readonly 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)
@@ -36,7 +37,8 @@ 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 = expClaim != null && long.TryParse(expClaim, out var expUnix) var expires =
expClaim != null && long.TryParse(expClaim, out var expUnix)
? DateTimeOffset.FromUnixTimeSeconds(expUnix).UtcDateTime ? DateTimeOffset.FromUnixTimeSeconds(expUnix).UtcDateTime
: DateTime.UtcNow.AddMinutes(15); : DateTime.UtcNow.AddMinutes(15);
@@ -47,7 +49,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,
}; };
} }
@@ -55,7 +57,12 @@ namespace SharpbinV3.Server.Extensions
{ {
foreach (var header in ipHeaders) foreach (var header in ipHeaders)
{ {
if (context.Request.Headers.TryGetValue(header, out Microsoft.Extensions.Primitives.StringValues value)) if (
context.Request.Headers.TryGetValue(
header,
out Microsoft.Extensions.Primitives.StringValues value
)
)
{ {
var ip = value.FirstOrDefault(); var ip = value.FirstOrDefault();
if (!string.IsNullOrEmpty(ip)) if (!string.IsNullOrEmpty(ip))
@@ -14,7 +14,8 @@ namespace SharpbinV3.Server.Migrations
name: "Users", name: "Users",
columns: table => new columns: table => new
{ {
UID = table.Column<int>(type: "INTEGER", nullable: false) UID = table
.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),
@@ -23,18 +24,20 @@ 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.Column<int>(type: "INTEGER", nullable: false) PID = table
.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),
@@ -48,7 +51,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 =>
{ {
@@ -57,8 +60,10 @@ 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",
@@ -70,7 +75,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 =>
{ {
@@ -79,81 +84,87 @@ 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( migrationBuilder.CreateIndex(name: "IX_Pastes_Views", table: "Pastes", column: "Views");
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( migrationBuilder.DropTable(name: "Pastes");
name: "Pastes");
migrationBuilder.DropTable( migrationBuilder.DropTable(name: "RefreshTokens");
name: "RefreshTokens");
migrationBuilder.DropTable( migrationBuilder.DropTable(name: "Users");
name: "Users");
} }
} }
} }
@@ -10,42 +10,39 @@ namespace SharpbinV3.Server.Migrations
/// <inheritdoc /> /// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder) protected override void Up(MigrationBuilder migrationBuilder)
{ {
migrationBuilder.DropColumn( migrationBuilder.DropColumn(name: "FilePath", table: "Pastes");
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( migrationBuilder.DropColumn(name: "Data", table: "Pastes");
name: "Data",
table: "Pastes");
migrationBuilder.DropColumn( migrationBuilder.DropColumn(name: "IsCompressed", table: "Pastes");
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,19 +10,13 @@ namespace SharpbinV3.Server.Migrations
/// <inheritdoc /> /// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder) protected override void Up(MigrationBuilder migrationBuilder)
{ {
migrationBuilder.RenameColumn( migrationBuilder.RenameColumn(name: "Data", table: "Pastes", newName: "Content");
name: "Data",
table: "Pastes",
newName: "Content");
} }
/// <inheritdoc /> /// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder) protected override void Down(MigrationBuilder migrationBuilder)
{ {
migrationBuilder.RenameColumn( migrationBuilder.RenameColumn(name: "Content", table: "Pastes", newName: "Data");
name: "Content",
table: "Pastes",
newName: "Data");
} }
} }
} }
@@ -13,12 +13,14 @@ 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 />
@@ -27,12 +29,14 @@ 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,29 +10,22 @@ namespace SharpbinV3.Server.Migrations
/// <inheritdoc /> /// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder) protected override void Up(MigrationBuilder migrationBuilder)
{ {
migrationBuilder.DropIndex( migrationBuilder.DropIndex(name: "IX_Users_UID", table: "Users");
name: "IX_Users_UID",
table: "Users");
migrationBuilder.RenameColumn( migrationBuilder.RenameColumn(name: "Visiblity", table: "Users", newName: "Visibility");
name: "Visiblity",
table: "Users",
newName: "Visibility");
} }
/// <inheritdoc /> /// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder) protected override void Down(MigrationBuilder migrationBuilder)
{ {
migrationBuilder.RenameColumn( migrationBuilder.RenameColumn(name: "Visibility", table: "Users", newName: "Visiblity");
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,15 +8,9 @@ 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,47 +10,35 @@ namespace SharpbinV3.Server.Migrations
/// <inheritdoc /> /// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder) protected override void Up(MigrationBuilder migrationBuilder)
{ {
migrationBuilder.DropForeignKey( migrationBuilder.DropForeignKey(name: "FK_Pastes_Users_UserUID", table: "Pastes");
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( migrationBuilder.DropPrimaryKey(name: "PK_Users", table: "Users");
name: "PK_Users",
table: "Users");
migrationBuilder.DropIndex( migrationBuilder.DropIndex(name: "IX_RefreshTokens_UserUID", table: "RefreshTokens");
name: "IX_RefreshTokens_UserUID",
table: "RefreshTokens");
migrationBuilder.DropIndex( migrationBuilder.DropIndex(name: "IX_Pastes_UserUID", table: "Pastes");
name: "IX_Pastes_UserUID",
table: "Pastes");
migrationBuilder.DropColumn( migrationBuilder.DropColumn(name: "UserUID", table: "RefreshTokens");
name: "UserUID",
table: "RefreshTokens");
migrationBuilder.DropColumn( migrationBuilder.DropColumn(name: "UserUID", table: "Pastes");
name: "UserUID",
table: "Pastes");
migrationBuilder.AlterColumn<int>( migrationBuilder
.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( migrationBuilder.AddPrimaryKey(name: "PK_Users", table: "Users", column: "UUID");
name: "PK_Users",
table: "Users",
column: "UUID");
migrationBuilder.AddForeignKey( migrationBuilder.AddForeignKey(
name: "FK_Pastes_Users_AuthorUUID", name: "FK_Pastes_Users_AuthorUUID",
@@ -58,7 +46,8 @@ 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",
@@ -66,73 +55,76 @@ 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( migrationBuilder.DropForeignKey(name: "FK_Pastes_Users_AuthorUUID", table: "Pastes");
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( migrationBuilder.DropPrimaryKey(name: "PK_Users", table: "Users");
name: "PK_Users",
table: "Users");
migrationBuilder.AlterColumn<int>( migrationBuilder
.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( migrationBuilder.AddPrimaryKey(name: "PK_Users", table: "Users", column: "UID");
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,7 +10,8 @@ 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
@@ -20,15 +21,19 @@ 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,15 +14,14 @@ 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( migrationBuilder.DropIndex(name: "IX_Users_UID", table: "Users");
name: "IX_Users_UID",
table: "Users");
} }
} }
} }
@@ -10,9 +10,7 @@ namespace SharpbinV3.Server.Migrations
/// <inheritdoc /> /// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder) protected override void Up(MigrationBuilder migrationBuilder)
{ {
migrationBuilder.DropIndex( migrationBuilder.DropIndex(name: "IX_Users_UID", table: "Users");
name: "IX_Users_UID",
table: "Users");
migrationBuilder.AlterColumn<int>( migrationBuilder.AlterColumn<int>(
name: "UID", name: "UID",
@@ -20,20 +18,16 @@ namespace SharpbinV3.Server.Migrations
type: "INTEGER", type: "INTEGER",
nullable: true, nullable: true,
oldClrType: typeof(int), oldClrType: typeof(int),
oldType: "INTEGER"); oldType: "INTEGER"
);
migrationBuilder.CreateIndex( migrationBuilder.CreateIndex(name: "IX_Users_UID", table: "Users", column: "UID");
name: "IX_Users_UID",
table: "Users",
column: "UID");
} }
/// <inheritdoc /> /// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder) protected override void Down(MigrationBuilder migrationBuilder)
{ {
migrationBuilder.DropIndex( migrationBuilder.DropIndex(name: "IX_Users_UID", table: "Users");
name: "IX_Users_UID",
table: "Users");
migrationBuilder.AlterColumn<int>( migrationBuilder.AlterColumn<int>(
name: "UID", name: "UID",
@@ -43,13 +37,15 @@ 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,7 +16,8 @@ namespace SharpbinV3.Server.Migrations
type: "TEXT", type: "TEXT",
nullable: true, nullable: true,
oldClrType: typeof(Guid), oldClrType: typeof(Guid),
oldType: "TEXT"); oldType: "TEXT"
);
} }
/// <inheritdoc /> /// <inheritdoc />
@@ -30,7 +31,8 @@ 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,15 +26,16 @@ 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( migrationBuilder.DropTable(name: "UserTotps");
name: "UserTotps");
} }
} }
} }
+41 -25
View File
@@ -1,3 +1,5 @@
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;
@@ -10,8 +12,6 @@ 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,11 +40,10 @@ namespace SharpbinV3.Server
builder.Services.AddHttpClient<IVerificationProvider, TurnstileVerificationProvider>(); builder.Services.AddHttpClient<IVerificationProvider, TurnstileVerificationProvider>();
builder.Services.AddMemoryCache(); builder.Services.AddMemoryCache();
builder.Services.AddHealthChecks() builder.Services.AddHealthChecks().AddDbContextCheck<AppDbContext>("Database");
.AddDbContextCheck<AppDbContext>("Database");
builder.Services builder
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(jwt => .AddJwtBearer(jwt =>
{ {
var jwtSettings = builder.Configuration.GetSection("JwtSettings"); var jwtSettings = builder.Configuration.GetSection("JwtSettings");
@@ -67,44 +66,58 @@ namespace SharpbinV3.Server
ClockSkew = TimeSpan.Zero, ClockSkew = TimeSpan.Zero,
RequireSignedTokens = true, RequireSignedTokens = true,
ValidAlgorithms = [SecurityAlgorithms.HmacSha256] ValidAlgorithms = [SecurityAlgorithms.HmacSha256],
}; };
}); });
builder.Services.AddAuthorizationBuilder() builder
.AddPolicy("NotBanned", policy => .Services.AddAuthorizationBuilder()
policy.Requirements.Add(new NotBannedRequirement())); .AddPolicy(
builder.Services.AddAuthorizationBuilder() "NotBanned",
.AddPolicy("AuthAndNotBanned", policy => policy => policy.Requirements.Add(new NotBannedRequirement())
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("Sliding", opt => options.AddSlidingWindowLimiter(
"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") p.WithOrigins("http://localhost:5173").AllowAnyHeader().AllowAnyMethod()
.AllowAnyHeader() );
.AllowAnyMethod());
}); });
builder.Services.Configure<PasteSettings>(builder.Configuration.GetSection("PasteSettings")); builder.Services.Configure<PasteSettings>(
builder.Services.Configure<JWTSettings>(builder.Configuration.GetSection("JWTSettings")); builder.Configuration.GetSection("PasteSettings")
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.Services.AddDataProtection() builder
.Services.AddDataProtection()
.PersistKeysToFileSystem(GetDataProtectionKeyDirectory(builder.Environment)) .PersistKeysToFileSystem(GetDataProtectionKeyDirectory(builder.Environment))
.SetApplicationName("SharpbinV3"); .SetApplicationName("SharpbinV3");
@@ -130,7 +143,8 @@ 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
@@ -140,13 +154,15 @@ 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");
+56 -23
View File
@@ -1,13 +1,13 @@
using Microsoft.EntityFrameworkCore; using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options; using Microsoft.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,13 +21,23 @@ 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(string username, string password, string? email, string? displayName) public async Task<User> CreateUser(
string username,
string password,
string? email,
string? displayName
)
{ {
var user = new User var user = new User
{ {
@@ -35,7 +45,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())
@@ -45,6 +55,7 @@ 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();
@@ -57,7 +68,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)
@@ -79,20 +90,24 @@ 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 => rt.UserUUID == user.UUID); var existingToken = await _db.RefreshTokens.FirstOrDefaultAsync(rt =>
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.UtcNow.AddMonths(6).ToUnixTimeMilliseconds(); existingToken.ExpiresAt = DateTimeOffset
.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);
} }
@@ -106,7 +121,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);
} }
@@ -117,7 +132,9 @@ namespace SharpbinV3.Server.Services
{ {
Token = jwtToken, Token = jwtToken,
Success = true, Success = true,
RefreshToken = existingToken?.Token ?? (await _db.RefreshTokens.FirstAsync(rt => rt.UserUUID == user.UUID)).Token RefreshToken =
existingToken?.Token
?? (await _db.RefreshTokens.FirstAsync(rt => rt.UserUUID == user.UUID)).Token,
}; };
} }
@@ -127,7 +144,9 @@ namespace SharpbinV3.Server.Services
var key = Encoding.UTF8.GetBytes(_jwtSettings.Secret); var key = Encoding.UTF8.GetBytes(_jwtSettings.Secret);
try try
{ {
var principal = jwtHandler.ValidateToken(token, new TokenValidationParameters var principal = jwtHandler.ValidateToken(
token,
new TokenValidationParameters
{ {
ValidateIssuerSigningKey = true, ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key), IssuerSigningKey = new SymmetricSecurityKey(key),
@@ -138,17 +157,26 @@ 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 var storedRefreshToken = await _db.RefreshTokens.FirstOrDefaultAsync(rt =>
.FirstOrDefaultAsync(rt => rt.Token == refreshToken); 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() { Success = false, Errors = ["Invalid refresh token, possibly already used or expired."] }; return new CreateJWT()
{
Success = false,
Errors = ["Invalid refresh token, possibly already used or expired."],
};
} }
storedRefreshToken.Used = true; storedRefreshToken.Used = true;
await _db.SaveChangesAsync(); await _db.SaveChangesAsync();
@@ -167,7 +195,9 @@ namespace SharpbinV3.Server.Services
public async Task<User> UpdateUser(User user) public async Task<User> UpdateUser(User user)
{ {
var existingUser = await _db.Users.FirstOrDefaultAsync(u => u.UUID == user.UUID) ?? throw new Exception("User not found"); var existingUser =
await _db.Users.FirstOrDefaultAsync(u => u.UUID == user.UUID)
?? throw new Exception("User not found");
existingUser.Username = user.Username; existingUser.Username = user.Username;
existingUser.Email = user.Email; existingUser.Email = user.Email;
existingUser.DisplayName = user.DisplayName; existingUser.DisplayName = user.DisplayName;
@@ -178,9 +208,12 @@ 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 = await _db.Users.FirstOrDefaultAsync(u => u.UUID == user.UUID) ?? throw new Exception("User not found"); var existingUser =
await _db.Users.FirstOrDefaultAsync(u => u.UUID == user.UUID)
?? throw new Exception("User not found");
existingUser.LastLogin = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); existingUser.LastLogin = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
_db.Users.Update(existingUser); _db.Users.Update(existingUser);
await _db.SaveChangesAsync(); await _db.SaveChangesAsync();
@@ -1,6 +1,5 @@
using System.IO.Compression; using System.IO.Compression;
namespace SharpbinV3.Server.Services namespace SharpbinV3.Server.Services
{ {
public class CompressionService : ICompressionService public class CompressionService : ICompressionService
@@ -21,16 +20,21 @@ 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("Data is not in a valid compressed format.", nameof(compressedData)); throw new ArgumentException(
"Data is not in a valid compressed format.",
nameof(compressedData)
);
using (MemoryStream ms = new()) using (MemoryStream ms = new())
{ {
@@ -3,14 +3,21 @@ using SharpbinV3.Server.Data;
namespace SharpbinV3.Server.Services namespace SharpbinV3.Server.Services
{ {
public class PasteCleanUpService(IServiceProvider serviceProvider, ILogger<PasteCleanUpService> logger) : BackgroundService public class PasteCleanUpService(
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 (!stoppingToken.IsCancellationRequested && await timer.WaitForNextTickAsync(stoppingToken)) while (
!stoppingToken.IsCancellationRequested
&& await timer.WaitForNextTickAsync(stoppingToken)
)
{ {
try try
{ {
@@ -36,7 +43,6 @@ 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);
} }
} }
} }
} }
+28 -10
View File
@@ -1,19 +1,31 @@
using Microsoft.EntityFrameworkCore; using System.Text;
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(AppDbContext db, ICompressionService cs, IOptions<PasteSettings> options) public sealed class PasteService(
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(User? author, string content, string title, string syntax, int visibility, long expiresAt, bool shouldCompress) public async Task<Paste> Create(
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)
@@ -50,20 +62,24 @@ 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);
@@ -79,39 +95,41 @@ 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 return await query.OrderByDescending(p => p.PID).Skip(offset).Take(count).ToListAsync();
.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) return true; if (expiresAt == 0)
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,7 +12,11 @@ namespace SharpbinV3.Server.Services.Verification.Providers
private readonly IDataProtector _protector; private readonly IDataProtector _protector;
private readonly IMemoryCache _cache; private readonly IMemoryCache _cache;
public TotpVerificationProvider(AppDbContext db, IDataProtectionProvider dataProtectionProvider, IMemoryCache cache) public TotpVerificationProvider(
AppDbContext db,
IDataProtectionProvider dataProtectionProvider,
IMemoryCache cache
)
{ {
_db = db; _db = db;
_protector = dataProtectionProvider.CreateProtector("TotpSecret-v1"); _protector = dataProtectionProvider.CreateProtector("TotpSecret-v1");
@@ -24,11 +28,16 @@ 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) return false; if (ctx.UserUUID is null)
if (string.IsNullOrWhiteSpace(ctx.Code)) return false; return false;
if (string.IsNullOrWhiteSpace(ctx.Code))
return false;
var userTotp = await _db.UserTotps.FirstOrDefaultAsync(t => t.UserUUID == ctx.UserUUID.Value); var userTotp = await _db.UserTotps.FirstOrDefaultAsync(t =>
if (userTotp is null) return false; t.UserUUID == ctx.UserUUID.Value
);
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))
@@ -44,30 +53,58 @@ 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) => string.IsNullOrWhiteSpace(base32) ? [] : Base32Encoding.ToBytes(base32); public byte[] FromBase32(string base32) =>
string.IsNullOrWhiteSpace(base32) ? [] : Base32Encoding.ToBytes(base32);
public string BuildOtpAuthUri(string issuer, string accountName, string secretBase32, int digits = 6, int period = 30, string algorithm = "SHA1") public string BuildOtpAuthUri(
string issuer,
string accountName,
string secretBase32,
int digits = 6,
int period = 30,
string algorithm = "SHA1"
)
{ {
var label = Uri.EscapeDataString($"{issuer}:{accountName}"); var label = Uri.EscapeDataString($"{issuer}:{accountName}");
var query = $"secret={secretBase32}&issuer={Uri.EscapeDataString(issuer)}&algorithm={algorithm}&digits={digits}&period={period}"; var query =
$"secret={secretBase32}&issuer={Uri.EscapeDataString(issuer)}&algorithm={algorithm}&digits={digits}&period={period}";
return $"otpauth://totp/{label}?{query}"; 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(string secretBase32, string code, int digits = 6, int period = 30, int window = 1) public bool VerifyWithSecretBase32(
string secretBase32,
string code,
int digits = 6,
int period = 30,
int window = 1
)
{ {
var secret = FromBase32(secretBase32); var secret = FromBase32(secretBase32);
return VerifyCode(secret, code, out _, digits, period, window); return VerifyCode(secret, code, out _, digits, period, window);
} }
private bool VerifyCode(byte[] secret, string code, out long matchedStep, int digits = 6, int period = 30, int window = 1) private bool VerifyCode(
byte[] secret,
string code,
out long matchedStep,
int digits = 6,
int period = 30,
int window = 1
)
{ {
var totp = new Totp(secret, step: period, mode: OtpHashMode.Sha1, totpSize: digits); var totp = new Totp(secret, step: period, mode: OtpHashMode.Sha1, totpSize: digits);
return totp.VerifyTotp(code, out matchedStep, new VerificationWindow(previous: window, future: window)); return totp.VerifyTotp(
code,
out matchedStep,
new VerificationWindow(previous: window, future: window)
);
} }
private string ComputeCode(byte[] key, long timestep, int digits) => new Totp(key, totpSize: digits).ComputeTotp(DateTime.UtcNow); private string ComputeCode(byte[] key, long timestep, int digits) =>
new Totp(key, totpSize: digits).ComputeTotp(DateTime.UtcNow);
} }
} }
@@ -1,17 +1,23 @@
using Microsoft.Extensions.Options; using System.Text.Json;
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(IOptions<AuthSettings> options, HttpClient httpClient) : IVerificationProvider public sealed class TurnstileVerificationProvider(
IOptions<AuthSettings> options,
HttpClient httpClient
) : IVerificationProvider
{ {
private readonly AuthSettings _authSettings = options.Value; private readonly AuthSettings _authSettings = options.Value;
private const string SiteverifyUrl = "https://challenges.cloudflare.com/turnstile/v0/siteverify"; private const string SiteverifyUrl =
"https://challenges.cloudflare.com/turnstile/v0/siteverify";
public int Priority => 1; public int Priority => 1;
public bool IsConfigured => !string.IsNullOrEmpty(_authSettings.CF_Turnstile_SecretKey) && !string.IsNullOrEmpty(_authSettings.CF_Turnstile_SiteKey); public bool IsConfigured =>
!string.IsNullOrEmpty(_authSettings.CF_Turnstile_SecretKey)
&& !string.IsNullOrEmpty(_authSettings.CF_Turnstile_SiteKey);
public async Task<bool> VerifyAsync(VerificationContext ctx) public async Task<bool> VerifyAsync(VerificationContext ctx)
{ {
@@ -23,7 +29,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,5 +8,4 @@
public Guid? UserUUID { get; init; } public Guid? UserUUID { get; init; }
public string? Code { get; init; } public string? Code { get; init; }
} }
} }
@@ -14,7 +14,10 @@ namespace SharpbinV3.Server.Services.Verification
.FirstOrDefault(); .FirstOrDefault();
} }
public async Task<bool> VerifyAsync(VerificationContext context, IVerificationProvider? provider = null) public async Task<bool> VerifyAsync(
VerificationContext context,
IVerificationProvider? provider = null
)
{ {
var activeProvider = provider ?? GetActiveProvider(); var activeProvider = provider ?? GetActiveProvider();
+8 -4
View File
@@ -1,5 +1,4 @@
<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>
@@ -25,10 +24,15 @@
<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 Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" Version="10.0.1" /> <PackageReference
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.23.0" /> Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore"
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>
+3 -1
View File
@@ -6,7 +6,9 @@
{ {
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var random = new Random(); var random = new Random();
return new string([.. Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)])]); return new string([
.. Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)]),
]);
} }
} }
} }