mirror of
https://github.com/whoswhip/Sharpbin.git
synced 2026-12-06 02:48:43 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
012690f507
|
||
|
|
5017e73bb5
|
||
|
|
809b513e7a
|
||
|
|
3374eadb56
|
||
|
|
7d09870ad2
|
||
|
|
fd1cb3998c
|
||
|
|
3dc8070efe
|
||
|
|
78f4ae181e
|
||
|
|
ee45deb439
|
||
|
|
3b2801a655
|
||
|
|
cac34423d9
|
||
|
|
5052bbdb13
|
||
|
|
0283d987d0
|
||
|
|
ff706d8777
|
||
|
|
53d0f33ff0
|
||
|
|
db363f0211
|
@@ -1,3 +1,28 @@
|
||||
## [3.0.4](https://github.com/whoswhip/Sharpbin/compare/v3.0.3...v3.0.4) (2026-02-14)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **backend:** use GenerateSecureRandomString for api-keys, paste ids, and refresh tokens ([5017e73](https://github.com/whoswhip/Sharpbin/commit/5017e73bb54e626d4dc060fd553c972663eec45f))
|
||||
* **frontend:api-keys:** add flag to track successful API key fetch ([78f4ae1](https://github.com/whoswhip/Sharpbin/commit/78f4ae181eb18a98ed9964d8e651d84319fa8d2c))
|
||||
* **frontend:user:** resolve lint errors ([7d09870](https://github.com/whoswhip/Sharpbin/commit/7d09870ad25472ff17a1acc22d5724e199f2c931))
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add dotnet-ef tool configuration to dotnet-tools.json ([db363f0](https://github.com/whoswhip/Sharpbin/commit/db363f0211972a06b622770ca522d3ef0bba12c8))
|
||||
* **backend:authentication:** implement API key authentication scheme and update authorization policies ([3374ead](https://github.com/whoswhip/Sharpbin/commit/3374eadb5654fa349a636c4a41a53df1ddf2edfe))
|
||||
* **backend:utilities:** implement GenerateSecureRandomString function that uses RandomNumberGenerator ([809b513](https://github.com/whoswhip/Sharpbin/commit/809b513e7a3f5a4f7faf64b02d9ed83e81c540b8))
|
||||
* **backend:** implement api keys; rename token -> verificationToken in paste creation api ([53d0f33](https://github.com/whoswhip/Sharpbin/commit/53d0f33ff026d6e5a188d80585e6a3bb633d9fa8))
|
||||
* **frontend:api-keys:** display the count of API keys in the header and adjust empty state condition ([3dc8070](https://github.com/whoswhip/Sharpbin/commit/3dc8070efeb19538c4ff120d2a681c4167c716f3))
|
||||
* **frontend:api-keys:** implement API key management features including creation, deletion, and fetching ([ee45deb](https://github.com/whoswhip/Sharpbin/commit/ee45deb43937cbf3996c3c379461110a484bd086))
|
||||
* **frontend:modal:** decrease modal background opacity and blur ([3b2801a](https://github.com/whoswhip/Sharpbin/commit/3b2801a65509d3a894c701f03028b2cd4599b456))
|
||||
* **frontend:stats:** enhance tooltip for total storage used to show uncompressed size ([cac3442](https://github.com/whoswhip/Sharpbin/commit/cac34423d99d1228f426be903da53bafca5f50e7))
|
||||
* **frontend:user:** improve UX; move user settings to settings tab ([5052bbd](https://github.com/whoswhip/Sharpbin/commit/5052bbdb135dc2df08db94874de5bf2bf738364c))
|
||||
* **frontend:** improve user page UX ([ff706d8](https://github.com/whoswhip/Sharpbin/commit/ff706d877742317cb8f4ccf72ba5f0791a6d2b88))
|
||||
|
||||
|
||||
|
||||
## [3.0.3](https://github.com/whoswhip/Sharpbin/compare/v3.0.2...v3.0.3) (2026-02-10)
|
||||
|
||||
|
||||
|
||||
@@ -50,16 +50,16 @@ You can configure Sharpbin using environment variables or `appsettings.json`. Wh
|
||||
- `JwtSettings__Secret`: A secure string used for signing JWT tokens.
|
||||
- `AuthSettings__CF_Turnstile_SecretKey`: Your Cloudflare Turnstile secret key.
|
||||
- `AuthSettings__CF_Turnstile_SiteKey`: Your Cloudflare Turnstile site key.
|
||||
- `AuthSettings__Registration_Enabled`: Set to `true` by default, enables/disables registration.
|
||||
- `AuthSettings__Registration_Enabled`:**true**: Enables/disables registration.
|
||||
- `AuthSettings__First_User_Admin`: Gives the first user the admin role, it is recommended to disable this after use.
|
||||
- `AuthSettings__Admins_Require_2FA`: Enforces Admins to have 2FA when trying to do certain actions.
|
||||
- `AuthSettings__API_Key_HMAC_Secret`: Recommended to securely hash API keys, but is not required.
|
||||
- `PasteSettings__MaxTitleLength`: Max title length in characters.
|
||||
- `PasteSettings__MaxPasteSizeInBytes`: Max Paste Size set in bytes, the default is `1_048_576` (1MB)
|
||||
- `PasteSettings__EnablePasteCompression`: Enables/Disables server-side paste compression, `true` by default.
|
||||
- `PasteSettings__RequiresVerification`: Enables/Disables CAPTCHA verification when creating pastes, `true` by default.
|
||||
- `PasteSettings__MaxPasteSizeInBytes`:**1_048_576** (1MB): Max Paste Size set in bytes.
|
||||
- `PasteSettings__EnablePasteCompression`:**true**: Enables/Disables server-side paste compression.
|
||||
- `PasteSettings__RequiresVerification`:**true**: Enables/Disables CAPTCHA verification when creating pastes.
|
||||
- `PasteSettings__View_HMAC_Secret`: Required to securely hash viewer identifiers
|
||||
- `PasteSettings__View_Internal_API_Key`: Enforces views to be counted/recorded only by the frontend, if set it needs to be the same for both backend and frontend.
|
||||
- `ASPNETCORE_ENVIRONMENT`: Set to `Production` or `Development`.
|
||||
|
||||
#### Frontend (SharpbinV3.Client)
|
||||
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "sharpbinv3.client",
|
||||
"version": "3.0.3",
|
||||
"version": "3.0.4",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "sharpbinv3.client",
|
||||
"version": "3.0.3",
|
||||
"version": "3.0.4",
|
||||
"dependencies": {
|
||||
"@lucide/svelte": "^0.562.0",
|
||||
"@sveltejs/adapter-node": "^5.4.0",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "sharpbinv3.client",
|
||||
"private": true,
|
||||
"version": "3.0.3",
|
||||
"version": "3.0.4",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite dev",
|
||||
|
||||
@@ -402,10 +402,10 @@
|
||||
</script>
|
||||
|
||||
{#if show}
|
||||
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm">
|
||||
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/20 backdrop-blur-xs">
|
||||
<form
|
||||
on:submit|preventDefault={handleSubmit}
|
||||
class="w-full max-w-md rounded bg-neutral-900 p-6"
|
||||
class="w-full max-w-md rounded border border-neutral-800 bg-neutral-900 p-6"
|
||||
>
|
||||
<h2 class="mb-4 text-xl font-semibold text-white">
|
||||
{displayTitle}
|
||||
|
||||
@@ -132,9 +132,9 @@
|
||||
data.auth?.cf_turnstile_site_key &&
|
||||
window.turnstile
|
||||
) {
|
||||
const token = window.turnstile.getResponse();
|
||||
if (token) {
|
||||
params.append('token', token);
|
||||
const verificationToken = window.turnstile.getResponse();
|
||||
if (verificationToken) {
|
||||
params.append('verificationToken', verificationToken);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -74,7 +74,10 @@
|
||||
<p class="text-sm text-neutral-400">Total Storage Used</p>
|
||||
<p
|
||||
class="text-2xl font-bold"
|
||||
use:tooltip={[formatBytes(stats.pastes.trueTotalSizeInBytes), true]}
|
||||
use:tooltip={[
|
||||
`${stats.pastes.trueTotalSizeInBytes != stats.pastes.totalSizeInBytes ? `Uncompressed Size: ${formatBytes(stats.pastes.trueTotalSizeInBytes)}` : ''}`,
|
||||
true
|
||||
]}
|
||||
>
|
||||
{formatBytes(stats.pastes.totalSizeInBytes)}
|
||||
</p>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,50 @@
|
||||
using System.Security.Claims;
|
||||
using System.Text.Encodings.Web;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SharpbinV3.Server.Extensions;
|
||||
using SharpbinV3.Server.Services;
|
||||
|
||||
namespace SharpbinV3.Server.Authentication
|
||||
{
|
||||
public sealed class ApiKeyAuthenticationHandler(
|
||||
IOptionsMonitor<AuthenticationSchemeOptions> options,
|
||||
ILoggerFactory logger,
|
||||
UrlEncoder encoder,
|
||||
ApiKeyService apiKeyService
|
||||
) : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
|
||||
{
|
||||
private readonly ApiKeyService _apiKeyService = apiKeyService;
|
||||
|
||||
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
{
|
||||
var apiKeyString = Context.GetApiKey();
|
||||
if (string.IsNullOrEmpty(apiKeyString))
|
||||
return AuthenticateResult.NoResult();
|
||||
|
||||
var apiKey = await _apiKeyService.GetByKeyAsync(apiKeyString);
|
||||
if (apiKey == null || apiKey.User == null)
|
||||
return AuthenticateResult.Fail("Invalid API key.");
|
||||
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
new("uuid", apiKey.User.UUID.ToString()),
|
||||
new("username", apiKey.User.Username ?? ""),
|
||||
new("displayname", apiKey.User.DisplayName ?? ""),
|
||||
new("totp_enabled", (apiKey.User.Totp != null).ToString()),
|
||||
};
|
||||
|
||||
if (apiKey.User.Roles != null)
|
||||
claims.AddRange(apiKey.User.Roles.Select(r => new Claim(ClaimTypes.Role, r.ToString())));
|
||||
|
||||
var identity = new ClaimsIdentity(claims, AuthSchemes.ApiKey);
|
||||
var principal = new ClaimsPrincipal(identity);
|
||||
var ticket = new AuthenticationTicket(principal, AuthSchemes.ApiKey);
|
||||
|
||||
Context.SetApiKeyContext(apiKey);
|
||||
await _apiKeyService.UpdateLastUsedAsync(apiKey.UUID);
|
||||
|
||||
return AuthenticateResult.Success(ticket);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace SharpbinV3.Server.Authentication
|
||||
{
|
||||
public static class AuthSchemes
|
||||
{
|
||||
public const string Combined = "Combined";
|
||||
public const string ApiKey = "ApiKey";
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using SharpbinV3.Server.Extensions;
|
||||
|
||||
namespace SharpbinV3.Server.Authorization
|
||||
{
|
||||
@@ -9,13 +10,26 @@ namespace SharpbinV3.Server.Authorization
|
||||
|
||||
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, NotBannedRequirement requirement)
|
||||
{
|
||||
var httpContext = context.Resource as HttpContext;
|
||||
var isAuthenticated = context.User.Identity?.IsAuthenticated ?? false;
|
||||
|
||||
if (!isAuthenticated && httpContext != null)
|
||||
{
|
||||
var apiKey = httpContext.GetApiKeyFromContext();
|
||||
if (apiKey != null)
|
||||
{
|
||||
isAuthenticated = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (_requireAuth && !isAuthenticated)
|
||||
return Task.CompletedTask;
|
||||
|
||||
var isBanned = context.User.Claims.Any(c => (c.Type == ClaimTypes.Role || c.Type == "role") && c.Value == "403");
|
||||
|
||||
if (httpContext?.GetApiKeyFromContext()?.User?.Roles?.Contains(403) == true)
|
||||
isBanned = true;
|
||||
|
||||
if (!isBanned)
|
||||
context.Succeed(requirement);
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ using Microsoft.Extensions.Options;
|
||||
using SharpbinV3.Server.Data;
|
||||
using SharpbinV3.Server.Data.Entities;
|
||||
using SharpbinV3.Server.DTOs;
|
||||
using SharpbinV3.Server.DTOs.ApiKey;
|
||||
using SharpbinV3.Server.DTOs.Auth;
|
||||
using SharpbinV3.Server.DTOs.User;
|
||||
using SharpbinV3.Server.Extensions;
|
||||
@@ -22,6 +23,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
public class AuthController(
|
||||
UserService userService,
|
||||
AuthService authService,
|
||||
ApiKeyService apiKeyService,
|
||||
IOptions<AuthSettings> options,
|
||||
VerificationService verification,
|
||||
TotpVerificationProvider totp,
|
||||
@@ -30,6 +32,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
{
|
||||
private readonly AuthService _authService = authService;
|
||||
private readonly UserService _userService = userService;
|
||||
private readonly ApiKeyService _apiKeyService = apiKeyService;
|
||||
private readonly VerificationService _verification = verification;
|
||||
private readonly TotpVerificationProvider _totp = totp;
|
||||
private readonly AppDbContext _db = db;
|
||||
@@ -164,7 +167,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
[Authorize]
|
||||
[Authorize(Policy = "JwtOnly")]
|
||||
[Route("totp/enroll")]
|
||||
public async Task<IActionResult> StartTotpEnrollment()
|
||||
{
|
||||
@@ -187,16 +190,12 @@ namespace SharpbinV3.Server.Controllers
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Authorize]
|
||||
[Authorize(Policy = "JwtOnly")]
|
||||
[Route("totp/enable")]
|
||||
[EnableRateLimiting("Sensitive")]
|
||||
public async Task<IActionResult> EnableTotp([FromBody] EnableTotpDto request)
|
||||
{
|
||||
var uuidClaim = User.Claims.FirstOrDefault(c => c.Type == "UUID")?.Value;
|
||||
if (string.IsNullOrEmpty(uuidClaim))
|
||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
||||
|
||||
var uuid = Guid.Parse(uuidClaim);
|
||||
var uuid = Guid.Parse(User.FindFirst("uuid")!.Value);
|
||||
if (string.IsNullOrWhiteSpace(request.Secret) || string.IsNullOrWhiteSpace(request.Code))
|
||||
return BadRequest(new { success = false, message = "Secret and code are required." });
|
||||
|
||||
@@ -221,7 +220,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Authorize]
|
||||
[Authorize(Policy = "JwtOnly")]
|
||||
[Route("totp/disable")]
|
||||
public async Task<IActionResult> DisableTotp([FromBody] DisableTotpDto dto)
|
||||
{
|
||||
@@ -240,5 +239,88 @@ namespace SharpbinV3.Server.Controllers
|
||||
await _db.SaveChangesAsync();
|
||||
return Ok(new { success = true, message = "TOTP disabled." });
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Authorize(Policy = "JwtOnly")]
|
||||
[Route("apikey/create")]
|
||||
[EnableRateLimiting("Strict")]
|
||||
public async Task<IActionResult> CreateApiKey([FromBody] CreateApiKeyRequest request)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(request.Name))
|
||||
return BadRequest(new { success = false, message = "API key name is required." });
|
||||
if (request.Name.Length > 26)
|
||||
return BadRequest(new { success = false, message = "API key name must not exceed 26 characters." });
|
||||
|
||||
var user = await _authService.GetUserFromHttpContext(HttpContext);
|
||||
if (user == null)
|
||||
return BadRequest(new { success = false, message = "User not found." });
|
||||
|
||||
var existingKeys = await _apiKeyService.GetUserKeysAsync(user.UUID);
|
||||
if (existingKeys.Count >= 10)
|
||||
return BadRequest(new { success = false, message = "API key limit reached. Please delete existing keys before creating new ones." });
|
||||
|
||||
var (apiKey, key) = await _apiKeyService.CreateAsync(user.UUID, request.Name);
|
||||
|
||||
return Ok(
|
||||
new
|
||||
{
|
||||
success = true,
|
||||
message = "API key created. Save it now as you won't be able to see it again.",
|
||||
apiKey = new ApiKeyResponseDto
|
||||
{
|
||||
UUID = apiKey.UUID,
|
||||
Key = key,
|
||||
Name = apiKey.Name,
|
||||
CreatedAt = apiKey.CreatedAt,
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
[Authorize]
|
||||
[Route("apikey/list")]
|
||||
public async Task<IActionResult> ListApiKeys()
|
||||
{
|
||||
var user = await _authService.GetUserFromHttpContext(HttpContext);
|
||||
if (user == null)
|
||||
return BadRequest(new { success = false, message = "User not found." });
|
||||
|
||||
var apiKeys = await _apiKeyService.GetUserKeysAsync(user.UUID);
|
||||
return Ok(
|
||||
new
|
||||
{
|
||||
success = true,
|
||||
apiKeys = apiKeys
|
||||
.Select(k => new ApiKeyListItemDto
|
||||
{
|
||||
UUID = k.UUID,
|
||||
Name = k.Name,
|
||||
CreatedAt = k.CreatedAt,
|
||||
LastUsedAt = k.LastUsedAt,
|
||||
})
|
||||
.ToList(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
[HttpDelete]
|
||||
[Authorize(Policy = "JwtOnly")]
|
||||
[Route("apikey/{uuid}")]
|
||||
public async Task<IActionResult> DeleteApiKey(string uuid)
|
||||
{
|
||||
if (!Guid.TryParse(uuid, out var keyUUID))
|
||||
return BadRequest(new { success = false, message = "Invalid API key UUID." });
|
||||
|
||||
var user = await _authService.GetUserFromHttpContext(HttpContext);
|
||||
if (user == null)
|
||||
return BadRequest(new { success = false, message = "User not found." });
|
||||
|
||||
var deleted = await _apiKeyService.DeleteAsync(user.UUID, keyUUID);
|
||||
if (!deleted)
|
||||
return NotFound(new { success = false, message = "API key not found." });
|
||||
|
||||
return Ok(new { success = true, message = "API key deleted." });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
string syntax = "plaintext",
|
||||
int visibility = 0,
|
||||
long expiresAt = 0,
|
||||
string? token = null
|
||||
string? verificationToken = null
|
||||
)
|
||||
{
|
||||
if (!_pasteService.ValidateExpiresAt(expiresAt))
|
||||
@@ -60,11 +60,18 @@ namespace SharpbinV3.Server.Controllers
|
||||
new { success = false, message = $"Paste size exceeds the maximum allowed size of {_pasteSettings.MaxPasteSizeInBytes} bytes." }
|
||||
);
|
||||
|
||||
if (
|
||||
_pasteSettings.RequiresVerification
|
||||
&& !await _verificationService.VerifyAsync(new VerificationContext { Token = token, Ip = HttpContext.GetRequestIP() })
|
||||
)
|
||||
return BadRequest(new { success = false, message = "Verification failed." });
|
||||
if (_pasteSettings.RequiresVerification && !HttpContext.IsApiKeyAuthenticated())
|
||||
{
|
||||
var providedApiKey = HttpContext.GetApiKey();
|
||||
if (providedApiKey != null)
|
||||
return BadRequest(new { success = false, message = "Invalid API key." });
|
||||
|
||||
var verifyResult = await _verificationService.VerifyAsync(
|
||||
new VerificationContext { Token = verificationToken, Ip = HttpContext.GetRequestIP() }
|
||||
);
|
||||
if (!verifyResult)
|
||||
return BadRequest(new { success = false, message = "Verification failed." });
|
||||
}
|
||||
|
||||
var user = await _authService.GetUserFromHttpContext(HttpContext);
|
||||
Paste paste = await _pasteService.Create(user, content, title, syntax, visibility, expiresAt, _pasteSettings.EnablePasteCompression);
|
||||
@@ -149,7 +156,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
|
||||
[HttpPut]
|
||||
[Route("{id}")]
|
||||
[Authorize(Policy = "AuthAndNotBanned")]
|
||||
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||
public async Task<IActionResult> EditPaste(string id)
|
||||
{
|
||||
string content = await new StreamReader(Request.Body).ReadToEndAsync();
|
||||
@@ -160,9 +167,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
if (paste == null)
|
||||
return StatusCode(404, new { success = false, message = "Paste not found." });
|
||||
|
||||
var user = HttpContext.GetJwtUser();
|
||||
if (user == null)
|
||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
||||
var user = HttpContext.GetJwtUser()!;
|
||||
|
||||
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
|
||||
if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
|
||||
@@ -178,16 +183,14 @@ namespace SharpbinV3.Server.Controllers
|
||||
|
||||
[HttpPatch]
|
||||
[Route("{id}")]
|
||||
[Authorize(Policy = "AuthAndNotBanned")]
|
||||
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||
public async Task<IActionResult> ModifyPasteMetadata(string id, [FromBody] UpdatePasteDto request)
|
||||
{
|
||||
var paste = await _pasteService.Get(id);
|
||||
if (paste == null)
|
||||
return NotFound(new { success = false, message = "Paste not found." });
|
||||
|
||||
var user = HttpContext.GetJwtUser();
|
||||
if (user == null)
|
||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
||||
var user = HttpContext.GetJwtUser()!;
|
||||
|
||||
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
|
||||
|
||||
@@ -239,16 +242,14 @@ namespace SharpbinV3.Server.Controllers
|
||||
|
||||
[HttpDelete]
|
||||
[Route("{id}")]
|
||||
[Authorize(Policy = "AuthAndNotBanned")]
|
||||
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||
public async Task<IActionResult> DeletePaste(string id)
|
||||
{
|
||||
var paste = await _pasteService.Get(id);
|
||||
if (paste == null)
|
||||
return NotFound(new { success = false, message = "Paste not found." });
|
||||
|
||||
var user = HttpContext.GetJwtUser();
|
||||
if (user == null)
|
||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
||||
var user = HttpContext.GetJwtUser()!;
|
||||
|
||||
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
|
||||
if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
|
||||
@@ -291,16 +292,14 @@ namespace SharpbinV3.Server.Controllers
|
||||
|
||||
[HttpPost]
|
||||
[Route("{id}/report")]
|
||||
[Authorize(Policy = "AuthAndNotBanned")]
|
||||
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||
[EnableRateLimiting("Sensitive")]
|
||||
public async Task<IActionResult> ReportPaste(string id, [FromBody] ReportDto request)
|
||||
{
|
||||
var paste = await _pasteService.Get(id);
|
||||
if (paste == null)
|
||||
return NotFound(new { success = false, message = "Paste not found." });
|
||||
var user = HttpContext.GetJwtUser();
|
||||
if (user == null)
|
||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
||||
var user = HttpContext.GetJwtUser()!;
|
||||
|
||||
Enum.TryParse<ReportType>(request.ReportType, true, out var reportType);
|
||||
if (!Enum.IsDefined(reportType))
|
||||
@@ -340,7 +339,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
|
||||
[HttpPatch]
|
||||
[Route("{id}/report/{reportId}")]
|
||||
[Authorize(Policy = "AuthAndNotBanned")]
|
||||
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||
[EnableRateLimiting("Sensitive")]
|
||||
public async Task<IActionResult> ModifyPasteReport(string id, int reportId, [FromBody] ReportDto request)
|
||||
{
|
||||
@@ -352,9 +351,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
if (report == null || report.TargetType != ReportTargetType.Paste || report.PastePID != paste.PID)
|
||||
return NotFound(new { success = false, message = "Report not found." });
|
||||
|
||||
var user = HttpContext.GetJwtUser();
|
||||
if (user == null)
|
||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
||||
var user = HttpContext.GetJwtUser()!;
|
||||
|
||||
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
|
||||
if (report.ReporterUUID != user.UUID && !hasPrivilegedRole)
|
||||
@@ -376,7 +373,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
|
||||
[HttpDelete]
|
||||
[Route("{id}/report/{reportId}")]
|
||||
[Authorize(Policy = "AuthAndNotBanned")]
|
||||
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||
[EnableRateLimiting("Sensitive")]
|
||||
public async Task<IActionResult> DeletePasteReport(string id, int reportId)
|
||||
{
|
||||
@@ -388,9 +385,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
if (report == null || report.TargetType != ReportTargetType.Paste || report.PastePID != paste.PID)
|
||||
return NotFound(new { success = false, message = "Report not found." });
|
||||
|
||||
var user = HttpContext.GetJwtUser();
|
||||
if (user == null)
|
||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
||||
var user = HttpContext.GetJwtUser()!;
|
||||
|
||||
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
|
||||
if (report.ReporterUUID != user.UUID && !hasPrivilegedRole)
|
||||
|
||||
@@ -15,12 +15,10 @@ namespace SharpbinV3.Server.Controllers
|
||||
[Route("{reportId:int}")]
|
||||
[HttpGet]
|
||||
[EnableRateLimiting("Sliding")]
|
||||
[Authorize(Policy = "AuthAndNotBanned")]
|
||||
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||
public async Task<IActionResult> GetReportById(int reportId)
|
||||
{
|
||||
var user = HttpContext.GetJwtUser();
|
||||
if (user is null)
|
||||
return Unauthorized(new { success = false, message = "You must be logged in to view reports." });
|
||||
var user = HttpContext.GetJwtUser()!;
|
||||
|
||||
var report = await reportService.GetReportByID(reportId);
|
||||
if (report is null)
|
||||
@@ -57,12 +55,10 @@ namespace SharpbinV3.Server.Controllers
|
||||
[Route("{reportId:int}")]
|
||||
[HttpPatch]
|
||||
[EnableRateLimiting("Sensitive")]
|
||||
[Authorize(Policy = "AuthAndNotBanned")]
|
||||
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||
public async Task<IActionResult> UpdateReport(int reportId, [FromBody] ReportUpdateDto request)
|
||||
{
|
||||
var user = HttpContext.GetJwtUser();
|
||||
if (user is null)
|
||||
return Unauthorized(new { success = false, message = "You must be logged in to update reports." });
|
||||
var user = HttpContext.GetJwtUser()!;
|
||||
if (!user.Roles.Contains(1) && !user.Roles.Contains(255))
|
||||
return StatusCode(403, new { success = false, message = "You do not have permission to update reports." });
|
||||
|
||||
@@ -127,12 +123,10 @@ namespace SharpbinV3.Server.Controllers
|
||||
[Route("pastes")]
|
||||
[HttpGet]
|
||||
[EnableRateLimiting("Sliding")]
|
||||
[Authorize(Policy = "AuthAndNotBanned")]
|
||||
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||
public async Task<IActionResult> GetReportsForPastes([FromQuery] ReportQuery request)
|
||||
{
|
||||
var user = HttpContext.GetJwtUser();
|
||||
if (user is null)
|
||||
return Unauthorized(new { success = false, message = "You must be logged in to view reports." });
|
||||
var user = HttpContext.GetJwtUser()!;
|
||||
if (!user.Roles.Contains(1) && !user.Roles.Contains(255))
|
||||
return StatusCode(403, new { success = false, message = "You do not have permission to view pastes." });
|
||||
|
||||
@@ -159,12 +153,10 @@ namespace SharpbinV3.Server.Controllers
|
||||
[Route("users")]
|
||||
[HttpGet]
|
||||
[EnableRateLimiting("Sliding")]
|
||||
[Authorize(Policy = "AuthAndNotBanned")]
|
||||
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||
public async Task<IActionResult> GetReportsForUsers([FromQuery] ReportQuery request)
|
||||
{
|
||||
var user = HttpContext.GetJwtUser();
|
||||
if (user is null)
|
||||
return Unauthorized(new { success = false, message = "You must be logged in to view reports." });
|
||||
var user = HttpContext.GetJwtUser()!;
|
||||
if (!user.Roles.Contains(1) && !user.Roles.Contains(255))
|
||||
return StatusCode(403, new { success = false, message = "You do not have permission to view users." });
|
||||
|
||||
@@ -197,7 +189,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
[Route("all")]
|
||||
[HttpGet]
|
||||
[EnableRateLimiting("Sliding")]
|
||||
[Authorize(Policy = "AuthAndNotBanned")]
|
||||
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||
public async Task<IActionResult> GetAllReports(
|
||||
[FromQuery] Guid? reporterUuid,
|
||||
[FromQuery] ReportTargetType? targetType,
|
||||
@@ -207,9 +199,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
[FromQuery] int pageSize = 20
|
||||
)
|
||||
{
|
||||
var user = HttpContext.GetJwtUser();
|
||||
if (user is null)
|
||||
return Unauthorized(new { success = false, message = "You must be logged in to view reports." });
|
||||
var user = HttpContext.GetJwtUser()!;
|
||||
if (!user.Roles.Contains(1) && !user.Roles.Contains(255))
|
||||
return StatusCode(403, new { success = false, message = "You do not have permission to view reports." });
|
||||
|
||||
|
||||
@@ -53,16 +53,13 @@ namespace SharpbinV3.Server.Controllers
|
||||
[Authorize]
|
||||
public async Task<IActionResult> GetMe([FromQuery] int page = 1)
|
||||
{
|
||||
var userUUID = HttpContext.User?.FindFirst("uuid")?.Value;
|
||||
if (userUUID is null)
|
||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
||||
|
||||
var userUUID = HttpContext.User.FindFirst("uuid")!.Value;
|
||||
var user = await _userService.GetByUUID(Guid.Parse(userUUID), withPastes: true);
|
||||
return user == null ? NotFound(new { success = false, message = "User not found." }) : await BuildUserResponse(user, page);
|
||||
}
|
||||
|
||||
[HttpPatch("uuid/{uuid}")]
|
||||
[Authorize]
|
||||
[Authorize(Policy = "JwtOnly")]
|
||||
[EnableRateLimiting("Strict")]
|
||||
public async Task<IActionResult> UpdateByUUID(Guid uuid, [FromBody] UpdateUserDto updatedUser)
|
||||
{
|
||||
@@ -70,9 +67,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(ModelState);
|
||||
|
||||
var jwtUser = HttpContext.GetJwtUser();
|
||||
if (jwtUser == null)
|
||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
||||
var jwtUser = HttpContext.GetJwtUser()!;
|
||||
|
||||
var user = await _userService.GetByUUID(uuid);
|
||||
if (user == null)
|
||||
@@ -113,13 +108,11 @@ namespace SharpbinV3.Server.Controllers
|
||||
}
|
||||
|
||||
[HttpDelete("uuid/{uuid}")]
|
||||
[Authorize(Policy = "AuthAndNotBanned")]
|
||||
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||
[EnableRateLimiting("Sensitive")]
|
||||
public async Task<IActionResult> DeleteByUUID(Guid uuid, [FromBody] DeleteUserDto dto)
|
||||
{
|
||||
var jwtUser = HttpContext.GetJwtUser();
|
||||
if (jwtUser == null)
|
||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
||||
var jwtUser = HttpContext.GetJwtUser()!;
|
||||
|
||||
var user = await _userService.GetByUUID(uuid);
|
||||
if (user == null)
|
||||
@@ -159,12 +152,10 @@ namespace SharpbinV3.Server.Controllers
|
||||
[HttpPost]
|
||||
[Route("{uuid}/report")]
|
||||
[EnableRateLimiting("Sensitive")]
|
||||
[Authorize(Policy = "AuthAndNotBanned")]
|
||||
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||
public async Task<IActionResult> ReportUser(Guid uuid, [FromBody] ReportDto request)
|
||||
{
|
||||
var reporter = HttpContext.GetJwtUser();
|
||||
if (reporter == null)
|
||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
||||
var reporter = HttpContext.GetJwtUser()!;
|
||||
|
||||
var reportedUser = await _userService.GetByUUID(uuid);
|
||||
if (reportedUser == null)
|
||||
@@ -210,12 +201,10 @@ namespace SharpbinV3.Server.Controllers
|
||||
[HttpPatch]
|
||||
[Route("{uuid}/report/{reportId}")]
|
||||
[EnableRateLimiting("Sensitive")]
|
||||
[Authorize(Policy = "AuthAndNotBanned")]
|
||||
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||
public async Task<IActionResult> UpdateUserReport(Guid uuid, int reportId, [FromBody] ReportDto request)
|
||||
{
|
||||
var jwtUser = HttpContext.GetJwtUser();
|
||||
if (jwtUser == null)
|
||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
||||
var jwtUser = HttpContext.GetJwtUser()!;
|
||||
|
||||
var user = await _userService.GetByUUID(uuid);
|
||||
if (user == null)
|
||||
@@ -239,12 +228,10 @@ namespace SharpbinV3.Server.Controllers
|
||||
[HttpDelete]
|
||||
[Route("{uuid}/report/{reportId}")]
|
||||
[EnableRateLimiting("Sensitive")]
|
||||
[Authorize(Policy = "AuthAndNotBanned")]
|
||||
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||
public async Task<IActionResult> DeleteUserReport(Guid uuid, int reportId)
|
||||
{
|
||||
var jwtUser = HttpContext.GetJwtUser();
|
||||
if (jwtUser == null)
|
||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
||||
var jwtUser = HttpContext.GetJwtUser()!;
|
||||
|
||||
var user = await _userService.GetByUUID(uuid);
|
||||
if (user == null)
|
||||
@@ -262,13 +249,11 @@ namespace SharpbinV3.Server.Controllers
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
[Authorize]
|
||||
[Authorize(Policy = "JwtOnly")]
|
||||
[Route("{uuid}/reports")]
|
||||
public async Task<IActionResult> GetUserReports(Guid uuid, [FromQuery] ReportQuery request)
|
||||
{
|
||||
var jwtUser = HttpContext.GetJwtUser();
|
||||
if (jwtUser == null)
|
||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
||||
var jwtUser = HttpContext.GetJwtUser()!;
|
||||
|
||||
var user = await _userService.GetByUUID(uuid);
|
||||
if (user == null)
|
||||
@@ -297,13 +282,11 @@ namespace SharpbinV3.Server.Controllers
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
[Authorize]
|
||||
[Authorize(Policy = "JwtOnly")]
|
||||
[Route("{uuid}/reports/submitted")]
|
||||
public async Task<IActionResult> GetUserSubmittedReports(Guid uuid, [FromQuery] ReportQuery request)
|
||||
{
|
||||
var jwtUser = HttpContext.GetJwtUser();
|
||||
if (jwtUser == null)
|
||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
||||
var jwtUser = HttpContext.GetJwtUser()!;
|
||||
|
||||
var user = await _userService.GetByUUID(uuid);
|
||||
if (user == null)
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace SharpbinV3.Server.DTOs.ApiKey
|
||||
{
|
||||
public sealed class ApiKeyListItemDto
|
||||
{
|
||||
public required string Name { get; set; }
|
||||
public required Guid UUID { get; set; }
|
||||
public required long CreatedAt { get; set; }
|
||||
public long? LastUsedAt { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace SharpbinV3.Server.DTOs.ApiKey
|
||||
{
|
||||
public sealed class ApiKeyResponseDto
|
||||
{
|
||||
public required string Key { get; set; }
|
||||
public required string Name { get; set; }
|
||||
public required Guid UUID { get; set; }
|
||||
public required long CreatedAt { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace SharpbinV3.Server.DTOs.ApiKey
|
||||
{
|
||||
public sealed class CreateApiKeyRequest
|
||||
{
|
||||
public required string Name { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ namespace SharpbinV3.Server.Data
|
||||
public DbSet<RefreshToken> RefreshTokens => Set<RefreshToken>();
|
||||
public DbSet<UserTotp> UserTotps => Set<UserTotp>();
|
||||
public DbSet<Report> Reports => Set<Report>();
|
||||
public DbSet<ApiKey> ApiKeys => Set<ApiKey>();
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
@@ -56,6 +57,12 @@ namespace SharpbinV3.Server.Data
|
||||
.WithMany(u => u.Reports)
|
||||
.HasForeignKey(r => r.UserUUID)
|
||||
.OnDelete(DeleteBehavior.SetNull);
|
||||
|
||||
modelBuilder.Entity<ApiKey>()
|
||||
.HasOne(a => a.User)
|
||||
.WithMany(u => u.ApiKeys)
|
||||
.HasForeignKey(a => a.UserUUID)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace SharpbinV3.Server.Data.Entities
|
||||
{
|
||||
public sealed class ApiKey
|
||||
{
|
||||
[Key]
|
||||
public Guid UUID { get; set; } = Guid.CreateVersion7();
|
||||
public required Guid UserUUID { get; set; }
|
||||
public User? User { get; set; }
|
||||
public required string KeyHash { get; set; }
|
||||
public required string Name { get; set; }
|
||||
public long CreatedAt { get; set; } = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
||||
public long? LastUsedAt { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,7 @@ namespace SharpbinV3.Server.Data.Entities
|
||||
public List<Paste> Pastes { get; set; } = [];
|
||||
public List<RefreshToken> RefreshTokens { get; set; } = [];
|
||||
public List<Report> Reports { get; set; } = [];
|
||||
public List<ApiKey> ApiKeys { get; set; } = [];
|
||||
public UserTotp? Totp { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using SharpbinV3.Server.Data.Entities;
|
||||
using SharpbinV3.Server.Services;
|
||||
|
||||
namespace SharpbinV3.Server.Extensions
|
||||
@@ -16,6 +17,38 @@ namespace SharpbinV3.Server.Extensions
|
||||
"X-ProxyUser-IP",
|
||||
];
|
||||
|
||||
private const string ApiKeyContextKey = "ApiKey";
|
||||
|
||||
public static string? GetApiKey(this HttpContext context)
|
||||
{
|
||||
var apiKeyHeader = context.Request.Headers["X-API-Key"].FirstOrDefault();
|
||||
if (string.IsNullOrEmpty(apiKeyHeader))
|
||||
return null;
|
||||
|
||||
if (apiKeyHeader.Length != ApiKeyService.KeyLength)
|
||||
return null;
|
||||
|
||||
return apiKeyHeader;
|
||||
}
|
||||
|
||||
public static ApiKey? GetApiKeyFromContext(this HttpContext context)
|
||||
{
|
||||
if (context.Items.TryGetValue(ApiKeyContextKey, out var apiKey))
|
||||
return apiKey as ApiKey;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static void SetApiKeyContext(this HttpContext context, ApiKey apiKey)
|
||||
{
|
||||
context.Items[ApiKeyContextKey] = apiKey;
|
||||
}
|
||||
|
||||
public static bool IsApiKeyAuthenticated(this HttpContext context)
|
||||
{
|
||||
return context.GetApiKeyFromContext() != null;
|
||||
}
|
||||
|
||||
public static JwtUser? GetJwtUser(this HttpContext context)
|
||||
{
|
||||
if (context.User == null || !context.User.Identity?.IsAuthenticated == true)
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
using SharpbinV3.Server.Extensions;
|
||||
using SharpbinV3.Server.Services;
|
||||
|
||||
namespace SharpbinV3.Server.Middleware
|
||||
{
|
||||
public sealed class ApiKeyAuthenticationMiddleware(RequestDelegate next)
|
||||
{
|
||||
private readonly RequestDelegate _next = next;
|
||||
|
||||
public async Task InvokeAsync(HttpContext context, ApiKeyService apiKeyService)
|
||||
{
|
||||
var apiKeyString = context.GetApiKey();
|
||||
if (!string.IsNullOrEmpty(apiKeyString))
|
||||
{
|
||||
var apiKey = await apiKeyService.GetByKeyAsync(apiKeyString);
|
||||
if (apiKey != null)
|
||||
{
|
||||
context.SetApiKeyContext(apiKey);
|
||||
await apiKeyService.UpdateLastUsedAsync(apiKey.UUID);
|
||||
}
|
||||
}
|
||||
|
||||
await _next(context);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,405 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using SharpbinV3.Server.Data;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SharpbinV3.Server.Migrations
|
||||
{
|
||||
[DbContext(typeof(AppDbContext))]
|
||||
[Migration("20260210231315_AddApiKeys")]
|
||||
partial class AddApiKeys
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder.HasAnnotation("ProductVersion", "10.0.1");
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b =>
|
||||
{
|
||||
b.Property<Guid>("UUID")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long>("CreatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("KeyHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long?>("LastUsedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<Guid>("UserUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("UUID");
|
||||
|
||||
b.HasIndex("UserUUID");
|
||||
|
||||
b.ToTable("ApiKeys");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
|
||||
{
|
||||
b.Property<int>("PID")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<Guid?>("AuthorUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<byte[]>("Content")
|
||||
.IsRequired()
|
||||
.HasColumnType("BLOB");
|
||||
|
||||
b.Property<long>("CreatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long?>("EditedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("ExpiresAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("ID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<bool>("IsCompressed")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("Size")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("Syntax")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Title")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long>("TrueSize")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<Guid>("UUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<int>("Views")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("Visibility")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.HasKey("PID");
|
||||
|
||||
b.HasIndex("AuthorUUID");
|
||||
|
||||
b.HasIndex("ExpiresAt");
|
||||
|
||||
b.HasIndex("ID")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("PID")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("Size");
|
||||
|
||||
b.HasIndex("Syntax");
|
||||
|
||||
b.HasIndex("UUID")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("Views");
|
||||
|
||||
b.HasIndex("Visibility");
|
||||
|
||||
b.ToTable("Pastes");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("PastePID")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("ViewedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("ViewerHash")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("PastePID", "ViewerHash")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("PasteViews");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<DateTimeOffset>("ExpiresAt")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("JwtId")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("ReplacedByToken")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<bool>("Revoked")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<byte[]>("RowVersion")
|
||||
.IsRequired()
|
||||
.HasColumnType("BLOB");
|
||||
|
||||
b.Property<string>("TokenHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<bool>("Used")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<Guid>("UserUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("TokenHash")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("UserUUID");
|
||||
|
||||
b.ToTable("RefreshTokens");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b =>
|
||||
{
|
||||
b.Property<int>("ReportID")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("CreatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("Description")
|
||||
.HasMaxLength(1000)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<int?>("PastePID")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<Guid>("ReporterUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<int>("Status")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("TargetType")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("Type")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long?>("UpdatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<Guid?>("UserUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("ReportID");
|
||||
|
||||
b.HasIndex("PastePID");
|
||||
|
||||
b.HasIndex("ReportID")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("ReporterUUID");
|
||||
|
||||
b.HasIndex("TargetType");
|
||||
|
||||
b.HasIndex("UserUUID");
|
||||
|
||||
b.ToTable("Reports");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
|
||||
{
|
||||
b.Property<Guid>("UUID")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long>("CreatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("DisplayName")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Email")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long?>("LastLogin")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("PasswordHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.PrimitiveCollection<string>("Roles")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<int?>("UID")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("Username")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<int>("Visibility")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.HasKey("UUID");
|
||||
|
||||
b.HasIndex("UID");
|
||||
|
||||
b.HasIndex("UUID")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Users");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b =>
|
||||
{
|
||||
b.Property<Guid>("UserUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long>("CreatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<byte[]>("EncryptedSecret")
|
||||
.IsRequired()
|
||||
.HasColumnType("BLOB");
|
||||
|
||||
b.HasKey("UserUUID");
|
||||
|
||||
b.ToTable("UserTotps");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
|
||||
.WithMany("ApiKeys")
|
||||
.HasForeignKey("UserUUID")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
|
||||
.WithMany("Pastes")
|
||||
.HasForeignKey("AuthorUUID")
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
|
||||
.WithMany("PasteViews")
|
||||
.HasForeignKey("PastePID")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Paste");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
|
||||
.WithMany("RefreshTokens")
|
||||
.HasForeignKey("UserUUID")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
|
||||
.WithMany("Reports")
|
||||
.HasForeignKey("PastePID")
|
||||
.OnDelete(DeleteBehavior.SetNull);
|
||||
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
|
||||
.WithMany("Reports")
|
||||
.HasForeignKey("UserUUID")
|
||||
.OnDelete(DeleteBehavior.SetNull);
|
||||
|
||||
b.Navigation("Paste");
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
|
||||
.WithOne("Totp")
|
||||
.HasForeignKey("SharpbinV3.Server.Data.Entities.UserTotp", "UserUUID")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
|
||||
{
|
||||
b.Navigation("PasteViews");
|
||||
|
||||
b.Navigation("Reports");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
|
||||
{
|
||||
b.Navigation("ApiKeys");
|
||||
|
||||
b.Navigation("Pastes");
|
||||
|
||||
b.Navigation("RefreshTokens");
|
||||
|
||||
b.Navigation("Reports");
|
||||
|
||||
b.Navigation("Totp");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SharpbinV3.Server.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddApiKeys : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "ApiKeys",
|
||||
columns: table => new
|
||||
{
|
||||
UUID = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
UserUUID = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
KeyHash = table.Column<string>(type: "TEXT", nullable: false),
|
||||
Name = table.Column<string>(type: "TEXT", nullable: false),
|
||||
CreatedAt = table.Column<long>(type: "INTEGER", nullable: false),
|
||||
LastUsedAt = table.Column<long>(type: "INTEGER", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_ApiKeys", x => x.UUID);
|
||||
table.ForeignKey(
|
||||
name: "FK_ApiKeys_Users_UserUUID",
|
||||
column: x => x.UserUUID,
|
||||
principalTable: "Users",
|
||||
principalColumn: "UUID",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_ApiKeys_UserUUID",
|
||||
table: "ApiKeys",
|
||||
column: "UserUUID");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "ApiKeys");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,36 @@ namespace SharpbinV3.Server.Migrations
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder.HasAnnotation("ProductVersion", "10.0.1");
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b =>
|
||||
{
|
||||
b.Property<Guid>("UUID")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long>("CreatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("KeyHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long?>("LastUsedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<Guid>("UserUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("UUID");
|
||||
|
||||
b.HasIndex("UserUUID");
|
||||
|
||||
b.ToTable("ApiKeys");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
|
||||
{
|
||||
b.Property<int>("PID")
|
||||
@@ -276,6 +306,17 @@ namespace SharpbinV3.Server.Migrations
|
||||
b.ToTable("UserTotps");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
|
||||
.WithMany("ApiKeys")
|
||||
.HasForeignKey("UserUUID")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
|
||||
@@ -345,6 +386,8 @@ namespace SharpbinV3.Server.Migrations
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
|
||||
{
|
||||
b.Navigation("ApiKeys");
|
||||
|
||||
b.Navigation("Pastes");
|
||||
|
||||
b.Navigation("RefreshTokens");
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
using System.Text;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.RateLimiting;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Microsoft.OpenApi;
|
||||
using SharpbinV3.Server.Authentication;
|
||||
using SharpbinV3.Server.Authorization;
|
||||
using SharpbinV3.Server.Data;
|
||||
using SharpbinV3.Server.Extensions;
|
||||
@@ -38,7 +41,21 @@ namespace SharpbinV3.Server
|
||||
options.AddDocumentTransformer(
|
||||
(document, context, cancellationToken) =>
|
||||
{
|
||||
document?.Components ??= new();
|
||||
document?.Servers?.Clear();
|
||||
document?.Components?.SecuritySchemes ??= new Dictionary<string, IOpenApiSecurityScheme>();
|
||||
|
||||
document
|
||||
?.Components
|
||||
?.SecuritySchemes
|
||||
?["ApiKey"] = new OpenApiSecurityScheme
|
||||
{
|
||||
Type = SecuritySchemeType.ApiKey,
|
||||
Name = "X-API-Key",
|
||||
In = ParameterLocation.Header,
|
||||
Description = "Bypass authentication and captcha by providing a valid API key.",
|
||||
};
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
);
|
||||
@@ -54,6 +71,7 @@ namespace SharpbinV3.Server
|
||||
builder.Services.AddScoped<UserService>();
|
||||
builder.Services.AddScoped<AuthService>();
|
||||
builder.Services.AddScoped<PasteService>();
|
||||
builder.Services.AddScoped<ApiKeyService>();
|
||||
builder.Services.AddScoped<VerificationService>();
|
||||
builder.Services.AddScoped<TotpVerificationProvider>();
|
||||
builder.Services.AddHttpClient<IVerificationProvider, TurnstileVerificationProvider>();
|
||||
@@ -75,7 +93,34 @@ namespace SharpbinV3.Server
|
||||
.ValidateOnStart();
|
||||
builder.Services.Configure<AuthSettings>(builder.Configuration.GetSection("AuthSettings"));
|
||||
|
||||
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer();
|
||||
builder
|
||||
.Services.AddAuthentication(options =>
|
||||
{
|
||||
options.DefaultAuthenticateScheme = AuthSchemes.Combined;
|
||||
options.DefaultScheme = AuthSchemes.Combined;
|
||||
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||
})
|
||||
.AddPolicyScheme(
|
||||
AuthSchemes.Combined,
|
||||
AuthSchemes.Combined,
|
||||
options =>
|
||||
{
|
||||
options.ForwardDefaultSelector = context =>
|
||||
{
|
||||
var apiKeyHeader = context.Request.Headers["X-API-Key"].ToString();
|
||||
if (!string.IsNullOrEmpty(apiKeyHeader))
|
||||
return AuthSchemes.ApiKey;
|
||||
|
||||
var authHeader = context.Request.Headers.Authorization.ToString();
|
||||
if (!string.IsNullOrEmpty(authHeader) && authHeader.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
|
||||
return JwtBearerDefaults.AuthenticationScheme;
|
||||
|
||||
return JwtBearerDefaults.AuthenticationScheme;
|
||||
};
|
||||
}
|
||||
)
|
||||
.AddJwtBearer()
|
||||
.AddScheme<AuthenticationSchemeOptions, ApiKeyAuthenticationHandler>(AuthSchemes.ApiKey, _ => { });
|
||||
|
||||
builder
|
||||
.Services.AddOptions<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme)
|
||||
@@ -109,6 +154,27 @@ namespace SharpbinV3.Server
|
||||
|
||||
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(
|
||||
"JwtOnly",
|
||||
policy =>
|
||||
{
|
||||
policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
|
||||
policy.RequireAuthenticatedUser();
|
||||
}
|
||||
);
|
||||
builder
|
||||
.Services.AddAuthorizationBuilder()
|
||||
.AddPolicy(
|
||||
"JwtOnlyAndNotBanned",
|
||||
policy =>
|
||||
{
|
||||
policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
|
||||
policy.RequireAuthenticatedUser();
|
||||
policy.Requirements.Add(new NotBannedRequirement());
|
||||
}
|
||||
);
|
||||
builder.Services.AddSingleton<IAuthorizationHandler>(new NotBannedHandler(false));
|
||||
builder.Services.AddSingleton<IAuthorizationHandler>(new NotBannedHandler(true));
|
||||
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SharpbinV3.Server.Data;
|
||||
using SharpbinV3.Server.Data.Entities;
|
||||
using SharpbinV3.Server.Settings;
|
||||
|
||||
namespace SharpbinV3.Server.Services
|
||||
{
|
||||
public sealed class ApiKeyService(AppDbContext db, IOptions<AuthSettings> authOptions)
|
||||
{
|
||||
private readonly AppDbContext _db = db;
|
||||
private readonly AuthSettings _authSettings = authOptions.Value;
|
||||
|
||||
public const int KeyLength = 64;
|
||||
|
||||
private string ComputeHash(string input)
|
||||
{
|
||||
if (string.IsNullOrEmpty(_authSettings.API_Key_HMAC_Secret))
|
||||
return Utilities.ComputeSha256(input);
|
||||
else
|
||||
return Utilities.ComputeHmacSha256(input, _authSettings.API_Key_HMAC_Secret);
|
||||
}
|
||||
|
||||
public async Task<ApiKey?> GetByKeyAsync(string key)
|
||||
{
|
||||
var keyHash = ComputeHash(key);
|
||||
return await _db.ApiKeys.Include(a => a.User).FirstOrDefaultAsync(a => a.KeyHash == keyHash);
|
||||
}
|
||||
|
||||
public async Task<(ApiKey apiKey, string key)> CreateAsync(Guid userUUID, string name)
|
||||
{
|
||||
var key = Utilities.GenerateSecureRandomString(KeyLength);
|
||||
var keyHash = ComputeHash(key);
|
||||
|
||||
var apiKey = new ApiKey
|
||||
{
|
||||
UserUUID = userUUID,
|
||||
Name = name,
|
||||
KeyHash = keyHash,
|
||||
};
|
||||
|
||||
_db.ApiKeys.Add(apiKey);
|
||||
await _db.SaveChangesAsync();
|
||||
|
||||
return (apiKey, key);
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteAsync(Guid userUUID, Guid keyUUID)
|
||||
{
|
||||
var apiKey = await _db.ApiKeys.FirstOrDefaultAsync(a => a.UUID == keyUUID && a.UserUUID == userUUID);
|
||||
if (apiKey == null)
|
||||
return false;
|
||||
|
||||
_db.ApiKeys.Remove(apiKey);
|
||||
await _db.SaveChangesAsync();
|
||||
return true;
|
||||
}
|
||||
|
||||
public async Task<List<ApiKey>> GetUserKeysAsync(Guid userUUID)
|
||||
{
|
||||
return await _db.ApiKeys.Where(a => a.UserUUID == userUUID).OrderByDescending(a => a.CreatedAt).ToListAsync();
|
||||
}
|
||||
|
||||
public async Task UpdateLastUsedAsync(Guid keyUUID)
|
||||
{
|
||||
var apiKey = await _db.ApiKeys.FirstOrDefaultAsync(a => a.UUID == keyUUID);
|
||||
if (apiKey == null)
|
||||
return;
|
||||
|
||||
apiKey.LastUsedAt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
||||
await _db.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ using Microsoft.IdentityModel.Tokens;
|
||||
using SharpbinV3.Server.Data;
|
||||
using SharpbinV3.Server.Data.Entities;
|
||||
using SharpbinV3.Server.DTOs.Auth;
|
||||
using SharpbinV3.Server.Extensions;
|
||||
using SharpbinV3.Server.Settings;
|
||||
using Bcrypt = BCrypt.Net.BCrypt;
|
||||
|
||||
@@ -91,7 +92,7 @@ namespace SharpbinV3.Server.Services
|
||||
var jwtToken = jwtHandler.WriteToken(token);
|
||||
var jti = claims.First(c => c.Type == JwtRegisteredClaimNames.Jti).Value;
|
||||
|
||||
var rawRefreshToken = Utilities.GenerateRandomString(36) + Guid.NewGuid();
|
||||
var rawRefreshToken = Utilities.GenerateSecureRandomString(36) + Guid.NewGuid();
|
||||
var refreshToken = new RefreshToken
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
@@ -201,6 +202,10 @@ namespace SharpbinV3.Server.Services
|
||||
|
||||
public async Task<User?> GetUserFromHttpContext(HttpContext context)
|
||||
{
|
||||
var apiKey = context.GetApiKeyFromContext();
|
||||
if (apiKey != null)
|
||||
return await _db.Users.FirstOrDefaultAsync(u => u.UUID == apiKey.UserUUID);
|
||||
|
||||
var uuidClaim = context.User.Claims.FirstOrDefault(c => c.Type == "uuid")?.Value;
|
||||
if (uuidClaim == null)
|
||||
return null;
|
||||
|
||||
@@ -35,7 +35,7 @@ namespace SharpbinV3.Server.Services
|
||||
var paste = new Paste
|
||||
{
|
||||
UUID = Guid.CreateVersion7(),
|
||||
ID = Utilities.GenerateRandomString(8),
|
||||
ID = Utilities.GenerateSecureRandomString(8),
|
||||
Title = title,
|
||||
AuthorUUID = author?.UUID,
|
||||
User = author,
|
||||
|
||||
@@ -7,5 +7,6 @@
|
||||
public bool Registration_Enabled { get; set; } = true;
|
||||
public bool First_User_Admin { get; set; } = true;
|
||||
public bool Admins_Require_2FA { get; set; } = true;
|
||||
public string API_Key_HMAC_Secret { get; set; } = string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,32 @@ namespace SharpbinV3.Server
|
||||
return new string([.. Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)])]);
|
||||
}
|
||||
|
||||
public static string GenerateSecureRandomString(int length)
|
||||
{
|
||||
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
||||
Span<byte> buffer = stackalloc byte[128];
|
||||
|
||||
var result = new char[length];
|
||||
int pos = 0;
|
||||
|
||||
while (pos < length)
|
||||
{
|
||||
RandomNumberGenerator.Fill(buffer);
|
||||
|
||||
foreach (byte b in buffer)
|
||||
{
|
||||
if (b >= 248)
|
||||
continue; // 248 is the largest multiple of 62 < 256
|
||||
|
||||
result[pos++] = chars[b % chars.Length];
|
||||
if (pos == length)
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return new string(result);
|
||||
}
|
||||
|
||||
public static string ComputeSha256(string input)
|
||||
{
|
||||
var inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
|
||||
|
||||
@@ -8,6 +8,13 @@
|
||||
"csharpier"
|
||||
],
|
||||
"rollForward": false
|
||||
},
|
||||
"dotnet-ef": {
|
||||
"version": "10.0.3",
|
||||
"commands": [
|
||||
"dotnet-ef"
|
||||
],
|
||||
"rollForward": false
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user