mirror of
https://github.com/whoswhip/Sharpbin.git
synced 2026-12-06 02:48:43 +00:00
feat(backend): implement api keys; rename token -> verificationToken in paste creation api
api keys can bypass authentication and captchas/verification
This commit is contained in:
@@ -132,9 +132,9 @@
|
|||||||
data.auth?.cf_turnstile_site_key &&
|
data.auth?.cf_turnstile_site_key &&
|
||||||
window.turnstile
|
window.turnstile
|
||||||
) {
|
) {
|
||||||
const token = window.turnstile.getResponse();
|
const verificationToken = window.turnstile.getResponse();
|
||||||
if (token) {
|
if (verificationToken) {
|
||||||
params.append('token', token);
|
params.append('verificationToken', verificationToken);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
using System.Security.Claims;
|
using System.Security.Claims;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using SharpbinV3.Server.Extensions;
|
||||||
|
|
||||||
namespace SharpbinV3.Server.Authorization
|
namespace SharpbinV3.Server.Authorization
|
||||||
{
|
{
|
||||||
@@ -9,13 +10,26 @@ namespace SharpbinV3.Server.Authorization
|
|||||||
|
|
||||||
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, NotBannedRequirement requirement)
|
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, NotBannedRequirement requirement)
|
||||||
{
|
{
|
||||||
|
var httpContext = context.Resource as HttpContext;
|
||||||
var isAuthenticated = context.User.Identity?.IsAuthenticated ?? false;
|
var isAuthenticated = context.User.Identity?.IsAuthenticated ?? false;
|
||||||
|
|
||||||
|
if (!isAuthenticated && httpContext != null)
|
||||||
|
{
|
||||||
|
var apiKey = httpContext.GetApiKeyFromContext();
|
||||||
|
if (apiKey != null)
|
||||||
|
{
|
||||||
|
isAuthenticated = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (_requireAuth && !isAuthenticated)
|
if (_requireAuth && !isAuthenticated)
|
||||||
return Task.CompletedTask;
|
return Task.CompletedTask;
|
||||||
|
|
||||||
var isBanned = context.User.Claims.Any(c => (c.Type == ClaimTypes.Role || c.Type == "role") && c.Value == "403");
|
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)
|
if (!isBanned)
|
||||||
context.Succeed(requirement);
|
context.Succeed(requirement);
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ using Microsoft.Extensions.Options;
|
|||||||
using SharpbinV3.Server.Data;
|
using SharpbinV3.Server.Data;
|
||||||
using SharpbinV3.Server.Data.Entities;
|
using SharpbinV3.Server.Data.Entities;
|
||||||
using SharpbinV3.Server.DTOs;
|
using SharpbinV3.Server.DTOs;
|
||||||
|
using SharpbinV3.Server.DTOs.ApiKey;
|
||||||
using SharpbinV3.Server.DTOs.Auth;
|
using SharpbinV3.Server.DTOs.Auth;
|
||||||
using SharpbinV3.Server.DTOs.User;
|
using SharpbinV3.Server.DTOs.User;
|
||||||
using SharpbinV3.Server.Extensions;
|
using SharpbinV3.Server.Extensions;
|
||||||
@@ -22,6 +23,7 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
public class AuthController(
|
public class AuthController(
|
||||||
UserService userService,
|
UserService userService,
|
||||||
AuthService authService,
|
AuthService authService,
|
||||||
|
ApiKeyService apiKeyService,
|
||||||
IOptions<AuthSettings> options,
|
IOptions<AuthSettings> options,
|
||||||
VerificationService verification,
|
VerificationService verification,
|
||||||
TotpVerificationProvider totp,
|
TotpVerificationProvider totp,
|
||||||
@@ -30,6 +32,7 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
{
|
{
|
||||||
private readonly AuthService _authService = authService;
|
private readonly AuthService _authService = authService;
|
||||||
private readonly UserService _userService = userService;
|
private readonly UserService _userService = userService;
|
||||||
|
private readonly ApiKeyService _apiKeyService = apiKeyService;
|
||||||
private readonly VerificationService _verification = verification;
|
private readonly VerificationService _verification = verification;
|
||||||
private readonly TotpVerificationProvider _totp = totp;
|
private readonly TotpVerificationProvider _totp = totp;
|
||||||
private readonly AppDbContext _db = db;
|
private readonly AppDbContext _db = db;
|
||||||
@@ -240,5 +243,88 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
await _db.SaveChangesAsync();
|
await _db.SaveChangesAsync();
|
||||||
return Ok(new { success = true, message = "TOTP disabled." });
|
return Ok(new { success = true, message = "TOTP disabled." });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[HttpPost]
|
||||||
|
[Authorize]
|
||||||
|
[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]
|
||||||
|
[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",
|
string syntax = "plaintext",
|
||||||
int visibility = 0,
|
int visibility = 0,
|
||||||
long expiresAt = 0,
|
long expiresAt = 0,
|
||||||
string? token = null
|
string? verificationToken = null
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
if (!_pasteService.ValidateExpiresAt(expiresAt))
|
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." }
|
new { success = false, message = $"Paste size exceeds the maximum allowed size of {_pasteSettings.MaxPasteSizeInBytes} bytes." }
|
||||||
);
|
);
|
||||||
|
|
||||||
if (
|
if (_pasteSettings.RequiresVerification && !HttpContext.IsApiKeyAuthenticated())
|
||||||
_pasteSettings.RequiresVerification
|
{
|
||||||
&& !await _verificationService.VerifyAsync(new VerificationContext { Token = token, Ip = HttpContext.GetRequestIP() })
|
var providedApiKey = HttpContext.GetApiKey();
|
||||||
)
|
if (providedApiKey != null)
|
||||||
return BadRequest(new { success = false, message = "Verification failed." });
|
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);
|
var user = await _authService.GetUserFromHttpContext(HttpContext);
|
||||||
Paste paste = await _pasteService.Create(user, content, title, syntax, visibility, expiresAt, _pasteSettings.EnablePasteCompression);
|
Paste paste = await _pasteService.Create(user, content, title, syntax, visibility, expiresAt, _pasteSettings.EnablePasteCompression);
|
||||||
|
|||||||
@@ -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<RefreshToken> RefreshTokens => Set<RefreshToken>();
|
||||||
public DbSet<UserTotp> UserTotps => Set<UserTotp>();
|
public DbSet<UserTotp> UserTotps => Set<UserTotp>();
|
||||||
public DbSet<Report> Reports => Set<Report>();
|
public DbSet<Report> Reports => Set<Report>();
|
||||||
|
public DbSet<ApiKey> ApiKeys => Set<ApiKey>();
|
||||||
|
|
||||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||||
{
|
{
|
||||||
@@ -56,6 +57,12 @@ namespace SharpbinV3.Server.Data
|
|||||||
.WithMany(u => u.Reports)
|
.WithMany(u => u.Reports)
|
||||||
.HasForeignKey(r => r.UserUUID)
|
.HasForeignKey(r => r.UserUUID)
|
||||||
.OnDelete(DeleteBehavior.SetNull);
|
.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<Paste> Pastes { get; set; } = [];
|
||||||
public List<RefreshToken> RefreshTokens { get; set; } = [];
|
public List<RefreshToken> RefreshTokens { get; set; } = [];
|
||||||
public List<Report> Reports { get; set; } = [];
|
public List<Report> Reports { get; set; } = [];
|
||||||
|
public List<ApiKey> ApiKeys { get; set; } = [];
|
||||||
public UserTotp? Totp { get; set; }
|
public UserTotp? Totp { get; set; }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
using System.IdentityModel.Tokens.Jwt;
|
using System.IdentityModel.Tokens.Jwt;
|
||||||
using System.Security.Claims;
|
using System.Security.Claims;
|
||||||
|
using SharpbinV3.Server.Data.Entities;
|
||||||
using SharpbinV3.Server.Services;
|
using SharpbinV3.Server.Services;
|
||||||
|
|
||||||
namespace SharpbinV3.Server.Extensions
|
namespace SharpbinV3.Server.Extensions
|
||||||
@@ -16,6 +17,38 @@ namespace SharpbinV3.Server.Extensions
|
|||||||
"X-ProxyUser-IP",
|
"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)
|
public static JwtUser? GetJwtUser(this HttpContext context)
|
||||||
{
|
{
|
||||||
if (context.User == null || !context.User.Identity?.IsAuthenticated == true)
|
if (context.User == null || !context.User.Identity?.IsAuthenticated == true)
|
||||||
|
|||||||
@@ -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
|
#pragma warning disable 612, 618
|
||||||
modelBuilder.HasAnnotation("ProductVersion", "10.0.1");
|
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 =>
|
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
|
||||||
{
|
{
|
||||||
b.Property<int>("PID")
|
b.Property<int>("PID")
|
||||||
@@ -276,6 +306,17 @@ namespace SharpbinV3.Server.Migrations
|
|||||||
b.ToTable("UserTotps");
|
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 =>
|
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
|
||||||
{
|
{
|
||||||
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
|
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
|
||||||
@@ -345,6 +386,8 @@ namespace SharpbinV3.Server.Migrations
|
|||||||
|
|
||||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
|
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
|
||||||
{
|
{
|
||||||
|
b.Navigation("ApiKeys");
|
||||||
|
|
||||||
b.Navigation("Pastes");
|
b.Navigation("Pastes");
|
||||||
|
|
||||||
b.Navigation("RefreshTokens");
|
b.Navigation("RefreshTokens");
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ using Microsoft.AspNetCore.DataProtection;
|
|||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using Microsoft.IdentityModel.Tokens;
|
using Microsoft.IdentityModel.Tokens;
|
||||||
|
using Microsoft.OpenApi;
|
||||||
using SharpbinV3.Server.Authorization;
|
using SharpbinV3.Server.Authorization;
|
||||||
using SharpbinV3.Server.Data;
|
using SharpbinV3.Server.Data;
|
||||||
using SharpbinV3.Server.Extensions;
|
using SharpbinV3.Server.Extensions;
|
||||||
@@ -38,7 +39,21 @@ namespace SharpbinV3.Server
|
|||||||
options.AddDocumentTransformer(
|
options.AddDocumentTransformer(
|
||||||
(document, context, cancellationToken) =>
|
(document, context, cancellationToken) =>
|
||||||
{
|
{
|
||||||
|
document?.Components ??= new();
|
||||||
document?.Servers?.Clear();
|
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;
|
return Task.CompletedTask;
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
@@ -54,6 +69,7 @@ namespace SharpbinV3.Server
|
|||||||
builder.Services.AddScoped<UserService>();
|
builder.Services.AddScoped<UserService>();
|
||||||
builder.Services.AddScoped<AuthService>();
|
builder.Services.AddScoped<AuthService>();
|
||||||
builder.Services.AddScoped<PasteService>();
|
builder.Services.AddScoped<PasteService>();
|
||||||
|
builder.Services.AddScoped<ApiKeyService>();
|
||||||
builder.Services.AddScoped<VerificationService>();
|
builder.Services.AddScoped<VerificationService>();
|
||||||
builder.Services.AddScoped<TotpVerificationProvider>();
|
builder.Services.AddScoped<TotpVerificationProvider>();
|
||||||
builder.Services.AddHttpClient<IVerificationProvider, TurnstileVerificationProvider>();
|
builder.Services.AddHttpClient<IVerificationProvider, TurnstileVerificationProvider>();
|
||||||
@@ -220,6 +236,8 @@ namespace SharpbinV3.Server
|
|||||||
app.UseHttpsRedirection();
|
app.UseHttpsRedirection();
|
||||||
app.UseCors();
|
app.UseCors();
|
||||||
|
|
||||||
|
app.UseMiddleware<Middleware.ApiKeyAuthenticationMiddleware>();
|
||||||
|
|
||||||
app.UseAuthentication();
|
app.UseAuthentication();
|
||||||
app.UseAuthorization();
|
app.UseAuthorization();
|
||||||
|
|
||||||
|
|||||||
@@ -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.GenerateRandomString(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;
|
||||||
using SharpbinV3.Server.Data.Entities;
|
using SharpbinV3.Server.Data.Entities;
|
||||||
using SharpbinV3.Server.DTOs.Auth;
|
using SharpbinV3.Server.DTOs.Auth;
|
||||||
|
using SharpbinV3.Server.Extensions;
|
||||||
using SharpbinV3.Server.Settings;
|
using SharpbinV3.Server.Settings;
|
||||||
using Bcrypt = BCrypt.Net.BCrypt;
|
using Bcrypt = BCrypt.Net.BCrypt;
|
||||||
|
|
||||||
@@ -201,6 +202,10 @@ namespace SharpbinV3.Server.Services
|
|||||||
|
|
||||||
public async Task<User?> GetUserFromHttpContext(HttpContext context)
|
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;
|
var uuidClaim = context.User.Claims.FirstOrDefault(c => c.Type == "uuid")?.Value;
|
||||||
if (uuidClaim == null)
|
if (uuidClaim == null)
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
@@ -7,5 +7,6 @@
|
|||||||
public bool Registration_Enabled { get; set; } = true;
|
public bool Registration_Enabled { get; set; } = true;
|
||||||
public bool First_User_Admin { get; set; } = true;
|
public bool First_User_Admin { get; set; } = true;
|
||||||
public bool Admins_Require_2FA { get; set; } = true;
|
public bool Admins_Require_2FA { get; set; } = true;
|
||||||
|
public string API_Key_HMAC_Secret { get; set; } = string.Empty;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user