diff --git a/SharpbinV2.Server/Compression.cs b/SharpbinV2.Server/Compression.cs deleted file mode 100644 index 07f130d..0000000 --- a/SharpbinV2.Server/Compression.cs +++ /dev/null @@ -1,73 +0,0 @@ -using System.IO.Compression; -using System.Text; - -namespace SharpbinV2.Server -{ - public class Compression - { - // Taken from old branch - public static async Task CompressString(string text) - { - byte[] compressedBytes; - using (var ms = new MemoryStream()) - { - using (var cs = new GZipStream(ms, CompressionMode.Compress)) - { - byte[] inputBytes = Encoding.UTF8.GetBytes(text); - await cs.WriteAsync(inputBytes, 0, inputBytes.Length); - } - compressedBytes = ms.ToArray(); - } - return compressedBytes; - } - public static async Task DecompressByteArrayToString(byte[] compressedBytes) - { - string decompressedText; - using (var ms = new MemoryStream(compressedBytes)) - { - using (var cs = new GZipStream(ms, CompressionMode.Decompress)) - { - using (var sr = new StreamReader(cs)) - { - decompressedText = await sr.ReadToEndAsync(); - } - } - } - return decompressedText; - } - public static async Task DecompressByteArray(byte[] compressedBytes) - { - byte[] decompressedBytes; - using (var ms = new MemoryStream(compressedBytes)) - { - using (var cs = new GZipStream(ms, CompressionMode.Decompress)) - { - using (var msDecompressed = new MemoryStream()) - { - await cs.CopyToAsync(msDecompressed); - decompressedBytes = msDecompressed.ToArray(); - } - } - } - return decompressedBytes; - } - public static async Task ShouldCompress(string text, int sizeThreshold = 512, double ratioThreshold = 0.8) - { - if (string.IsNullOrEmpty(text)) - return false; - - byte[] inputBytes = Encoding.UTF8.GetBytes(text); - if (inputBytes.Length < sizeThreshold) - return false; - - byte[] compressedBytes = await CompressString(text).ConfigureAwait(false); - double compressionRatio = (double)compressedBytes.Length / inputBytes.Length; - - return compressionRatio < ratioThreshold; - } - public static bool IsCompressed(byte[] data) - { - return data.Length >= 2 && data[0] == 0x1F && data[1] == 0x8B; - } - } -} diff --git a/SharpbinV2.Server/Controllers/PasteController.cs b/SharpbinV2.Server/Controllers/PasteController.cs index c8aba06..d5885a6 100644 --- a/SharpbinV2.Server/Controllers/PasteController.cs +++ b/SharpbinV2.Server/Controllers/PasteController.cs @@ -310,7 +310,7 @@ namespace SharpbinV2.Server.Controllers return BadRequest(new { success = false, message = "Page number exceeds available pages." }); List? 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." }); + return NotFound(new { success = false, message = "No pastes found." }); var pasteList = new List(); foreach (var paste in pastes) { diff --git a/SharpbinV2.Server/Controllers/SiteController.cs b/SharpbinV2.Server/Controllers/SiteController.cs new file mode 100644 index 0000000..13e476c --- /dev/null +++ b/SharpbinV2.Server/Controllers/SiteController.cs @@ -0,0 +1,30 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; +using SharpbinV2.Server.Services; + +namespace SharpbinV2.Server.Controllers +{ + [ApiController] + [Route("api/site")] + public class SiteController : Controller + { + private readonly ILogger _logger; + private readonly DatabaseService _databaseService; + public SiteController(ILogger logger, DatabaseService databaseService) + { + _logger = logger; + _databaseService = databaseService; + } + + [HttpGet("info")] + [EnableRateLimiting("general")] + public IActionResult GetInfo() + { + var info = new + { + Program.MaxFileSize, + }; + return Ok(new { success = true, info }); + } + } +} diff --git a/SharpbinV2.Server/Controllers/UserController.cs b/SharpbinV2.Server/Controllers/UserController.cs new file mode 100644 index 0000000..529251d --- /dev/null +++ b/SharpbinV2.Server/Controllers/UserController.cs @@ -0,0 +1,182 @@ +using Microsoft.AspNetCore.Mvc; +using SharpbinV2.Server.Services; + +namespace SharpbinV2.Server.Controllers +{ + [ApiController] + [Route("api/users")] + public class UserController : Controller + { + private readonly ILogger _logger; + private readonly DatabaseService _databaseService; + public UserController(ILogger logger, DatabaseService databaseService) + { + _logger = logger; + _databaseService = databaseService; + } + + [HttpGet("uuid/{uuid}")] + public async Task GetUserByUuid(string uuid) + { + try + { + if (string.IsNullOrWhiteSpace(uuid)) + return BadRequest(new { success = false, message = "UUID cannot be null or empty" }); + + var user = await _databaseService.UserFromUUID(uuid); + if (user == null) + { + _logger.LogWarning("User not found for UUID: {Uuid}", uuid); + return NotFound(new { success = false, message = "User not found" }); + } + + return Ok(new + { + success = true, + user = new + { + user.UID, + user.UUID, + user.Username, + user.DisplayName, + user.Created, + user.LastLogin, + } + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error retrieving user by UUID: {Uuid}", uuid); + return StatusCode(500, new { success= false, message = "Internal server error" }); + } + } + + [HttpGet("uid/{uid}")] + public async Task GetUserByUID(int uid) + { + try + { + if (uid <= 0) + return BadRequest(new { success = false, message = "UID must be a positive integer" }); + var user = await _databaseService.UserFromUID(uid); + if (user == null) + { + _logger.LogWarning("User not found for UID: {Uid}", uid); + return NotFound(new { success = false, message = "User not found" }); + } + return Ok(new + { + success = true, + user = new + { + user.UID, + user.UUID, + user.Username, + user.DisplayName, + user.Created, + user.LastLogin, + } + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error retrieving user by UID: {Uid}", uid); + return StatusCode(500, new { success= false, message = "Internal server error" }); + } + } + + [HttpGet("username/{username}")] + public async Task GetUserByUsername(string username) + { + try + { + if (string.IsNullOrWhiteSpace(username)) + return BadRequest(new { success = false, message = "Username cannot be null or empty" }); + var user = await _databaseService.UserFromUsername(username); + if (user == null) + { + _logger.LogWarning("User not found for username: {Username}", username); + return NotFound(new { success = false, message = "User not found" }); + } + return Ok(new + { + success = true, + user = new + { + user.UID, + user.UUID, + user.Username, + user.DisplayName, + user.Created, + user.LastLogin, + } + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error retrieving user by username: {Username}", username); + return StatusCode(500, new { success= false, message = "Internal server error" }); + } + } + + [HttpGet("{uuid}/pastes")] + public async Task GetUserPastes(string uuid, int limit, int page) + { + try + { + if (string.IsNullOrWhiteSpace(uuid)) + return BadRequest(new { success = false, message = "UUID cannot be null or empty" }); + if (limit <= 0 || page < 0) + return BadRequest(new { success = false, message = "Invalid pagination parameters" }); + if (page == 1) page = 0; + + var user = await _databaseService.UserFromUUID(uuid); + if (user == null) + { + _logger.LogWarning("User not found for UUID: {Uuid}", uuid); + return NotFound(new { success = false, message = "User not found" }); + } + + int pages = await _databaseService.EnumerateUserPastes(user) / limit; + if (page > pages) + return BadRequest(new { success = false, message = "Page number exceeds available pages" }); + + var pastes = await _databaseService.GetPastesFromUser(user, limit, page, _logger); + if (pastes == null || pastes.Count == 0) + return Ok(new { success = false, message = "No pastes found for this user."}); + + var pasteList = new List(); + 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, + pastes = pasteList, + pages + }); + + } + catch (Exception ex) + { + _logger.LogError(ex, "Error retrieving pastes for user UUID: {Uuid}", uuid); + return StatusCode(500, new { success= false, message = "Internal server error" }); + } + } + } +} diff --git a/SharpbinV2.Server/Program.cs b/SharpbinV2.Server/Program.cs index 5c6cefd..753e12d 100644 --- a/SharpbinV2.Server/Program.cs +++ b/SharpbinV2.Server/Program.cs @@ -55,7 +55,7 @@ namespace SharpbinV2.Server builder.WebHost.ConfigureKestrel(options => { - options.Limits.MaxRequestBodySize = null; + options.Limits.MaxRequestBodySize = MaxFileSize; }); builder.Services.AddRateLimiter(options => @@ -100,6 +100,8 @@ namespace SharpbinV2.Server builder.Services.AddResponseCompression(); builder.Services.AddControllers(); builder.Services.AddScoped(); + //builder.Services.AddEndpointsApiExplorer(); + //builder.Services.AddSwaggerGen(); var app = builder.Build(); @@ -109,8 +111,15 @@ namespace SharpbinV2.Server { app.UseExceptionHandler("/Error"); app.UseHsts(); + } + //if (app.Environment.IsDevelopment()) + //{ + // app.UseSwagger(); + // app.UseSwaggerUI(); + //} + //app.UseHttpsRedirection(); app.UseRouting(); @@ -302,168 +311,6 @@ namespace SharpbinV2.Server context.Response.Headers.Append("Content-Type", "text/html"); await context.Response.SendFileAsync("wwwroot/reset-password.html"); }).RequireRateLimiting("general"); - - - #endregion - - #region API - - app.MapGet("/api/users/uuid/{uuid}", async (HttpContext context) => - { - var uuid = context.Request.RouteValues["uuid"].ToString() ?? null; - if (string.IsNullOrEmpty(uuid)) - { - context.Response.StatusCode = 400; - await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid UUID." }); - return; - } - var user = await Database.UserFromUUID(uuid); - if (user == null) - { - context.Response.StatusCode = 400; - await context.Response.WriteAsJsonAsync(new { success = false, message = "User not found." }); - return; - } - - context.Response.StatusCode = 200; - await context.Response.WriteAsJsonAsync(new - { - success = true, - user = new - { - user.UID, - user.UUID, - user.Username, - user.DisplayName, - user.Created, - user.LastLogin - } - }); - }).RequireRateLimiting("general"); - app.MapGet("/api/users/{username}", async (HttpContext context) => - { - var username = context.Request.RouteValues["username"].ToString() ?? null; - if (string.IsNullOrEmpty(username)) - { - context.Response.StatusCode = 400; - await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid Username." }); - return; - } - var user = await Database.UserFromUsername(username); - if (user == null) - { - context.Response.StatusCode = 400; - await context.Response.WriteAsJsonAsync(new { success = false, message = "User not found." }); - return; - } - context.Response.StatusCode = 200; - await context.Response.WriteAsJsonAsync(new - { - success = true, - user = new - { - user.UID, - user.UUID, - user.Username, - user.DisplayName, - user.Created, - user.LastLogin - } - }); - }).RequireRateLimiting("general"); - app.MapGet("/api/users/{uuid}/pastes", async (HttpContext context) => - { - var uuid = context.Request.RouteValues["uuid"].ToString() ?? null; - if (string.IsNullOrEmpty(uuid)) - { - context.Response.StatusCode = 400; - await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid UUID." }); - return; - } - var user = await Database.UserFromUUID(uuid); - if (user == null) - { - context.Response.StatusCode = 400; - await context.Response.WriteAsJsonAsync(new { success = false, message = "User not found." }); - 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 AND Visibility NOT IN (1, 2) 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(); - 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; - } - } - - } - }).RequireRateLimiting("general"); - - app.MapGet("/api/site/info", async (HttpContext context) => - { - context.Response.StatusCode = 200; - var info = new - { - MaxFileSize - }; - await context.Response.WriteAsJsonAsync(new { success = true, info }); - }).RequireRateLimiting("general"); - #endregion app.MapControllers(); diff --git a/SharpbinV2.Server/Services/DatabaseService.cs b/SharpbinV2.Server/Services/DatabaseService.cs index 2a80300..af717c9 100644 --- a/SharpbinV2.Server/Services/DatabaseService.cs +++ b/SharpbinV2.Server/Services/DatabaseService.cs @@ -129,6 +129,38 @@ namespace SharpbinV2.Server.Services } } } + public async Task UserFromUID(int uid) + { + if (uid <= 0) + return null; + using (var connection = new SqliteConnection(_connectionString)) + { + await connection.OpenAsync(); + using (var command = connection.CreateCommand()) + { + command.CommandText = "SELECT * FROM users WHERE UID = @UID;"; + command.Parameters.AddWithValue("@UID", uid); + using (var reader = await command.ExecuteReaderAsync()) + { + if (!reader.HasRows) + return null; + await reader.ReadAsync(); + return new User + { + UID = reader.GetInt32(0), + UUID = reader.GetString(1), + Type = reader.GetInt32(2), + Email = reader.IsDBNull(3) ? null : reader.GetString(3), + Username = reader.GetString(4), + DisplayName = reader.IsDBNull(5) ? null : reader.GetString(5), + Password = reader.GetString(6), + Created = reader.GetInt64(7), + LastLogin = reader.GetInt64(8) + }; + } + } + } + } public async Task EnumeratePastes() { using (var connection = new SqliteConnection(_connectionString)) diff --git a/SharpbinV2.Server/SharpbinV2.Server.csproj b/SharpbinV2.Server/SharpbinV2.Server.csproj index 24b6a25..6df57f3 100644 --- a/SharpbinV2.Server/SharpbinV2.Server.csproj +++ b/SharpbinV2.Server/SharpbinV2.Server.csproj @@ -18,7 +18,7 @@ - +