mirror of
https://github.com/whoswhip/Sharpbin.git
synced 2026-12-06 02:48:43 +00:00
Finish converting all apis to controllers, static endpoints next.
This commit is contained in:
@@ -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<byte[]> 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<string> 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<byte[]> 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<bool> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -310,7 +310,7 @@ namespace SharpbinV2.Server.Controllers
|
||||
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." });
|
||||
return NotFound(new { success = false, message = "No pastes found." });
|
||||
var pasteList = new List<object>();
|
||||
foreach (var paste in pastes)
|
||||
{
|
||||
|
||||
@@ -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<SiteController> _logger;
|
||||
private readonly DatabaseService _databaseService;
|
||||
public SiteController(ILogger<SiteController> 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 });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<UserController> _logger;
|
||||
private readonly DatabaseService _databaseService;
|
||||
public UserController(ILogger<UserController> logger, DatabaseService databaseService)
|
||||
{
|
||||
_logger = logger;
|
||||
_databaseService = databaseService;
|
||||
}
|
||||
|
||||
[HttpGet("uuid/{uuid}")]
|
||||
public async Task<IActionResult> 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<IActionResult> 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<IActionResult> 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<IActionResult> 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<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,
|
||||
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" });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+10
-163
@@ -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<DatabaseService>();
|
||||
//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<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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}).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();
|
||||
|
||||
@@ -129,6 +129,38 @@ namespace SharpbinV2.Server.Services
|
||||
}
|
||||
}
|
||||
}
|
||||
public async Task<User?> 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<int> EnumeratePastes()
|
||||
{
|
||||
using (var connection = new SqliteConnection(_connectionString))
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
<PackageReference Include="Microsoft.Data.Sqlite" Version="9.0.5" />
|
||||
<PackageReference Include="BCrypt.Net-Next" Version="4.0.3" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
|
||||
<PackageReference Include="UAParser" Version="3.1.47" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user