Improve paste handling and pagination logic

- Updated `PasteController.cs` to enhance visibility parameter handling and added methods for retrieving pastes with pagination and error handling.
- Added `UID` property to the `Paste` class for better identification.
- Refactored `Program.cs` to remove unused namespaces and improve response header handling.
- Enhanced `DatabaseService.cs` with new methods for retrieving pastes and user pastes, including better error handling.
- Adjusted pagination logic in `archive.js` and `dash.js` to start from page 1, improving user interface navigation.
This commit is contained in:
whoswhip
2025-07-08 15:32:17 -04:00
parent 181c401af7
commit ed98238c40
6 changed files with 246 additions and 398 deletions
@@ -40,7 +40,9 @@ namespace SharpbinV2.Server.Controllers
string title = queries.ContainsKey("title") ? queries["title"].ToString() : $"Untitled {await _databaseService.EnumeratePastes()}"; string title = queries.ContainsKey("title") ? queries["title"].ToString() : $"Untitled {await _databaseService.EnumeratePastes()}";
string syntax = queries.ContainsKey("syntax") ? queries["syntax"].ToString() : "none"; string syntax = queries.ContainsKey("syntax") ? queries["syntax"].ToString() : "none";
int visibility = queries.ContainsKey("visibility") ? int.Parse(queries["visibility"]) : 0; int visibility = 0;
if (queries.ContainsKey("visibility") && int.TryParse(queries["visibility"], out int parsedVisibility))
visibility = parsedVisibility;
if (title.Length > 500) if (title.Length > 500)
return BadRequest(new { success = false, message = "Title cannot exceed 500 characters." }); return BadRequest(new { success = false, message = "Title cannot exceed 500 characters." });
@@ -232,5 +234,113 @@ namespace SharpbinV2.Server.Controllers
return StatusCode(500, new { error = "An error occurred while retrieving the paste views." }); return StatusCode(500, new { error = "An error occurred while retrieving the paste views." });
} }
} }
[HttpGet("archive")]
[EnableRateLimiting("general")]
public async Task<IActionResult> GetPastes(int page, int limit)
{
if (page < 1 || limit < 1 || limit > 25)
return BadRequest(new { success = false, message = "Invalid page or limit parameters." });
if (page == 1)
page = 0;
try
{
int pages = await _databaseService.EnumeratePastes() / limit;
if (page > pages)
return BadRequest(new { success = false, message = "Page number exceeds available pages." });
List<Paste?>? pastes = await _databaseService.GetPastes(limit, page, _logger);
if (pastes == null || pastes.Count == 0)
return NotFound(new { success = false, message = "No pastes found." });
var pasteList = new List<object>();
foreach (var paste in pastes)
{
if (paste == null)
continue;
pasteList.Add(new
{
paste.ID,
paste.UUID,
paste.Title,
paste.Syntax,
paste.Visibility,
paste.Created,
paste.Size,
paste.TrueSize,
paste.AuthorUUID
});
}
return Ok(new
{
success = true,
pages,
pastes = pasteList
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Error retrieving pastes archive");
return StatusCode(500, new { error = "An error occurred while retrieving the pastes archive." });
}
}
[HttpGet("my")]
[EnableRateLimiting("general")]
public async Task<IActionResult> GetMyPastes(int page, int limit)
{
var requestDetails = HelperService.GetRequestDetails(HttpContext);
if (string.IsNullOrWhiteSpace(requestDetails.Token) || await _databaseService.GetSession(requestDetails.Token) == null)
return Unauthorized(new { success = false, message = "Invalid or missing authentication token." });
User? user = await _databaseService.UserFromToken(requestDetails.Token ?? "");
if (user == null)
return Unauthorized(new { success = false, message = "User not found." });
if (page < 1 || limit < 1 || limit > 25)
return BadRequest(new { success = false, message = "Invalid page or limit parameters." });
if (page == 1)
page = 0;
try
{
int pages = await _databaseService.EnumerateUserPastes(user) / limit;
if (page > pages)
return BadRequest(new { success = false, message = "Page number exceeds available pages." });
List<Paste?>? pastes = await _databaseService.GetPastesFromUser(user, limit, page, _logger);
if (pastes == null || pastes.Count == 0)
return NotFound(new { success = false, message = "No pastes found for this user." });
var pasteList = new List<object>();
foreach (var paste in pastes)
{
if (paste == null)
continue;
pasteList.Add(new
{
paste.ID,
paste.UUID,
paste.Title,
paste.Syntax,
paste.Visibility,
paste.Created,
paste.Size,
paste.TrueSize,
paste.AuthorUUID
});
}
return Ok(new
{
success = true,
pages,
pastes = pasteList
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Error retrieving user's pastes");
return StatusCode(500, new { error = "An error occurred while retrieving the user's pastes." });
}
}
} }
} }
+1
View File
@@ -2,6 +2,7 @@
{ {
public class Paste public class Paste
{ {
public int UID { get; set; }
public string? UUID { get; set; } public string? UUID { get; set; }
public string? ID { get; set; } public string? ID { get; set; }
public int? Visibility { get; set; } public int? Visibility { get; set; }
+24 -386
View File
@@ -1,8 +1,4 @@
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using Newtonsoft.Json.Linq;
using System.Text;
using Bcrypt = BCrypt.Net.BCrypt;
using UAParser;
using Microsoft.AspNetCore.RateLimiting; using Microsoft.AspNetCore.RateLimiting;
using SharpbinV2.Server.Models; using SharpbinV2.Server.Models;
using SharpbinV2.Server.Services; using SharpbinV2.Server.Services;
@@ -40,7 +36,6 @@ namespace SharpbinV2.Server
"toml", "toml",
"xml" "xml"
}; };
public static JObject Configuration { get; set; }
static async Task Main(string[] args) static async Task Main(string[] args)
{ {
@@ -136,13 +131,12 @@ namespace SharpbinV2.Server
app.MapGet("/", (HttpContext context) => app.MapGet("/", (HttpContext context) =>
{ {
context.Response.StatusCode = 200; context.Response.StatusCode = 200;
context.Response.Headers.Add("Content-Type", "text/html"); context.Response.Headers.Append("Content-Type", "text/html");
return context.Response.SendFileAsync("wwwroot/index.html"); return context.Response.SendFileAsync("wwwroot/index.html");
}).RequireRateLimiting("general"); }).RequireRateLimiting("general");
app.MapGet("/{pasteid}", async (HttpContext context, IWebHostEnvironment env) => app.MapGet("/{pasteid}", async (HttpContext context, IWebHostEnvironment env, string pasteid) =>
{ {
var pasteid = context.Request.RouteValues["pasteid"].ToString() ?? null; if (string.IsNullOrWhiteSpace(pasteid))
if (string.IsNullOrEmpty(pasteid))
{ {
context.Response.StatusCode = 400; context.Response.StatusCode = 400;
context.Response.Redirect("/error?error=400&message=Invalid paste id."); context.Response.Redirect("/error?error=400&message=Invalid paste id.");
@@ -156,26 +150,26 @@ namespace SharpbinV2.Server
switch (Path.GetExtension(filePath)) switch (Path.GetExtension(filePath))
{ {
case "html": case "html":
context.Response.Headers.Add("Content-Type", "text/html"); context.Response.Headers.Append("Content-Type", "text/html");
break; break;
case "css": case "css":
context.Response.Headers.Add("Content-Type", "text/css"); context.Response.Headers.Append("Content-Type", "text/css");
break; break;
case "js": case "js":
context.Response.Headers.Add("Content-Type", "text/javascript"); context.Response.Headers.Append("Content-Type", "text/javascript");
break; break;
case "json": case "json":
context.Response.Headers.Add("Content-Type", "application/json"); context.Response.Headers.Append("Content-Type", "application/json");
break; break;
case "png": case "png":
context.Response.Headers.Add("Content-Type", "image/png"); context.Response.Headers.Append("Content-Type", "image/png");
break; break;
case "jpg": case "jpg":
case "jpeg": case "jpeg":
context.Response.Headers.Add("Content-Type", "image/jpeg"); context.Response.Headers.Append("Content-Type", "image/jpeg");
break; break;
case "ico": case "ico":
context.Response.Headers.Add("Content-Type", "image/x-icon"); context.Response.Headers.Append("Content-Type", "image/x-icon");
break; break;
} }
await context.Response.SendFileAsync(filePath); await context.Response.SendFileAsync(filePath);
@@ -205,17 +199,17 @@ namespace SharpbinV2.Server
{ {
if (!await Database.HasAlreadyViewedFromRqDetails(requestdetails)) if (!await Database.HasAlreadyViewedFromRqDetails(requestdetails))
{ {
await Database.AddViewToPaste(null, paste, requestdetails); await Database.AddViewToPaste(new User { UUID = "0" }, paste, requestdetails);
} }
} }
context.Response.StatusCode = 200; context.Response.StatusCode = 200;
context.Response.Headers.Add("Content-Type", "text/html"); context.Response.Headers.Append("Content-Type", "text/html");
await context.Response.SendFileAsync("wwwroot/paste.html"); await context.Response.SendFileAsync("wwwroot/paste.html");
}).RequireRateLimiting("general"); }).RequireRateLimiting("general");
app.MapGet("/error", async (HttpContext context) => app.MapGet("/error", async (HttpContext context) =>
{ {
context.Response.StatusCode = 400; context.Response.StatusCode = 400;
context.Response.Headers.Add("Content-Type", "text/html"); context.Response.Headers.Append("Content-Type", "text/html");
await context.Response.SendFileAsync("wwwroot/error.html"); await context.Response.SendFileAsync("wwwroot/error.html");
}); });
app.MapGet("/error.html", (HttpContext context) => app.MapGet("/error.html", (HttpContext context) =>
@@ -239,10 +233,10 @@ namespace SharpbinV2.Server
return; return;
} }
context.Response.StatusCode = 200; context.Response.StatusCode = 200;
context.Response.Headers.Add("Content-Type", "text/plain"); context.Response.Headers.Append("Content-Type", "text/plain");
if (paste.FilePath.EndsWith(".gz")) if (paste.FilePath.EndsWith(".gz"))
{ {
context.Response.Headers.Add("Content-Encoding", "gzip"); context.Response.Headers.Append("Content-Encoding", "gzip");
await context.Response.SendFileAsync(paste.FilePath); await context.Response.SendFileAsync(paste.FilePath);
} }
else else
@@ -257,13 +251,13 @@ namespace SharpbinV2.Server
app.MapGet("/archive", async (HttpContext context) => app.MapGet("/archive", async (HttpContext context) =>
{ {
context.Response.StatusCode = 200; context.Response.StatusCode = 200;
context.Response.Headers.Add("Content-Type", "text/html"); context.Response.Headers.Append("Content-Type", "text/html");
await context.Response.SendFileAsync("wwwroot/archive.html"); await context.Response.SendFileAsync("wwwroot/archive.html");
}).RequireRateLimiting("general"); }).RequireRateLimiting("general");
app.MapGet("/dash", async (HttpContext context) => app.MapGet("/dash", async (HttpContext context) =>
{ {
context.Response.StatusCode = 200; context.Response.StatusCode = 200;
context.Response.Headers.Add("Content-Type", "text/html"); context.Response.Headers.Append("Content-Type", "text/html");
await context.Response.SendFileAsync("wwwroot/dash.html"); await context.Response.SendFileAsync("wwwroot/dash.html");
}).RequireRateLimiting("general"); }).RequireRateLimiting("general");
app.MapGet("/dash.html", (HttpContext context) => app.MapGet("/dash.html", (HttpContext context) =>
@@ -273,13 +267,13 @@ namespace SharpbinV2.Server
app.MapGet("/login", async (HttpContext context) => app.MapGet("/login", async (HttpContext context) =>
{ {
context.Response.StatusCode = 200; context.Response.StatusCode = 200;
context.Response.Headers.Add("Content-Type", "text/html"); context.Response.Headers.Append("Content-Type", "text/html");
await context.Response.SendFileAsync("wwwroot/login.html"); await context.Response.SendFileAsync("wwwroot/login.html");
}).RequireRateLimiting("general"); }).RequireRateLimiting("general");
app.MapGet("/register", async (HttpContext context) => app.MapGet("/register", async (HttpContext context) =>
{ {
context.Response.StatusCode = 200; context.Response.StatusCode = 200;
context.Response.Headers.Add("Content-Type", "text/html"); context.Response.Headers.Append("Content-Type", "text/html");
await context.Response.SendFileAsync("wwwroot/register.html"); await context.Response.SendFileAsync("wwwroot/register.html");
}).RequireRateLimiting("general"); }).RequireRateLimiting("general");
app.MapGet("/u/{username}", async (HttpContext context) => app.MapGet("/u/{username}", async (HttpContext context) =>
@@ -293,10 +287,10 @@ namespace SharpbinV2.Server
} }
string html = File.ReadAllText("wwwroot/user.html"); string html = File.ReadAllText("wwwroot/user.html");
context.Response.StatusCode = 200; context.Response.StatusCode = 200;
context.Response.Headers.Add("Content-Type", "text/html"); context.Response.Headers.Append("Content-Type", "text/html");
context.Response.Headers.Add("Cache-Control", "no-cache, no-store, must-revalidate"); context.Response.Headers.Append("Cache-Control", "no-cache, no-store, must-revalidate");
context.Response.Headers.Add("Pragma", "no-cache"); context.Response.Headers.Append("Pragma", "no-cache");
context.Response.Headers.Add("Expires", "0"); context.Response.Headers.Append("Expires", "0");
await context.Response.WriteAsync(html); await context.Response.WriteAsync(html);
@@ -305,7 +299,7 @@ namespace SharpbinV2.Server
app.MapGet("/reset-password", async (HttpContext context) => app.MapGet("/reset-password", async (HttpContext context) =>
{ {
context.Response.StatusCode = 200; context.Response.StatusCode = 200;
context.Response.Headers.Add("Content-Type", "text/html"); context.Response.Headers.Append("Content-Type", "text/html");
await context.Response.SendFileAsync("wwwroot/reset-password.html"); await context.Response.SendFileAsync("wwwroot/reset-password.html");
}).RequireRateLimiting("general"); }).RequireRateLimiting("general");
@@ -314,256 +308,6 @@ namespace SharpbinV2.Server
#region API #region API
app.MapPost("/api/accounts/reset-password", async (HttpContext context) =>
{
var requestdetails = GetRequestDetails(context);
if (string.IsNullOrEmpty(requestdetails.Token))
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, message = "No token provided, not authorized." });
return;
}
var body = await new StreamReader(context.Request.Body).ReadToEndAsync();
if (body == null)
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid Body." });
return;
}
var json = TryParse(body);
if (json == null)
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid JSON." });
return;
}
if (!string.IsNullOrEmpty(json["token"]?.ToString()) && !string.IsNullOrEmpty(json["uuid"]?.ToString()) && !string.IsNullOrEmpty(json["url"]?.ToString()))
{
var password = json["password"]?.ToString();
var uuid = json["uuid"]?.ToString();
var token = json["token"]?.ToString();
var url = json["url"]?.ToString();
if (string.IsNullOrEmpty(uuid) || string.IsNullOrEmpty(token) || string.IsNullOrEmpty(url) || string.IsNullOrEmpty(password))
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, message = "Missing required fields." });
return;
}
var pwreset = await Database.GetPasswordReset(url, uuid, token);
if (pwreset == null)
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid token/url/uuid." });
return;
}
var user = await Database.UserFromUUID(uuid);
if (user == null)
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid user." });
return;
}
var passwordHashed = Bcrypt.HashPassword(password, Bcrypt.GenerateSalt(12));
if (!Database.ResetPassword(user.UUID ?? "", passwordHashed).Result)
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, message = "Failed to reset password." });
return;
}
else
{
context.Response.StatusCode = 200;
await context.Response.WriteAsJsonAsync(new { success = true, message = "Password reset." });
}
return;
}
else // normal password resets from the dashboard
{
var user = await Database.UserFromToken(requestdetails.Token);
if (user == null)
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid token." });
return;
}
var password = json["password"]?.ToString();
if (string.IsNullOrEmpty(password))
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, message = "Missing required fields." });
return;
}
var passwordHashed = Bcrypt.HashPassword(password, Bcrypt.GenerateSalt(12));
if (!Database.ResetPassword(user.UUID ?? "", passwordHashed).Result)
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, message = "Failed to reset password." });
return;
}
else
{
context.Response.StatusCode = 200;
await context.Response.WriteAsJsonAsync(new { success = true, message = "Password reset." });
}
}
}).RequireRateLimiting("auth");
app.MapGet("/api/pastes/archive", async (HttpContext context) =>
{
var queries = context.Request.Query;
if (!queries.ContainsKey("page") && !queries.ContainsKey("limit"))
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, message = "Missing required fields." });
return;
}
var page = queries.ContainsKey("page") ? Convert.ToInt32(queries["page"]) : 0;
var limit = queries.ContainsKey("limit") ? Convert.ToInt32(queries["limit"]) : 10;
int pages = await Database.EnumeratePastes() / limit;
if (page < 0 || limit <= 0 || limit > 25)
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid page or limit." });
return;
}
if (page > pages)
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, message = "Page out of range.", pages });
return;
}
using (var connection = new SqliteConnection(MainDatabaseConnection))
{
await connection.OpenAsync();
using (var command = connection.CreateCommand())
{
command.CommandText = "SELECT * FROM pastes WHERE Visibility NOT IN (1, 2) ORDER BY Created DESC LIMIT @Limit OFFSET @Offset;";
command.Parameters.AddWithValue("@Limit", limit);
command.Parameters.AddWithValue("@Offset", page * limit);
using (var reader = await command.ExecuteReaderAsync())
{
if (!reader.HasRows)
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, message = "No pastes found." });
return;
}
var pastes = new List<object>();
while (await reader.ReadAsync())
{
pastes.Add(new
{
UUID = reader.GetString(1),
ID = reader.GetString(2),
Visibility = reader.GetInt32(3),
Title = reader.IsDBNull(4) ? null : reader.GetString(4),
AuthorUUID = reader.GetString(5),
Created = reader.GetInt64(7),
Edited = reader.GetInt64(8),
Size = reader.GetInt32(9),
TrueSize = reader.GetInt32(10),
Views = reader.GetInt32(11),
Syntax = reader.IsDBNull(12) ? null : reader.GetString(12)
});
}
context.Response.StatusCode = 200;
await context.Response.WriteAsJsonAsync(new { success = true, pastes, pages });
return;
}
}
}
}).RequireRateLimiting("general");
app.MapGet("/api/pastes/my", async (HttpContext context) =>
{
var requestdetails = GetRequestDetails(context);
if (string.IsNullOrEmpty(requestdetails.Token))
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, message = "Not authorized." });
return;
}
var user = await Database.UserFromToken(requestdetails.Token);
if (user == null)
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid token." });
return;
}
var queries = context.Request.Query;
if (!queries.ContainsKey("page") && !queries.ContainsKey("limit"))
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, message = "Missing required fields." });
return;
}
var page = queries.ContainsKey("page") ? Convert.ToInt32(queries["page"]) : 0;
var limit = queries.ContainsKey("limit") ? Convert.ToInt32(queries["limit"]) : 10;
if (page < 0 || limit <= 0 || limit > 25)
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid page or limit." });
return;
}
int pages = await Database.EnumerateUserPastes(user) / limit;
if (page > pages)
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, message = "Page out of range.", pages });
return;
}
using (var connection = new SqliteConnection(MainDatabaseConnection))
{
await connection.OpenAsync();
using (var command = connection.CreateCommand())
{
command.CommandText = "SELECT * FROM pastes WHERE AuthorUUID = @AuthorUUID ORDER BY Created DESC LIMIT @Limit OFFSET @Offset;";
command.Parameters.AddWithValue("@AuthorUUID", user.UUID);
command.Parameters.AddWithValue("@Limit", limit);
command.Parameters.AddWithValue("@Offset", page * limit);
using (var reader = await command.ExecuteReaderAsync())
{
if (!reader.HasRows)
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, error = true, message = "No pastes found." });
return;
}
var pastes = new List<Paste>();
while (await reader.ReadAsync())
{
pastes.Add(new Paste
{
UUID = reader.GetString(1),
ID = reader.GetString(2),
Visibility = reader.GetInt32(3),
Title = reader.IsDBNull(4) ? null : reader.GetString(4),
AuthorUUID = reader.GetString(5),
Created = reader.GetInt64(7),
Edited = reader.GetInt64(8),
Size = reader.GetInt32(9),
TrueSize = reader.GetInt32(10),
Views = reader.GetInt32(11),
Syntax = reader.IsDBNull(12) ? null : reader.GetString(12)
});
}
context.Response.StatusCode = 200;
await context.Response.WriteAsJsonAsync(new { success = true, pastes, pages });
return;
}
}
}
});
app.MapGet("/api/users/uuid/{uuid}", async (HttpContext context) => app.MapGet("/api/users/uuid/{uuid}", async (HttpContext context) =>
{ {
var uuid = context.Request.RouteValues["uuid"].ToString() ?? null; var uuid = context.Request.RouteValues["uuid"].ToString() ?? null;
@@ -720,66 +464,6 @@ namespace SharpbinV2.Server
await context.Response.WriteAsJsonAsync(new { success = true, info }); await context.Response.WriteAsJsonAsync(new { success = true, info });
}).RequireRateLimiting("general"); }).RequireRateLimiting("general");
app.MapGet("/admin/{useruuid}/reset-password", async (HttpContext context) =>
{
var requestdetails = GetRequestDetails(context);
var user = await Database.UserFromToken(requestdetails.Token);
if (user == null)
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid token." });
return;
}
if (user.Type != 255)
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, message = "Not authorized." });
return;
}
var useruuid = context.Request.RouteValues["useruuid"].ToString() ?? null;
if (string.IsNullOrEmpty(useruuid))
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid UUID." });
return;
}
var targetuser = await Database.UserFromUUID(useruuid);
if (targetuser == null)
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, message = "User not found." });
return;
}
string uuid = Guid.NewGuid().ToString();
string url = GenerateRandomString(32);
string token = GenerateToken();
using (var connection = new SqliteConnection(MainDatabaseConnection))
{
await connection.OpenAsync();
var expiry = DateTimeOffset.UtcNow.AddHours(1).ToUnixTimeSeconds();
using (var command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO passwordresets (UUID, USERUUID, URL, Token,Created, Expirary) VALUES (@UUID, @USERUUID, @URL, @Token,@Created, @Expirary);";
command.Parameters.AddWithValue("@UUID", uuid);
command.Parameters.AddWithValue("@USERUUID", targetuser.UUID);
command.Parameters.AddWithValue("@URL", url);
command.Parameters.AddWithValue("@Token", token);
command.Parameters.AddWithValue("@Created", DateTimeOffset.UtcNow.ToUnixTimeSeconds());
command.Parameters.AddWithValue("@Expirary", expiry);
await command.ExecuteNonQueryAsync();
}
await connection.CloseAsync();
}
var resetlink = $"{context.Request.Scheme}://{context.Request.Host}/reset-password?uuid={uuid}&url={url}&token={token}";
context.Response.StatusCode = 200;
context.Response.Headers.Add("Content-Type", "application/json");
await context.Response.WriteAsJsonAsync(new { success = true, resetlink, uuid, url, token });
});
#endregion #endregion
app.MapControllers(); app.MapControllers();
@@ -789,40 +473,6 @@ namespace SharpbinV2.Server
} }
#region Helper Functions #region Helper Functions
static JObject TryParse(string json)
{
try
{
return JObject.Parse(json);
}
catch (Exception ex)
{
return null;
}
}
static JArray TryParseArray(string json)
{
try
{
return JArray.Parse(json);
}
catch (Exception ex)
{
return null;
}
}
static string GenerateToken()
{
string randomstring = GenerateRandomString(32);
string randomguid = Guid.NewGuid().ToString();
return Convert.ToBase64String(Encoding.UTF8.GetBytes(Bcrypt.HashPassword(randomstring + randomguid, Bcrypt.GenerateSalt(10))));
}
static string GenerateRandomString(int length)
{
var random = new Random();
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
return new string(Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)]).ToArray());
}
static RequestDetails GetRequestDetails(HttpContext context) static RequestDetails GetRequestDetails(HttpContext context)
{ {
var requestdetails = new RequestDetails(); var requestdetails = new RequestDetails();
@@ -852,18 +502,6 @@ namespace SharpbinV2.Server
return requestdetails; return requestdetails;
} }
static string FormatBytes(long bytes)
{
string[] sizes = { "B", "KB", "MB", "GB", "TB" };
double len = bytes;
int order = 0;
while (len >= 1024 && order < sizes.Length - 1)
{
order++;
len = len / 1024;
}
return $"{len:0.##} {sizes[order]}";
}
#endregion #endregion
static async Task Initialize() static async Task Initialize()
{ {
+100 -1
View File
@@ -546,7 +546,7 @@ namespace SharpbinV2.Server.Services
{ {
if (!reader.HasRows) if (!reader.HasRows)
return null; return null;
var views = new List<View>(); var views = new List<View?>();
while (await reader.ReadAsync()) while (await reader.ReadAsync())
{ {
views.Add(new View views.Add(new View
@@ -569,5 +569,104 @@ namespace SharpbinV2.Server.Services
return null; return null;
} }
} }
public async Task<List<Paste?>?> GetPastes(int limit, int page, ILogger logger)
{
if (limit <= 0 || page < 0)
return null;
try
{
using (var connection = new SqliteConnection(_connectionString))
{
await connection.OpenAsync();
using (var command = connection.CreateCommand())
{
command.CommandText = "SELECT * FROM pastes WHERE Visibility NOT IN (1,2) ORDER BY Created DESC LIMIT @Limit OFFSET @Offset;";
command.Parameters.AddWithValue("@Limit", limit);
command.Parameters.AddWithValue("@Offset", limit * page);
using (var reader = await command.ExecuteReaderAsync())
{
if (!reader.HasRows)
return null;
var pastes = new List<Paste?>();
while (await reader.ReadAsync())
{
pastes.Add(new Paste
{
UID = reader.GetInt32(0),
UUID = reader.GetString(1),
ID = reader.GetString(2),
Visibility = reader.GetInt32(3),
Title = reader.IsDBNull(4) ? null : reader.GetString(4),
AuthorUUID = reader.GetString(5),
FilePath = reader.GetString(6),
Created = reader.GetInt64(7),
Edited = reader.GetInt64(8),
Size = reader.GetInt32(9),
TrueSize = reader.GetInt32(10),
Views = reader.GetInt32(11),
Syntax = reader.IsDBNull(12) ? null : reader.GetString(12)
});
}
return pastes;
}
}
}
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to get pastes from database.");
return null;
}
}
public async Task<List<Paste?>?> GetPastesFromUser(User user, int limit, int page, ILogger logger)
{
if (user == null || limit <= 0 || page < 0)
return null;
try
{
using (var connection = new SqliteConnection(_connectionString))
{
await connection.OpenAsync();
using (var command = connection.CreateCommand())
{
command.CommandText = "SELECT * FROM pastes WHERE AuthorUUID = @AuthorUUID ORDER BY Created DESC LIMIT @Limit OFFSET @Offset;";
command.Parameters.AddWithValue("@AuthorUUID", user.UUID);
command.Parameters.AddWithValue("@Limit", limit);
command.Parameters.AddWithValue("@Offset", limit * page);
using (var reader = await command.ExecuteReaderAsync())
{
if (!reader.HasRows)
return null;
var pastes = new List<Paste?>();
while (await reader.ReadAsync())
{
pastes.Add(new Paste
{
UID = reader.GetInt32(0),
UUID = reader.GetString(1),
ID = reader.GetString(2),
Visibility = reader.GetInt32(3),
Title = reader.IsDBNull(4) ? null : reader.GetString(4),
AuthorUUID = reader.GetString(5),
FilePath = reader.GetString(6),
Created = reader.GetInt64(7),
Edited = reader.GetInt64(8),
Size = reader.GetInt32(9),
TrueSize = reader.GetInt32(10),
Views = reader.GetInt32(11),
Syntax = reader.IsDBNull(12) ? null : reader.GetString(12)
});
}
return pastes;
}
}
}
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to get user pastes from database.");
return null;
}
}
} }
} }
+8 -8
View File
@@ -1,5 +1,5 @@
let pages = 0; let pages = 1;
let currentPage = 0; let currentPage = 1;
let limit = 25; let limit = 25;
async function renderArchive(page, limit) { async function renderArchive(page, limit) {
@@ -35,9 +35,9 @@ async function renderArchive(page, limit) {
pages = archiveData.pages; pages = archiveData.pages;
currentPage = page; currentPage = page;
pagesElement.innerText = `${page + 1}/${pages}`; pagesElement.innerText = `${page}/${pages}`;
previousButton.disabled = page <= 0; previousButton.disabled = page <= 1;
nextButton.disabled = page + 1 >= pages; nextButton.disabled = page >= pages;
let archiveListHTML = ""; let archiveListHTML = "";
if (pastes.length === 0) { if (pastes.length === 0) {
@@ -70,7 +70,7 @@ document.addEventListener('DOMContentLoaded', async () => {
let page = parseInt(queries.get("page")); let page = parseInt(queries.get("page"));
limit = parseInt(queries.get("limit")); limit = parseInt(queries.get("limit"));
if (isNaN(page) || page < 0) page = 0; if (isNaN(page) || page < 1) page = 1;
if (isNaN(limit) || limit < 1 || limit > 25) limit = 25; if (isNaN(limit) || limit < 1 || limit > 25) limit = 25;
await renderArchive(page, limit); await renderArchive(page, limit);
@@ -119,13 +119,13 @@ function formatDate(unix, relative = false) {
} }
function nextPage() { function nextPage() {
if (currentPage + 1 >= pages) return; if (currentPage >= pages) return;
currentPage++; currentPage++;
updateUrlAndRender(); updateUrlAndRender();
} }
function previousPage() { function previousPage() {
if (currentPage <= 0) return; if (currentPage <= 1) return;
currentPage--; currentPage--;
updateUrlAndRender(); updateUrlAndRender();
} }
+2 -2
View File
@@ -1,5 +1,5 @@
let currentPage = 1; let currentPage = 1;
let totalPages = 0; let totalPages = 1;
let pastesPerPage = 10; let pastesPerPage = 10;
let userPastes = []; let userPastes = [];
@@ -63,7 +63,7 @@ function formatDate(date, minutes = false) {
async function fetchUserPastes() { async function fetchUserPastes() {
try { try {
const response = await fetch('/api/pastes/my?page=0&limit=15'); const response = await fetch('/api/pastes/my?page=1&limit=15');
const pastesData = await response.json(); const pastesData = await response.json();
if (pastesData.message === 'No pastes found.' || pastesData.message === 'Page out of range.') { if (pastesData.message === 'No pastes found.' || pastesData.message === 'Page out of range.') {