mirror of
https://github.com/LBPUnion/ProjectLighthouse.git
synced 2025-08-08 12:58:41 +00:00
Fix base64 image parsing and remove DBContext from rate limiter
This commit is contained in:
parent
ace3678da7
commit
4107ecc654
2 changed files with 14 additions and 6 deletions
|
@ -274,6 +274,13 @@ public static class FileHelper
|
|||
|
||||
private static readonly Regex base64Regex = new(@"data:([^\/]+)\/([^;]+);base64,(.*)", RegexOptions.Compiled);
|
||||
|
||||
private static byte[]? TryParseBase64Data(string b64)
|
||||
{
|
||||
Span<byte> buffer = new(new byte[b64.Length]);
|
||||
bool valid = Convert.TryFromBase64String(b64, buffer, out _);
|
||||
return valid ? buffer.ToArray() : null;
|
||||
}
|
||||
|
||||
public static async Task<string?> ParseBase64Image(string? image)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(image)) return null;
|
||||
|
@ -284,7 +291,8 @@ public static class FileHelper
|
|||
|
||||
if (match.Groups.Count != 4) return null;
|
||||
|
||||
byte[] data = Convert.FromBase64String(match.Groups[3].Value);
|
||||
byte[]? data = TryParseBase64Data(match.Groups[3].Value);
|
||||
if (data == null) return null;
|
||||
|
||||
LbpFile file = new(data);
|
||||
|
||||
|
|
|
@ -13,16 +13,16 @@ using Microsoft.AspNetCore.Http;
|
|||
|
||||
namespace LBPUnion.ProjectLighthouse.Middlewares;
|
||||
|
||||
public class RateLimitMiddleware : MiddlewareDBContext
|
||||
public class RateLimitMiddleware : Middleware
|
||||
{
|
||||
|
||||
// (userId, requestData)
|
||||
// (ipAddress, requestData)
|
||||
private static readonly ConcurrentDictionary<IPAddress, List<LighthouseRequest?>> recentRequests = new();
|
||||
|
||||
public RateLimitMiddleware(RequestDelegate next) : base(next)
|
||||
{ }
|
||||
|
||||
public override async Task InvokeAsync(HttpContext ctx, Database database)
|
||||
public override async Task InvokeAsync(HttpContext ctx)
|
||||
{
|
||||
// We only want to rate limit POST requests
|
||||
if (ctx.Request.Method != "POST")
|
||||
|
@ -51,9 +51,9 @@ public class RateLimitMiddleware : MiddlewareDBContext
|
|||
|
||||
if (GetNumRequestsForPath(address, path) >= GetMaxNumRequests(options))
|
||||
{
|
||||
Logger.Info($"Request limit reached for {address.ToString()} ({ctx.Request.Path})", LogArea.RateLimit);
|
||||
Logger.Info($"Request limit reached for {address} ({ctx.Request.Path})", LogArea.RateLimit);
|
||||
long nextExpiration = recentRequests[address][0]?.Expiration ?? TimeHelper.TimestampMillis;
|
||||
ctx.Response.Headers.Add("Retry-After", "" + Math.Ceiling((nextExpiration - TimeHelper.TimestampMillis) / 1000f));
|
||||
ctx.Response.Headers.TryAdd("Retry-After", "" + Math.Ceiling((nextExpiration - TimeHelper.TimestampMillis) / 1000f));
|
||||
ctx.Response.StatusCode = 429;
|
||||
return;
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue