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