Commit Message Generated by Copilot

Enhance date handling, error checks, data limits, and rate limiting

- Added `using System.Globalization;` to support date and time formatting.
- Handled empty/null paste titles with defaults and truncation.
- Display paste dates as human-readable time differences.
- Changed rate limiting policy to "fixed-bigger".
- Improved error handling for `/api/create` endpoint.
- Updated `ConvertToBytes` method for clarity.
- Added `GetDifference` method for date comparisons.
- Enforced length limits on input fields in `index.html`.
This commit is contained in:
whoswhip
2024-08-19 04:46:58 -04:00
parent 47aed18919
commit 59fe4caa4d
2 changed files with 72 additions and 11 deletions
+67 -6
View File
@@ -4,6 +4,7 @@ using System.Threading.RateLimiting;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using System.Data; using System.Data;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Globalization;
class Program class Program
{ {
@@ -120,6 +121,14 @@ class Program
context.Response.StatusCode = 404; context.Response.StatusCode = 404;
return; return;
} }
if (paste.Title == "" || string.IsNullOrEmpty(paste.Title))
{
paste.Title = $"Untitled {reader.GetString(0)}";
}
if (paste.Title.Length > 40)
{
paste.Title = paste.Title.Substring(0, 50) + "...";
}
var html = File.ReadAllText("assets\\paste.html"); var html = File.ReadAllText("assets\\paste.html");
html = html.Replace("{pastetitle}", paste.Title); html = html.Replace("{pastetitle}", paste.Title);
html = html.Replace("{content}", content); html = html.Replace("{content}", content);
@@ -170,7 +179,15 @@ class Program
{ {
paste.Title = $"Untitled {reader.GetString(0)}"; paste.Title = $"Untitled {reader.GetString(0)}";
} }
pastes += $"<a href=\"/{paste.Id}\"><li>{paste.Title} {paste.Date} {ConvertToBytes(paste.Size)}</li></a>"; if (paste.Title.Length > 40)
{
paste.Title = paste.Title.Substring(0, 50) + "...";
}
DateTime date = DateTime.ParseExact(paste.Date, "dd/MM/yyyy-HH:mm:ss", CultureInfo.InvariantCulture);
DateTime now = DateTime.Now;
var difference = GetDifference(date, now);
pastes += $"<a href=\"/{paste.Id}\"><li>{paste.Title} {difference} {ConvertToBytes(paste.Size)}</li></a>";
} }
if(string.IsNullOrEmpty(pastes)) if(string.IsNullOrEmpty(pastes))
{ {
@@ -181,7 +198,7 @@ class Program
await context.Response.WriteAsync(html); await context.Response.WriteAsync(html);
return; return;
} }
}).RequireRateLimiting("fixed"); }).RequireRateLimiting("fixed-bigger");
app.MapGet("/archive", async (HttpContext context) => app.MapGet("/archive", async (HttpContext context) =>
{ {
var html = File.ReadAllText("assets\\archives.html"); var html = File.ReadAllText("assets\\archives.html");
@@ -220,7 +237,14 @@ class Program
{ {
paste.Title = $"Untitled {reader.GetString(0)}"; paste.Title = $"Untitled {reader.GetString(0)}";
} }
pastes += $"<a href=\"/{paste.Id}\"><li>{paste.Title} {paste.Date} {ConvertToBytes(paste.Size)}</li></a>"; if (paste.Title.Length > 40)
{
paste.Title = paste.Title.Substring(0, 50) + "...";
}
DateTime date = DateTime.ParseExact(paste.Date, "dd/MM/yyyy-HH:mm:ss", CultureInfo.InvariantCulture);
DateTime now = DateTime.Now;
var difference = GetDifference(date, now);
pastes += $"<a href=\"/{paste.Id}\"><li>{paste.Title} {difference} {ConvertToBytes(paste.Size)}</li></a>";
} }
var findCountCommand = connection.CreateCommand(); var findCountCommand = connection.CreateCommand();
findCountCommand.CommandText = "SELECT COUNT(*) FROM pastes WHERE Visibility != 'Private'"; findCountCommand.CommandText = "SELECT COUNT(*) FROM pastes WHERE Visibility != 'Private'";
@@ -259,11 +283,11 @@ class Program
app.MapPost("/api/create", async (HttpContext context) => app.MapPost("/api/create", async (HttpContext context) =>
{ {
string requestBody = await new StreamReader(context.Request.Body).ReadToEndAsync(); string requestBody = await new StreamReader(context.Request.Body).ReadToEndAsync();
if (requestBody.Length > 500_000 || string.IsNullOrEmpty(requestBody)) if (string.IsNullOrEmpty(requestBody))
{ {
context.Response.StatusCode = 400; context.Response.StatusCode = 400;
context.Response.ContentType = "application/json"; context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Invalid request body" }.ToString()); await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "No content uploaded" }.ToString());
return; return;
} }
var data = JObject.Parse(requestBody); var data = JObject.Parse(requestBody);
@@ -271,6 +295,14 @@ class Program
var content = SanitizeInput(data["content"]?.ToString() ?? ""); var content = SanitizeInput(data["content"]?.ToString() ?? "");
var visibility = SanitizeInput(data["visibility"]?.ToString() ?? "Public"); var visibility = SanitizeInput(data["visibility"]?.ToString() ?? "Public");
if(content.Length > 500_000 || title.Length > 500)
{
context.Response.StatusCode = 400;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Content or Title is too long" }.ToString());
return;
}
if (visibility != "Public" && visibility != "Unlisted" && visibility != "Private") if (visibility != "Public" && visibility != "Unlisted" && visibility != "Private")
{ {
context.Response.StatusCode = 400; context.Response.StatusCode = 400;
@@ -358,7 +390,7 @@ class Program
{ {
return "0 B"; return "0 B";
} }
string[] sizes = { "B", "KB", "MB", "GB", "TB" }; string[] sizes = { "Bytes", "KB", "MB", "GB", "TB" };
double len = double.Parse(length); double len = double.Parse(length);
int order = 0; int order = 0;
while (len >= 1024 && order < sizes.Length - 1) while (len >= 1024 && order < sizes.Length - 1)
@@ -366,8 +398,37 @@ class Program
order++; order++;
len = len / 1024; len = len / 1024;
} }
if (sizes[order] == "Bytes")
{
return $"{len:0.##} {sizes[order]}"; return $"{len:0.##} {sizes[order]}";
} }
else
{
return $"{len:0.##}{sizes[order]}";
}
}
public static string GetDifference(DateTime startDate, DateTime endDate)
{
TimeSpan span = endDate.Subtract(startDate);
if (span.TotalSeconds < 60)
{
return $"{Math.Round(span.TotalSeconds, 0)} sec ago";
}
else if (span.TotalMinutes < 60)
{
return $"{Math.Round(span.TotalMinutes, 0)} min";
}
else if (span.TotalHours < 24)
{
return $"{Math.Round(span.TotalHours,1)} hrs ago";
}
else
{
return $"{Math.Round(span.TotalDays,1)} days ago";
}
}
public static string GenerateRandomString(int length) public static string GenerateRandomString(int length)
{ {
var random = new Random(); var random = new Random();
+2 -2
View File
@@ -17,9 +17,9 @@
<h1>create paste</h1> <h1>create paste</h1>
<form id="createForm"> <form id="createForm">
<label for="pasteTitle" class="label">Title</label> <label for="pasteTitle" class="label">Title</label>
<input type="text" id="pasteTitle" class="textinput" name="pasteTitle"> <input type="text" id="pasteTitle" class="textinput" name="pasteTitle" maxlength="500">
<label for="pasteContent" class="label">Content</label> <label for="pasteContent" class="label">Content</label>
<textarea id="pasteContent" class="textarea" name="pasteContent" required ></textarea> <textarea id="pasteContent" class="textarea" name="pasteContent" required maxlength="500000"></textarea>
<button type="submit" class="button">Create</button> <button type="submit" class="button">Create</button>
</form> </form>
</div> </div>