mirror of
https://github.com/whoswhip/Sharpbin.git
synced 2026-12-06 02:48:43 +00:00
Convert all static endpoints into a controller
This commit is contained in:
@@ -0,0 +1,203 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using SharpbinV2.Server.Services;
|
||||
using SharpbinV2.Server.Models;
|
||||
|
||||
namespace SharpbinV2.Server.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("")]
|
||||
public class StaticController : Controller
|
||||
{
|
||||
private readonly ILogger<StaticController> _logger;
|
||||
private readonly DatabaseService _databaseService;
|
||||
private readonly IWebHostEnvironment _environment;
|
||||
|
||||
public StaticController(ILogger<StaticController> logger, DatabaseService databaseService, IWebHostEnvironment environment)
|
||||
{
|
||||
_logger = logger;
|
||||
_databaseService = databaseService;
|
||||
_environment = environment;
|
||||
}
|
||||
|
||||
[HttpGet("")]
|
||||
[EnableRateLimiting("general")]
|
||||
public IActionResult Index()
|
||||
{
|
||||
Response.StatusCode = 200;
|
||||
Response.Headers.Append("Content-Type", "text/html");
|
||||
return PhysicalFile(Path.Combine(_environment.WebRootPath, "index.html"), "text/html");
|
||||
}
|
||||
|
||||
[HttpGet("{pasteid}")]
|
||||
[EnableRateLimiting("general")]
|
||||
public async Task<IActionResult> GetPaste(string pasteid)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(pasteid))
|
||||
{
|
||||
return Redirect("/error?error=400&message=Invalid paste id.");
|
||||
}
|
||||
|
||||
var filePath = Path.Combine(_environment.WebRootPath, pasteid);
|
||||
if (System.IO.File.Exists(filePath))
|
||||
{
|
||||
var contentType = GetContentType(Path.GetExtension(filePath));
|
||||
return PhysicalFile(filePath, contentType);
|
||||
}
|
||||
|
||||
var paste = await _databaseService.GetPasteFromID(pasteid);
|
||||
if (paste == null)
|
||||
{
|
||||
return Redirect("/error?error=400&message=Paste not found.");
|
||||
}
|
||||
|
||||
var requestDetails = HelperService.GetRequestDetails(HttpContext);
|
||||
var user = await _databaseService.UserFromToken(requestDetails.Token ?? "");
|
||||
|
||||
if (user != null)
|
||||
{
|
||||
if (user.UUID != paste.AuthorUUID)
|
||||
{
|
||||
if (!await _databaseService.HasAlreadyViewedFromUserDetails(user))
|
||||
{
|
||||
await _databaseService.AddViewToPaste(user, paste, requestDetails);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!await _databaseService.AlreadyViewed(requestDetails))
|
||||
{
|
||||
await _databaseService.AddViewToPaste(new User { UUID = "0" }, paste, requestDetails);
|
||||
}
|
||||
}
|
||||
|
||||
Response.Headers.Append("Content-Type", "text/html");
|
||||
return PhysicalFile(Path.Combine(_environment.WebRootPath, "paste.html"), "text/html");
|
||||
}
|
||||
|
||||
[HttpGet("error")]
|
||||
public IActionResult Error()
|
||||
{
|
||||
Response.StatusCode = 400;
|
||||
Response.Headers.Append("Content-Type", "text/html");
|
||||
return PhysicalFile(Path.Combine(_environment.WebRootPath, "error.html"), "text/html");
|
||||
}
|
||||
|
||||
[HttpGet("error.html")]
|
||||
public IActionResult ErrorHtml()
|
||||
{
|
||||
return Redirect("/error");
|
||||
}
|
||||
|
||||
[HttpGet("raw/{pasteid}")]
|
||||
[EnableRateLimiting("general")]
|
||||
public async Task<IActionResult> GetRawPaste(string pasteid)
|
||||
{
|
||||
if (string.IsNullOrEmpty(pasteid))
|
||||
{
|
||||
return Redirect("/error?error=400&message=Invalid paste id.");
|
||||
}
|
||||
|
||||
var paste = await _databaseService.GetPasteFromID(pasteid);
|
||||
if (paste == null || paste.FilePath == null)
|
||||
{
|
||||
return Redirect("/error?error=400&message=Paste not found.");
|
||||
}
|
||||
|
||||
Response.Headers.Append("Content-Type", "text/plain");
|
||||
if (paste.FilePath.EndsWith(".gz"))
|
||||
{
|
||||
Response.Headers.Append("Content-Encoding", "gzip");
|
||||
}
|
||||
|
||||
return PhysicalFile(paste.FilePath, "text/plain");
|
||||
}
|
||||
|
||||
[HttpGet("paste.html")]
|
||||
public IActionResult PasteHtml()
|
||||
{
|
||||
return Redirect("/");
|
||||
}
|
||||
|
||||
[HttpGet("archive")]
|
||||
[EnableRateLimiting("general")]
|
||||
public IActionResult Archive()
|
||||
{
|
||||
Response.Headers.Append("Content-Type", "text/html");
|
||||
return PhysicalFile(Path.Combine(_environment.WebRootPath, "archive.html"), "text/html");
|
||||
}
|
||||
|
||||
[HttpGet("dash")]
|
||||
[EnableRateLimiting("general")]
|
||||
public IActionResult Dashboard()
|
||||
{
|
||||
Response.Headers.Append("Content-Type", "text/html");
|
||||
return PhysicalFile(Path.Combine(_environment.WebRootPath, "dash.html"), "text/html");
|
||||
}
|
||||
|
||||
[HttpGet("dash.html")]
|
||||
public IActionResult DashboardHtml()
|
||||
{
|
||||
return Redirect("/dash");
|
||||
}
|
||||
|
||||
[HttpGet("login")]
|
||||
[EnableRateLimiting("general")]
|
||||
public IActionResult Login()
|
||||
{
|
||||
Response.Headers.Append("Content-Type", "text/html");
|
||||
return PhysicalFile(Path.Combine(_environment.WebRootPath, "login.html"), "text/html");
|
||||
}
|
||||
|
||||
[HttpGet("register")]
|
||||
[EnableRateLimiting("general")]
|
||||
public IActionResult Register()
|
||||
{
|
||||
Response.Headers.Append("Content-Type", "text/html");
|
||||
return PhysicalFile(Path.Combine(_environment.WebRootPath, "register.html"), "text/html");
|
||||
}
|
||||
|
||||
[HttpGet("u/{username}")]
|
||||
[EnableRateLimiting("general")]
|
||||
public async Task<IActionResult> UserProfile(string username)
|
||||
{
|
||||
if (string.IsNullOrEmpty(username))
|
||||
{
|
||||
return Redirect("/error?error=400&message=Invalid username.");
|
||||
}
|
||||
|
||||
string html = await System.IO.File.ReadAllTextAsync(Path.Combine(_environment.WebRootPath, "user.html"));
|
||||
|
||||
Response.Headers.Append("Content-Type", "text/html");
|
||||
Response.Headers.Append("Cache-Control", "no-cache, no-store, must-revalidate");
|
||||
Response.Headers.Append("Pragma", "no-cache");
|
||||
Response.Headers.Append("Expires", "0");
|
||||
|
||||
return Content(html, "text/html");
|
||||
}
|
||||
|
||||
[HttpGet("reset-password")]
|
||||
[EnableRateLimiting("general")]
|
||||
public IActionResult ResetPassword()
|
||||
{
|
||||
Response.Headers.Append("Content-Type", "text/html");
|
||||
return PhysicalFile(Path.Combine(_environment.WebRootPath, "reset-password.html"), "text/html");
|
||||
}
|
||||
|
||||
private static string GetContentType(string extension)
|
||||
{
|
||||
return extension.ToLowerInvariant() switch
|
||||
{
|
||||
".html" => "text/html",
|
||||
".css" => "text/css",
|
||||
".js" => "text/javascript",
|
||||
".json" => "application/json",
|
||||
".png" => "image/png",
|
||||
".jpg" or ".jpeg" => "image/jpeg",
|
||||
".ico" => "image/x-icon",
|
||||
_ => "application/octet-stream"
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,337 +0,0 @@
|
||||
using BCrypt.Net;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using SharpbinV2.Server.Models;
|
||||
using Bcrypt = BCrypt.Net.BCrypt;
|
||||
|
||||
namespace SharpbinV2.Server
|
||||
{
|
||||
public class Database
|
||||
{
|
||||
public static async Task<User> UserFromUsername(string username)
|
||||
{
|
||||
if (string.IsNullOrEmpty(username))
|
||||
return null;
|
||||
using (var connection = new SqliteConnection(Program.MainDatabaseConnection))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "SELECT * FROM users WHERE Username = @Username;";
|
||||
command.Parameters.AddWithValue("@Username", username);
|
||||
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 static async Task<User> UserFromUUID(string uuid)
|
||||
{
|
||||
if (string.IsNullOrEmpty(uuid))
|
||||
return null;
|
||||
using (var connection = new SqliteConnection(Program.MainDatabaseConnection))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "SELECT * FROM users WHERE UUID = @UUID;";
|
||||
command.Parameters.AddWithValue("@UUID", uuid);
|
||||
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 static async Task<User> UserFromEmail(string email)
|
||||
{
|
||||
if (string.IsNullOrEmpty(email))
|
||||
return null;
|
||||
using (var connection = new SqliteConnection(Program.MainDatabaseConnection))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "SELECT * FROM users WHERE Email = @Email;";
|
||||
command.Parameters.AddWithValue("@Email", email);
|
||||
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 static async Task<User> UserFromToken(string token)
|
||||
{
|
||||
if (string.IsNullOrEmpty(token))
|
||||
return null;
|
||||
using (var connection = new SqliteConnection(Program.MainDatabaseConnection))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "SELECT * FROM sessions WHERE Token = @Token;";
|
||||
command.Parameters.AddWithValue("@Token", token);
|
||||
using (var reader = await command.ExecuteReaderAsync())
|
||||
{
|
||||
if (!reader.HasRows)
|
||||
return null;
|
||||
await reader.ReadAsync();
|
||||
return await UserFromUUID(reader.GetString(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
public static async Task<int> EnumeratePastes()
|
||||
{
|
||||
using (var connection = new SqliteConnection(Program.MainDatabaseConnection))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "SELECT COUNT(*) FROM pastes;";
|
||||
return Convert.ToInt32(await command.ExecuteScalarAsync());
|
||||
}
|
||||
}
|
||||
}
|
||||
public static async Task<int> EnumerateUserPastes(User user)
|
||||
{
|
||||
if (user == null)
|
||||
return 0;
|
||||
using (var connection = new SqliteConnection(Program.MainDatabaseConnection))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "SELECT COUNT(*) FROM pastes WHERE AuthorUUID = @AuthorUUID;";
|
||||
command.Parameters.AddWithValue("@AuthorUUID", user.UUID);
|
||||
return Convert.ToInt32(await command.ExecuteScalarAsync());
|
||||
}
|
||||
}
|
||||
}
|
||||
public static async Task<Paste> GetPasteFromID(string id)
|
||||
{
|
||||
if (string.IsNullOrEmpty(id))
|
||||
return null;
|
||||
using (var connection = new SqliteConnection(Program.MainDatabaseConnection))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "SELECT * FROM pastes WHERE ID = @ID;";
|
||||
command.Parameters.AddWithValue("@ID", id);
|
||||
using (var reader = await command.ExecuteReaderAsync())
|
||||
{
|
||||
if (!reader.HasRows)
|
||||
return null;
|
||||
await reader.ReadAsync();
|
||||
return 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),
|
||||
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)
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
public static async Task<bool> HasAlreadyViewedFromRqDetails(RequestDetails details)
|
||||
{
|
||||
using (var connection = new SqliteConnection(Program.MainDatabaseConnection))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "SELECT * FROM views WHERE Ip = @Ip AND UserAgent = @UserAgent;";
|
||||
command.Parameters.AddWithValue("@Ip", Bcrypt.HashPassword(details.Ip, Bcrypt.GenerateSalt(8)));
|
||||
command.Parameters.AddWithValue("@UserAgent", details.UserAgent);
|
||||
using (var reader = await command.ExecuteReaderAsync())
|
||||
{
|
||||
return reader.HasRows;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
public static async Task<bool> HasAlreadyViewedFromUserDetails(User user)
|
||||
{
|
||||
using (var connection = new SqliteConnection(Program.MainDatabaseConnection))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "SELECT * FROM views WHERE UserUUID = @UserUUID;";
|
||||
command.Parameters.AddWithValue("@UserUUID", user.UUID);
|
||||
using (var reader = await command.ExecuteReaderAsync())
|
||||
{
|
||||
return reader.HasRows;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
public static async Task AddViewToPaste(User user, Paste paste, RequestDetails details)
|
||||
{
|
||||
if (paste == null || details == null)
|
||||
return;
|
||||
var _user = user ?? new User { UUID = "0" };
|
||||
using (var connection = new SqliteConnection(Program.MainDatabaseConnection))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "INSERT INTO views (UserUUID, PasteUUID, Ip, UserAgent, Created) VALUES (@UserUUID, @PasteUUID, @Ip, @UserAgent, @Created);";
|
||||
command.Parameters.AddWithValue("@UserUUID", _user.UUID);
|
||||
command.Parameters.AddWithValue("@PasteUUID", paste.UUID);
|
||||
command.Parameters.AddWithValue("@Ip", Bcrypt.HashPassword(details.Ip, Bcrypt.GenerateSalt(8)));
|
||||
command.Parameters.AddWithValue("@UserAgent", details.UserAgent);
|
||||
command.Parameters.AddWithValue("@Created", DateTimeOffset.UtcNow.ToUnixTimeSeconds());
|
||||
await command.ExecuteNonQueryAsync();
|
||||
command.CommandText = "UPDATE pastes SET Views = Views + 1 WHERE UUID = @UUID;";
|
||||
command.Parameters.AddWithValue("@UUID", paste.UUID);
|
||||
await command.ExecuteNonQueryAsync();
|
||||
}
|
||||
await connection.CloseAsync();
|
||||
}
|
||||
}
|
||||
public static async Task<List<Paste>> PastesFromUser(User user)
|
||||
{
|
||||
if (user == null)
|
||||
return null;
|
||||
using (var connection = new SqliteConnection(Program.MainDatabaseConnection))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "SELECT * FROM pastes WHERE AuthorUUID = @AuthorUUID;";
|
||||
command.Parameters.AddWithValue("@AuthorUUID", user.UUID);
|
||||
using (var reader = await command.ExecuteReaderAsync())
|
||||
{
|
||||
if (!reader.HasRows)
|
||||
return null;
|
||||
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),
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task<PasswordReset> GetPasswordReset(string url, string uuid, string token)
|
||||
{
|
||||
if (string.IsNullOrEmpty(url) || string.IsNullOrEmpty(uuid) || string.IsNullOrEmpty(token))
|
||||
return null;
|
||||
using (var connection = new SqliteConnection(Program.MainDatabaseConnection))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = new SqliteCommand(Program.MainDatabaseConnection))
|
||||
{
|
||||
command.CommandText = "SELECT * FROM passwordresets WHERE URL = @URL AND UUID = @UUID AND Token = @Token;";
|
||||
command.Parameters.AddWithValue("@URL", url);
|
||||
command.Parameters.AddWithValue("@UUID", uuid);
|
||||
command.Parameters.AddWithValue("@Token", token);
|
||||
await command.ExecuteNonQueryAsync();
|
||||
using (var reader = await command.ExecuteReaderAsync())
|
||||
{
|
||||
if (!reader.HasRows)
|
||||
return null;
|
||||
await reader.ReadAsync();
|
||||
return new PasswordReset
|
||||
{
|
||||
UID = reader.GetString(0),
|
||||
UUID = reader.GetString(1),
|
||||
USERUUID = reader.GetString(2),
|
||||
URL = reader.GetString(3),
|
||||
Token = reader.GetString(4),
|
||||
Created = reader.GetInt64(5),
|
||||
Expirary = reader.GetInt64(6)
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
public static async Task<bool> ResetPassword(string uuid, string password_hash)
|
||||
{
|
||||
if (string.IsNullOrEmpty(uuid) || string.IsNullOrEmpty(password_hash))
|
||||
return false;
|
||||
using (var connection = new SqliteConnection(Program.MainDatabaseConnection))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = new SqliteCommand(Program.MainDatabaseConnection))
|
||||
{
|
||||
command.CommandText = "UPDATE users SET Password = @Password WHERE UUID = @UUID;";
|
||||
command.Parameters.AddWithValue("@Password", password_hash);
|
||||
command.Parameters.AddWithValue("@UUID", uuid);
|
||||
await command.ExecuteNonQueryAsync();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
public string? UUID { get; set; }
|
||||
public string? PasteUUID { get; set; }
|
||||
public string? UserUUID { get; set; }
|
||||
public string? IP { get; set; }
|
||||
public string? Fingerprint { get; set; }
|
||||
public string? UserAgent { get; set; }
|
||||
public long? Created { get; set; }
|
||||
}
|
||||
|
||||
+34
-211
@@ -2,6 +2,7 @@ using Microsoft.Data.Sqlite;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using SharpbinV2.Server.Models;
|
||||
using SharpbinV2.Server.Services;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace SharpbinV2.Server
|
||||
{
|
||||
@@ -36,13 +37,15 @@ namespace SharpbinV2.Server
|
||||
"toml",
|
||||
"xml"
|
||||
};
|
||||
public static string SHA256Salt = RandomNumberGenerator.GetHexString(32);
|
||||
|
||||
static async Task Main(string[] args)
|
||||
{
|
||||
await Initialize();
|
||||
var logger = new Logging();
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
builder.Configuration.AddEnvironmentVariables();
|
||||
|
||||
if (Environment.GetEnvironmentVariable("HTTPS") == "true")
|
||||
{
|
||||
builder.WebHost.UseUrls($"https://*:{Environment.GetEnvironmentVariable("ASPNETCORE_HTTPS_PORTS") ?? "5820"}");
|
||||
@@ -51,8 +54,36 @@ namespace SharpbinV2.Server
|
||||
{
|
||||
builder.WebHost.UseUrls($"http://*:{Environment.GetEnvironmentVariable("ASPNETCORE_HTTP_PORTS") ?? "5810"}");
|
||||
}
|
||||
|
||||
MaxFileSize = Environment.GetEnvironmentVariable("MAX_FILE_SIZE") != null ? Convert.ToInt64(Environment.GetEnvironmentVariable("MAX_FILE_SIZE")) : MaxFileSize;
|
||||
|
||||
if (Environment.GetEnvironmentVariable("SHA256_SALT") != null)
|
||||
{
|
||||
SHA256Salt = Environment.GetEnvironmentVariable("SHA256_SALT") ?? SHA256Salt;
|
||||
}
|
||||
else
|
||||
{
|
||||
SHA256Salt = RandomNumberGenerator.GetHexString(32);
|
||||
Environment.SetEnvironmentVariable("SHA256_SALT", SHA256Salt);
|
||||
|
||||
var dotenv = Path.Combine(Directory.GetCurrentDirectory(), ".env");
|
||||
if (File.Exists(dotenv))
|
||||
{
|
||||
var lines = File.ReadAllLines(dotenv).ToList();
|
||||
var saltLine = $"SHA256_SALT={SHA256Salt}";
|
||||
if (lines.Any(line => line.StartsWith("SHA256_SALT=")))
|
||||
{
|
||||
lines[lines.FindIndex(line => line.StartsWith("SHA256_SALT="))] = saltLine;
|
||||
}
|
||||
else
|
||||
{
|
||||
lines.Add(saltLine);
|
||||
}
|
||||
File.WriteAllLines(dotenv, lines);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
builder.WebHost.ConfigureKestrel(options =>
|
||||
{
|
||||
options.Limits.MaxRequestBodySize = MaxFileSize;
|
||||
@@ -136,220 +167,12 @@ namespace SharpbinV2.Server
|
||||
app.UseResponseCaching();
|
||||
app.UseResponseCompression();
|
||||
|
||||
#region Static Endpoints
|
||||
app.MapGet("/", (HttpContext context) =>
|
||||
{
|
||||
context.Response.StatusCode = 200;
|
||||
context.Response.Headers.Append("Content-Type", "text/html");
|
||||
return context.Response.SendFileAsync("wwwroot/index.html");
|
||||
}).RequireRateLimiting("general");
|
||||
app.MapGet("/{pasteid}", async (HttpContext context, IWebHostEnvironment env, string pasteid) =>
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(pasteid))
|
||||
{
|
||||
context.Response.StatusCode = 400;
|
||||
context.Response.Redirect("/error?error=400&message=Invalid paste id.");
|
||||
return;
|
||||
}
|
||||
|
||||
var filePath = Path.Combine(env.WebRootPath, pasteid);
|
||||
if (File.Exists(filePath))
|
||||
{
|
||||
context.Response.StatusCode = 200;
|
||||
switch (Path.GetExtension(filePath))
|
||||
{
|
||||
case "html":
|
||||
context.Response.Headers.Append("Content-Type", "text/html");
|
||||
break;
|
||||
case "css":
|
||||
context.Response.Headers.Append("Content-Type", "text/css");
|
||||
break;
|
||||
case "js":
|
||||
context.Response.Headers.Append("Content-Type", "text/javascript");
|
||||
break;
|
||||
case "json":
|
||||
context.Response.Headers.Append("Content-Type", "application/json");
|
||||
break;
|
||||
case "png":
|
||||
context.Response.Headers.Append("Content-Type", "image/png");
|
||||
break;
|
||||
case "jpg":
|
||||
case "jpeg":
|
||||
context.Response.Headers.Append("Content-Type", "image/jpeg");
|
||||
break;
|
||||
case "ico":
|
||||
context.Response.Headers.Append("Content-Type", "image/x-icon");
|
||||
break;
|
||||
}
|
||||
await context.Response.SendFileAsync(filePath);
|
||||
return;
|
||||
}
|
||||
var paste = await Database.GetPasteFromID(pasteid);
|
||||
if (paste == null)
|
||||
{
|
||||
context.Response.StatusCode = 400;
|
||||
context.Response.Redirect("/error?error=400&message=Paste not found.");
|
||||
return;
|
||||
}
|
||||
var requestdetails = GetRequestDetails(context);
|
||||
var user = await Database.UserFromToken(requestdetails.Token);
|
||||
|
||||
if (user != null)
|
||||
{
|
||||
if (user.UUID != paste.AuthorUUID)
|
||||
{
|
||||
if (!await Database.HasAlreadyViewedFromUserDetails(user))
|
||||
{
|
||||
await Database.AddViewToPaste(user, paste, requestdetails);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!await Database.HasAlreadyViewedFromRqDetails(requestdetails))
|
||||
{
|
||||
await Database.AddViewToPaste(new User { UUID = "0" }, paste, requestdetails);
|
||||
}
|
||||
}
|
||||
context.Response.StatusCode = 200;
|
||||
context.Response.Headers.Append("Content-Type", "text/html");
|
||||
await context.Response.SendFileAsync("wwwroot/paste.html");
|
||||
}).RequireRateLimiting("general");
|
||||
app.MapGet("/error", async (HttpContext context) =>
|
||||
{
|
||||
context.Response.StatusCode = 400;
|
||||
context.Response.Headers.Append("Content-Type", "text/html");
|
||||
await context.Response.SendFileAsync("wwwroot/error.html");
|
||||
});
|
||||
app.MapGet("/error.html", (HttpContext context) =>
|
||||
{
|
||||
context.Response.Redirect("/error");
|
||||
});
|
||||
app.MapGet("/raw/{pasteid}", async (HttpContext context) =>
|
||||
{
|
||||
var pasteid = context.Request.RouteValues["pasteid"].ToString() ?? null;
|
||||
if (string.IsNullOrEmpty(pasteid))
|
||||
{
|
||||
context.Response.StatusCode = 400;
|
||||
context.Response.Redirect("/error?error=400&message=Invalid paste id.");
|
||||
return;
|
||||
}
|
||||
var paste = await Database.GetPasteFromID(pasteid);
|
||||
if (paste == null)
|
||||
{
|
||||
context.Response.StatusCode = 400;
|
||||
context.Response.Redirect("/error?error=400&message=Paste not found.");
|
||||
return;
|
||||
}
|
||||
context.Response.StatusCode = 200;
|
||||
context.Response.Headers.Append("Content-Type", "text/plain");
|
||||
if (paste.FilePath.EndsWith(".gz"))
|
||||
{
|
||||
context.Response.Headers.Append("Content-Encoding", "gzip");
|
||||
await context.Response.SendFileAsync(paste.FilePath);
|
||||
}
|
||||
else
|
||||
{
|
||||
await context.Response.SendFileAsync(paste.FilePath);
|
||||
}
|
||||
}).RequireRateLimiting("general");
|
||||
app.MapGet("/paste.html", (HttpContext context) =>
|
||||
{
|
||||
context.Response.Redirect("/");
|
||||
});
|
||||
app.MapGet("/archive", async (HttpContext context) =>
|
||||
{
|
||||
context.Response.StatusCode = 200;
|
||||
context.Response.Headers.Append("Content-Type", "text/html");
|
||||
await context.Response.SendFileAsync("wwwroot/archive.html");
|
||||
}).RequireRateLimiting("general");
|
||||
app.MapGet("/dash", async (HttpContext context) =>
|
||||
{
|
||||
context.Response.StatusCode = 200;
|
||||
context.Response.Headers.Append("Content-Type", "text/html");
|
||||
await context.Response.SendFileAsync("wwwroot/dash.html");
|
||||
}).RequireRateLimiting("general");
|
||||
app.MapGet("/dash.html", (HttpContext context) =>
|
||||
{
|
||||
context.Response.Redirect("/dash");
|
||||
});
|
||||
app.MapGet("/login", async (HttpContext context) =>
|
||||
{
|
||||
context.Response.StatusCode = 200;
|
||||
context.Response.Headers.Append("Content-Type", "text/html");
|
||||
await context.Response.SendFileAsync("wwwroot/login.html");
|
||||
}).RequireRateLimiting("general");
|
||||
app.MapGet("/register", async (HttpContext context) =>
|
||||
{
|
||||
context.Response.StatusCode = 200;
|
||||
context.Response.Headers.Append("Content-Type", "text/html");
|
||||
await context.Response.SendFileAsync("wwwroot/register.html");
|
||||
}).RequireRateLimiting("general");
|
||||
app.MapGet("/u/{username}", async (HttpContext context) =>
|
||||
{
|
||||
var username = context.Request.RouteValues["username"].ToString() ?? null;
|
||||
if (string.IsNullOrEmpty(username))
|
||||
{
|
||||
context.Response.StatusCode = 400;
|
||||
context.Response.Redirect("/error?error=400&message=Invalid username.");
|
||||
return;
|
||||
}
|
||||
string html = File.ReadAllText("wwwroot/user.html");
|
||||
context.Response.StatusCode = 200;
|
||||
context.Response.Headers.Append("Content-Type", "text/html");
|
||||
context.Response.Headers.Append("Cache-Control", "no-cache, no-store, must-revalidate");
|
||||
context.Response.Headers.Append("Pragma", "no-cache");
|
||||
context.Response.Headers.Append("Expires", "0");
|
||||
|
||||
|
||||
await context.Response.WriteAsync(html);
|
||||
|
||||
}).RequireRateLimiting("general");
|
||||
app.MapGet("/reset-password", async (HttpContext context) =>
|
||||
{
|
||||
context.Response.StatusCode = 200;
|
||||
context.Response.Headers.Append("Content-Type", "text/html");
|
||||
await context.Response.SendFileAsync("wwwroot/reset-password.html");
|
||||
}).RequireRateLimiting("general");
|
||||
#endregion
|
||||
|
||||
app.MapControllers();
|
||||
|
||||
await app.RunAsync();
|
||||
|
||||
}
|
||||
|
||||
#region Helper Functions
|
||||
static RequestDetails GetRequestDetails(HttpContext context)
|
||||
{
|
||||
var requestdetails = new RequestDetails();
|
||||
var headers = context.Request.Headers;
|
||||
if (headers.ContainsKey("User-Agent"))
|
||||
requestdetails.UserAgent = headers["User-Agent"];
|
||||
|
||||
if (headers.ContainsKey("X-Forwarded-For"))
|
||||
requestdetails.Ip = headers["X-Forwarded-For"];
|
||||
else if (headers.ContainsKey("X-Real-IP"))
|
||||
requestdetails.Ip = headers["X-Real-IP"];
|
||||
else if (headers.ContainsKey("CF-Connecting-IP"))
|
||||
requestdetails.Ip = headers["CF-Connecting-IP"];
|
||||
else if (headers.ContainsKey("True-Client-IP"))
|
||||
requestdetails.Ip = headers["True-Client-IP"];
|
||||
else if (headers.ContainsKey("X-Cluster-Client-IP"))
|
||||
requestdetails.Ip = headers["X-Cluster-Client-IP"];
|
||||
else if (headers.ContainsKey("X-ProxyUser-IP"))
|
||||
requestdetails.Ip = headers["X-ProxyUser-IP"];
|
||||
else
|
||||
requestdetails.Ip = context.Connection.RemoteIpAddress?.ToString();
|
||||
|
||||
if (headers.ContainsKey("Authorization"))
|
||||
requestdetails.Token = headers["Authorization"];
|
||||
else if (context.Request.Cookies.ContainsKey("Authorization"))
|
||||
requestdetails.Token = context.Request.Cookies["Authorization"];
|
||||
|
||||
return requestdetails;
|
||||
}
|
||||
#endregion
|
||||
static async Task Initialize()
|
||||
{
|
||||
try
|
||||
@@ -402,8 +225,8 @@ namespace SharpbinV2.Server
|
||||
command.CommandText = @"CREATE TABLE IF NOT EXISTS views (
|
||||
UserUUID TEXT NOT NULL,
|
||||
PasteUUID INTEGER NOT NULL,
|
||||
Ip TEXT NOT NULL,
|
||||
UserAgent TEXT NOT NULL,
|
||||
Fingerprint TEXT NOT NULL,
|
||||
UserAgent TEXT,
|
||||
Created INTEGER NOT NULL
|
||||
);";
|
||||
await command.ExecuteNonQueryAsync();
|
||||
|
||||
@@ -230,9 +230,8 @@ namespace SharpbinV2.Server.Services
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "SELECT * FROM views WHERE Ip = @Ip AND UserAgent = @UserAgent;";
|
||||
command.Parameters.AddWithValue("@Ip", Bcrypt.HashPassword(details.Ip, Bcrypt.GenerateSalt(8)));
|
||||
command.Parameters.AddWithValue("@UserAgent", details.UserAgent);
|
||||
command.CommandText = "SELECT * FROM views WHERE Fingerprint = @Fingerprint";
|
||||
command.Parameters.AddWithValue("@Fingerprint", HelperService.SHA256Hash(details.Ip + details.UserAgent, Program.SHA256Salt));
|
||||
using (var reader = await command.ExecuteReaderAsync())
|
||||
{
|
||||
return reader.HasRows;
|
||||
@@ -266,11 +265,11 @@ namespace SharpbinV2.Server.Services
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "INSERT INTO views (UserUUID, PasteUUID, Ip, UserAgent, Created) VALUES (@UserUUID, @PasteUUID, @Ip, @UserAgent, @Created);";
|
||||
command.CommandText = "INSERT INTO views (UserUUID, PasteUUID, Fingerprint, UserAgent, Created) VALUES (@UserUUID, @PasteUUID, @Fingerprint, @UserAgent, @Created);";
|
||||
command.Parameters.AddWithValue("@UserUUID", _user.UUID);
|
||||
command.Parameters.AddWithValue("@PasteUUID", paste.UUID);
|
||||
command.Parameters.AddWithValue("@Ip", Bcrypt.HashPassword(details.Ip, Bcrypt.GenerateSalt(8)));
|
||||
command.Parameters.AddWithValue("@UserAgent", details.UserAgent);
|
||||
command.Parameters.AddWithValue("@Fingerprint", HelperService.SHA256Hash(details.Ip + details.UserAgent, Program.SHA256Salt));
|
||||
command.Parameters.AddWithValue("@UserAgent", details.UserAgent ?? (object)DBNull.Value);
|
||||
command.Parameters.AddWithValue("@Created", DateTimeOffset.UtcNow.ToUnixTimeSeconds());
|
||||
await command.ExecuteNonQueryAsync();
|
||||
command.CommandText = "UPDATE pastes SET Views = Views + 1 WHERE UUID = @UUID;";
|
||||
@@ -585,7 +584,7 @@ namespace SharpbinV2.Server.Services
|
||||
{
|
||||
UserUUID = reader.GetString(0),
|
||||
PasteUUID = reader.GetString(1),
|
||||
IP = reader.GetString(2),
|
||||
Fingerprint = reader.GetString(2),
|
||||
UserAgent = reader.GetString(3),
|
||||
Created = reader.GetInt64(4)
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using Newtonsoft.Json.Linq;
|
||||
using SharpbinV2.Server.Models;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using Bcrypt = BCrypt.Net.BCrypt;
|
||||
@@ -86,6 +87,20 @@ namespace SharpbinV2.Server.Services
|
||||
{
|
||||
return Regex.IsMatch(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$");
|
||||
}
|
||||
|
||||
public static string SHA256Hash(string input, string salt = "")
|
||||
{
|
||||
using (SHA256 sha256Hash = SHA256.Create())
|
||||
{
|
||||
string combinedInput = input + salt;
|
||||
byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(combinedInput));
|
||||
|
||||
StringBuilder builder = new StringBuilder();
|
||||
foreach (byte b in bytes)
|
||||
{
|
||||
builder.Append(b.ToString("x2"));
|
||||
}
|
||||
return builder.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user