Enhance security, add admin features, and improve UX

Removed unused cryptography directive and switched to BCrypt for hashing IPs and tokens with a configurable salt. Updated file paths for cross-platform compatibility. Added rate limiting to routes and new admin API endpoints for user management. Improved `config.json` handling and added random password generation.

Enhanced `admin.html` with search debounce, infinite scrolling, and updated CSS. Added password change functionality and notifications to `user.html`. Improved error handling in `archives.html` and refactored `index.html` for better readability. Corrected password character count in `signup.html`.
This commit is contained in:
whoswhip
2024-09-07 18:57:18 -04:00
parent f02e68b1d3
commit 071434efc9
9 changed files with 860 additions and 185 deletions
+1
View File
@@ -375,3 +375,4 @@ PasteBin/p/2d48a001-383d-44fd-8553-4806c9de100d.html
/PasteBin/logs.txt /PasteBin/logs.txt
/PasteBin/config.json /PasteBin/config.json
/PasteBin/Encryption.cs /PasteBin/Encryption.cs
/PasteBin/.config
+441 -25
View File
@@ -5,11 +5,12 @@ using Newtonsoft.Json.Linq;
using System.Data; using System.Data;
using System.Text; using System.Text;
using Sharpbin; using Sharpbin;
using System.Security.Cryptography;
class Program class Program
{ {
private static string salt = string.Empty; private static string salt = string.Empty;
private static string smallerSalt = string.Empty;
public static Dictionary<int, string> accountType = new Dictionary<int, string> public static Dictionary<int, string> accountType = new Dictionary<int, string>
{ {
{ 0, "User" }, { 0, "User" },
@@ -76,7 +77,7 @@ class Program
app.MapGet("/", async (HttpContext context) => app.MapGet("/", async (HttpContext context) =>
{ {
var html = File.ReadAllText("assets\\index.html"); var html = File.ReadAllText("assets/index.html");
bool loggedIn = await IsLoggedInAsync(context.Request.Cookies["token"]); bool loggedIn = await IsLoggedInAsync(context.Request.Cookies["token"]);
if (loggedIn) if (loggedIn)
{ {
@@ -96,6 +97,17 @@ class Program
await context.Response.WriteAsync(html); await context.Response.WriteAsync(html);
return; return;
}); });
app.MapGet("/favicon.ico", async (HttpContext context) =>
{
context.Response.ContentType = "image/x-icon";
if (!File.Exists("assets/favicon.ico"))
{
context.Response.StatusCode = 404;
return;
}
await context.Response.SendFileAsync("assets/favicon.ico");
return;
});
app.MapGet("/login", async (HttpContext context) => app.MapGet("/login", async (HttpContext context) =>
{ {
if (await IsLoggedInAsync(context.Request.Cookies["token"])) if (await IsLoggedInAsync(context.Request.Cookies["token"]))
@@ -103,7 +115,7 @@ class Program
context.Response.Redirect("/"); context.Response.Redirect("/");
return; return;
} }
var html = File.ReadAllText("assets\\login.html"); var html = File.ReadAllText("assets/login.html");
html = html.Replace("{html}", "<a href=\"/sign-up\">sign up</a>"); html = html.Replace("{html}", "<a href=\"/sign-up\">sign up</a>");
context.Response.ContentType = "text/html"; context.Response.ContentType = "text/html";
await context.Response.WriteAsync(html); await context.Response.WriteAsync(html);
@@ -116,7 +128,7 @@ class Program
context.Response.Redirect("/"); context.Response.Redirect("/");
return; return;
} }
var html = File.ReadAllText("assets\\signup.html"); var html = File.ReadAllText("assets/signup.html");
html = html.Replace("{html}", "<a href=\"/login\">login</a>"); html = html.Replace("{html}", "<a href=\"/login\">login</a>");
context.Response.ContentType = "text/html"; context.Response.ContentType = "text/html";
await context.Response.WriteAsync(html); await context.Response.WriteAsync(html);
@@ -197,15 +209,15 @@ class Program
} }
string totalSizeString = ConvertToBytes(totalSize.ToString()); string totalSizeString = ConvertToBytes(totalSize.ToString());
var html = File.ReadAllText("assets\\dash.html"); var html = File.ReadAllText("assets/dash.html");
if (user.Type == 255) if (user.Type == 255)
{ {
html = File.ReadAllText("assets\\admin.html"); html = File.ReadAllText("assets/admin.html");
using (var connection = new SqliteConnection("Data Source=pastes.sqlite")) using (var connection = new SqliteConnection("Data Source=pastes.sqlite"))
{ {
await connection.OpenAsync(); await connection.OpenAsync();
var usersCommand = connection.CreateCommand(); var usersCommand = connection.CreateCommand();
usersCommand.CommandText = "SELECT * FROM users"; usersCommand.CommandText = "SELECT * FROM users LIMIT 10";
var usersReader = await usersCommand.ExecuteReaderAsync(); var usersReader = await usersCommand.ExecuteReaderAsync();
List<User> users = new List<User>(); List<User> users = new List<User>();
while (await usersReader.ReadAsync()) while (await usersReader.ReadAsync())
@@ -266,7 +278,7 @@ class Program
app.MapGet("/paste-not-found", async (HttpContext context) => app.MapGet("/paste-not-found", async (HttpContext context) =>
{ {
context.Response.StatusCode = 404; context.Response.StatusCode = 404;
var error_html = File.ReadAllText("assets\\error.html"); var error_html = File.ReadAllText("assets/error.html");
error_html = error_html.Replace("{code}", "404"); error_html = error_html.Replace("{code}", "404");
error_html = error_html.Replace("{message}", "Paste not found"); error_html = error_html.Replace("{message}", "Paste not found");
bool loggedIn = await IsLoggedInAsync(context.Request.Cookies["token"]); bool loggedIn = await IsLoggedInAsync(context.Request.Cookies["token"]);
@@ -285,7 +297,7 @@ class Program
app.MapGet("/unauthorized", async (HttpContext context) => app.MapGet("/unauthorized", async (HttpContext context) =>
{ {
context.Response.StatusCode = 404; context.Response.StatusCode = 404;
var error_html = File.ReadAllText("assets\\error.html"); var error_html = File.ReadAllText("assets/error.html");
error_html = error_html.Replace("{code}", "401"); error_html = error_html.Replace("{code}", "401");
error_html = error_html.Replace("{message}", "Unauthorized"); error_html = error_html.Replace("{message}", "Unauthorized");
bool loggedIn = await IsLoggedInAsync(context.Request.Cookies["token"]); bool loggedIn = await IsLoggedInAsync(context.Request.Cookies["token"]);
@@ -304,7 +316,7 @@ class Program
app.MapGet("/banned", async (HttpContext context) => app.MapGet("/banned", async (HttpContext context) =>
{ {
context.Response.StatusCode = 404; context.Response.StatusCode = 404;
var error_html = File.ReadAllText("assets\\error.html"); var error_html = File.ReadAllText("assets/error.html");
bool loggedIn = await IsLoggedInAsync(context.Request.Cookies["token"]); bool loggedIn = await IsLoggedInAsync(context.Request.Cookies["token"]);
if (loggedIn) if (loggedIn)
{ {
@@ -412,7 +424,7 @@ class Program
} }
var html = File.ReadAllText("assets\\paste.html"); var html = File.ReadAllText("assets/paste.html");
html = html.Replace("{pastetitleattribute}", paste.Title); html = html.Replace("{pastetitleattribute}", paste.Title);
html = html.Replace("{pastetitle}", title); html = html.Replace("{pastetitle}", title);
html = html.Replace("{content}", content); html = html.Replace("{content}", content);
@@ -445,7 +457,7 @@ class Program
await context.Response.WriteAsync(html); await context.Response.WriteAsync(html);
return; return;
} }
}); }).RequireRateLimiting("fixed-bigger");
app.MapGet("/raw/{id}", async (HttpContext context) => app.MapGet("/raw/{id}", async (HttpContext context) =>
{ {
var id = context.Request?.RouteValues?["id"]?.ToString(); var id = context.Request?.RouteValues?["id"]?.ToString();
@@ -458,10 +470,10 @@ class Program
context.Response.ContentType = "text/plain"; context.Response.ContentType = "text/plain";
await context.Response.WriteAsync(content); await context.Response.WriteAsync(content);
return; return;
}); }).RequireRateLimiting("fixed-bigger");
app.MapGet("/pastes", async (HttpContext context) => app.MapGet("/pastes", async (HttpContext context) =>
{ {
var html = File.ReadAllText("assets\\recent_pastes.html"); var html = File.ReadAllText("assets/recent_pastes.html");
bool loggedIn = await IsLoggedInAsync(context.Request.Cookies["token"]); bool loggedIn = await IsLoggedInAsync(context.Request.Cookies["token"]);
if (loggedIn) if (loggedIn)
{ {
@@ -518,7 +530,7 @@ class Program
}).RequireRateLimiting("fixed-bigger"); }).RequireRateLimiting("fixed-bigger");
app.MapGet("/archive", async (HttpContext context) => app.MapGet("/archive", async (HttpContext context) =>
{ {
var html = File.ReadAllText("assets\\archives.html"); var html = File.ReadAllText("assets/archives.html");
var page = context.Request?.Query["page"].ToString(); var page = context.Request?.Query["page"].ToString();
bool loggedIn = await IsLoggedInAsync(context.Request.Cookies["token"]); bool loggedIn = await IsLoggedInAsync(context.Request.Cookies["token"]);
@@ -603,7 +615,7 @@ class Program
app.MapGet("/u/{username}", async (HttpContext context) => app.MapGet("/u/{username}", async (HttpContext context) =>
{ {
string username = context.Request?.RouteValues?["username"]?.ToString(); string username = context.Request?.RouteValues?["username"]?.ToString();
var html = File.ReadAllText(@"assets\user.html"); var html = File.ReadAllText(@"assets/user.html");
using (var connection = new SqliteConnection("Data Source=pastes.sqlite")) using (var connection = new SqliteConnection("Data Source=pastes.sqlite"))
{ {
await connection.OpenAsync(); await connection.OpenAsync();
@@ -614,7 +626,7 @@ class Program
await reader.ReadAsync(); await reader.ReadAsync();
if (!reader.HasRows) if (!reader.HasRows)
{ {
html = File.ReadAllText(@"assets\error.html"); html = File.ReadAllText(@"assets/error.html");
html = html.Replace("{code}", "404"); html = html.Replace("{code}", "404");
html = html.Replace("{message}", "User not found"); html = html.Replace("{message}", "User not found");
context.Response.ContentType = "text/html"; context.Response.ContentType = "text/html";
@@ -696,7 +708,7 @@ class Program
app.MapGet("/uid/{uid}", async (HttpContext context) => app.MapGet("/uid/{uid}", async (HttpContext context) =>
{ {
string username = context.Request?.RouteValues?["uid"]?.ToString(); string username = context.Request?.RouteValues?["uid"]?.ToString();
var html = File.ReadAllText(@"assets\user.html"); var html = File.ReadAllText(@"assets/user.html");
using (var connection = new SqliteConnection("Data Source=pastes.sqlite")) using (var connection = new SqliteConnection("Data Source=pastes.sqlite"))
{ {
await connection.OpenAsync(); await connection.OpenAsync();
@@ -707,7 +719,7 @@ class Program
await reader.ReadAsync(); await reader.ReadAsync();
if (!reader.HasRows) if (!reader.HasRows)
{ {
html = File.ReadAllText(@"assets\error.html"); html = File.ReadAllText(@"assets/error.html");
html = html.Replace("{code}", "404"); html = html.Replace("{code}", "404");
html = html.Replace("{message}", "User not found"); html = html.Replace("{message}", "User not found");
context.Response.ContentType = "text/html"; context.Response.ContentType = "text/html";
@@ -806,7 +818,7 @@ class Program
} }
} }
var html = File.ReadAllText(@"assets\admin\user.html"); var html = File.ReadAllText(@"assets/admin/user.html");
using (var connection = new SqliteConnection("Data Source=pastes.sqlite")) using (var connection = new SqliteConnection("Data Source=pastes.sqlite"))
{ {
await connection.OpenAsync(); await connection.OpenAsync();
@@ -817,7 +829,7 @@ class Program
await reader.ReadAsync(); await reader.ReadAsync();
if (!reader.HasRows) if (!reader.HasRows)
{ {
html = File.ReadAllText(@"assets\error.html"); html = File.ReadAllText(@"assets/error.html");
html = html.Replace("{code}", "404"); html = html.Replace("{code}", "404");
html = html.Replace("{message}", "User not found"); html = html.Replace("{message}", "User not found");
context.Response.ContentType = "text/html"; context.Response.ContentType = "text/html";
@@ -1004,6 +1016,399 @@ class Program
context.Response.ContentType = "application/json"; context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["message"] = "User banned" }.ToString()); await context.Response.WriteAsJsonAsync(new JObject { ["message"] = "User banned" }.ToString());
return; return;
}).RequireRateLimiting("fixed");
app.MapPost("/api/accounts/admin/unban", async (HttpContext context) =>
{
var loggedInUser = await GetLoggedInUserAsync(context.Request.Cookies["token"]);
if (!await IsLoggedInAsync(context.Request.Cookies["token"]))
{
context.Response.StatusCode = 401;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Unauthorized" }.ToString());
return;
}
else if (await IsLoggedInAsync(context.Request.Cookies["token"]))
{
if (loggedInUser.Type != 255)
{
context.Response.StatusCode = 401;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Unauthorized" }.ToString());
return;
}
}
string requestBody = await new StreamReader(context.Request.Body).ReadToEndAsync();
try
{
JObject.Parse(requestBody);
}
catch
{
context.Response.StatusCode = 400;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Invalid JSON" }.ToString());
return;
}
if (string.IsNullOrEmpty(requestBody))
{
context.Response.StatusCode = 400;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "No data uploaded" }.ToString());
return;
}
var data = JObject.Parse(requestBody);
var uuid = SanitizeInput(data["uuid"]?.ToString() ?? "");
var reason = SanitizeInput(data["reason"]?.ToString() ?? "No reason provided");
if (string.IsNullOrEmpty(uuid) || string.IsNullOrWhiteSpace(uuid))
{
context.Response.StatusCode = 400;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Invalid request body" }.ToString());
return;
}
var user = new User();
using (var connection = new SqliteConnection("Data Source = pastes.sqlite"))
{
await connection.OpenAsync();
var command = connection.CreateCommand();
command.CommandText = "SELECT * FROM users WHERE UUID = @UUID";
command.Parameters.AddWithValue("@UUID", uuid);
var reader = await command.ExecuteReaderAsync();
await reader.ReadAsync();
if (!reader.HasRows)
{
context.Response.StatusCode = 404;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "User not found" }.ToString());
return;
}
user = new User
{
UID = reader.GetString(0),
UUID = reader.GetString(1),
Username = reader.GetString(2),
PasswordHash = reader.GetString(3),
CreationDate = reader.GetString(4),
LastLoginDate = reader.GetString(5),
Type = reader.GetInt32(6),
State = reader.GetInt32(7),
};
if (user.State == 0)
{
context.Response.StatusCode = 400;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "User is already unbanned" }.ToString());
return;
}
var banUserCommand = connection.CreateCommand();
banUserCommand.CommandText = "UPDATE users SET State = 0 WHERE UUID = @UUID";
banUserCommand.Parameters.AddWithValue("@UUID", uuid);
await banUserCommand.ExecuteNonQueryAsync();
var punishedUsersCommand = connection.CreateCommand();
punishedUsersCommand.CommandText = "DELETE FROM punishedUsers WHERE UUID = @UUID";
punishedUsersCommand.Parameters.AddWithValue("@UUID", uuid);
await punishedUsersCommand.ExecuteNonQueryAsync();
}
Console.WriteLine($"[{DateTime.Now}] Account {user.Username}({user.UUID}) has been banned by {loggedInUser.Username}({loggedInUser.UUID}) for {reason}");
await File.AppendAllTextAsync("logs.log", $"[{DateTime.Now}] Account {user.Username}({user.UUID}) has been banned by {loggedInUser.Username}({loggedInUser.UUID}) for {reason}\n");
context.Response.StatusCode = 200;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["message"] = "User unbanned" }.ToString());
}).RequireRateLimiting("fixed");
app.MapPost("/api/accounts/admin/change-password", async (HttpContext context) =>
{
var loggedInUser = await GetLoggedInUserAsync(context.Request.Cookies["token"]);
if (!await IsLoggedInAsync(context.Request.Cookies["token"]))
{
context.Response.StatusCode = 401;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Unauthorized" }.ToString());
return;
}
else if (await IsLoggedInAsync(context.Request.Cookies["token"]))
{
if (loggedInUser.Type != 255)
{
context.Response.StatusCode = 401;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Unauthorized" }.ToString());
return;
}
}
string requestBody = await new StreamReader(context.Request.Body).ReadToEndAsync();
try
{
JObject.Parse(requestBody);
}
catch
{
context.Response.StatusCode = 400;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Invalid JSON" }.ToString());
return;
}
if (string.IsNullOrEmpty(requestBody))
{
context.Response.StatusCode = 400;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "No data uploaded" }.ToString());
return;
}
var data = JObject.Parse(requestBody);
var uuid = SanitizeInput(data["uuid"]?.ToString() ?? "");
var newPassword = SanitizeInput(data["password"]?.ToString() ?? GenerateRandomPassword(50));
if (string.IsNullOrEmpty(newPassword) || string.IsNullOrWhiteSpace(newPassword))
{
newPassword = GenerateRandomPassword(50);
}
Console.WriteLine(newPassword);
if (string.IsNullOrEmpty(uuid) || string.IsNullOrWhiteSpace(uuid))
{
context.Response.StatusCode = 400;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Invalid request body" }.ToString());
return;
}
var user = new User();
using (var connection = new SqliteConnection("Data Source = pastes.sqlite"))
{
await connection.OpenAsync();
var command = connection.CreateCommand();
command.CommandText = "SELECT * FROM users WHERE UUID = @UUID";
command.Parameters.AddWithValue("@UUID", uuid);
var reader = await command.ExecuteReaderAsync();
await reader.ReadAsync();
if (!reader.HasRows)
{
context.Response.StatusCode = 404;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "User not found" }.ToString());
return;
}
user = new User
{
UID = reader.GetString(0),
UUID = reader.GetString(1),
Username = reader.GetString(2),
PasswordHash = reader.GetString(3),
CreationDate = reader.GetString(4),
LastLoginDate = reader.GetString(5),
Type = reader.GetInt32(6),
State = reader.GetInt32(7),
};
var changePasswordCommand = connection.CreateCommand();
changePasswordCommand.CommandText = "UPDATE users SET PasswordHash = @Password WHERE UUID = @UUID";
changePasswordCommand.Parameters.AddWithValue("@Password", BCrypt.Net.BCrypt.HashPassword(newPassword));
changePasswordCommand.Parameters.AddWithValue("@UUID", uuid);
await changePasswordCommand.ExecuteNonQueryAsync();
var deleteLoginsCommand = connection.CreateCommand();
deleteLoginsCommand.CommandText = "DELETE FROM logins WHERE UUID = @UUID";
deleteLoginsCommand.Parameters.AddWithValue("@UUID", uuid);
await deleteLoginsCommand.ExecuteNonQueryAsync();
}
Console.WriteLine($"[{DateTime.Now}] Account {user.Username}({user.UUID}) has had their password changed by {loggedInUser.Username}({loggedInUser.UUID})");
await File.AppendAllTextAsync("logs.log", $"[{DateTime.Now}] Account {user.Username}({user.UUID}) has had their password changed by {loggedInUser.Username}({loggedInUser.UUID})\n");
context.Response.StatusCode = 200;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["message"] = "Password changed", ["password"] = newPassword }.ToString());
}).RequireRateLimiting("fixed");
app.MapPost("/api/accounts/admin/get", async (HttpContext context) =>
{
var loggedInUser = await GetLoggedInUserAsync(context.Request.Cookies["token"]);
var htmlQuery = context.Request.Query["html"].ToString();
if (!await IsLoggedInAsync(context.Request.Cookies["token"]))
{
context.Response.StatusCode = 401;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Unauthorized" }.ToString());
return;
}
else if (await IsLoggedInAsync(context.Request.Cookies["token"]))
{
if (loggedInUser.Type != 255)
{
context.Response.StatusCode = 401;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Unauthorized" }.ToString());
return;
}
}
string requestBody = await new StreamReader(context.Request.Body).ReadToEndAsync();
try
{
JObject.Parse(requestBody);
}
catch
{
context.Response.StatusCode = 400;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Invalid JSON" }.ToString());
return;
}
if (string.IsNullOrEmpty(requestBody))
{
context.Response.StatusCode = 400;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "No data uploaded" }.ToString());
return;
}
var data = JObject.Parse(requestBody);
List<User> users = new List<User>();
JArray usersJson = new JArray();
string html = string.Empty;
long offset = data["offset"]?.ToObject<long>() ?? 0;
string searhc = data["search"]?.ToString() ?? "";
using (var connection = new SqliteConnection("Data Source=pastes.sqlite"))
{
await connection.OpenAsync();
var command = connection.CreateCommand();
command.CommandText = "SELECT * FROM users ORDER BY UID LIMIT 10 OFFSET @Offset";
command.Parameters.AddWithValue("@Offset", offset);
var reader = await command.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
var user = new User
{
UID = reader.GetString(0),
UUID = reader.GetString(1),
Username = reader.GetString(2),
PasswordHash = reader.GetString(3),
CreationDate = reader.GetString(4),
LastLoginDate = reader.GetString(5),
Type = reader.GetInt32(6),
State = reader.GetInt32(7),
};
users.Add(user);
if (htmlQuery.ToLower() == "true")
{
html += $"<a class=\"list-a\" href=\"/admin/u/{user.Username}\"><li class=\"list-item \">{user.Username}</li></a>";
}
else
{
JObject userJson = new JObject();
userJson["uid"] = user.UID;
userJson["uuid"] = user.UUID;
userJson["username"] = user.Username;
userJson["creationdate"] = user.CreationDate;
userJson["lastlogindate"] = user.LastLoginDate;
userJson["type"] = accountType[user.Type];
userJson["state"] = user.State;
usersJson.Add(userJson);
}
}
}
if (htmlQuery.ToLower() == "true")
{
context.Response.ContentType = "text/html";
await context.Response.WriteAsync(html);
}
else
{
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(usersJson.ToString());
}
}).RequireRateLimiting("fixed-bigger");
app.MapPost("/api/accounts/admin/search", async (HttpContext context) =>
{
var loggedInUser = await GetLoggedInUserAsync(context.Request.Cookies["token"]);
var htmlQuery = context.Request.Query["html"].ToString();
if (!await IsLoggedInAsync(context.Request.Cookies["token"]))
{
context.Response.StatusCode = 401;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Unauthorized" }.ToString());
return;
}
else if (await IsLoggedInAsync(context.Request.Cookies["token"]))
{
if (loggedInUser.Type != 255)
{
context.Response.StatusCode = 401;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Unauthorized" }.ToString());
return;
}
}
string requestBody = await new StreamReader(context.Request.Body).ReadToEndAsync();
try
{
JObject.Parse(requestBody);
}
catch
{
context.Response.StatusCode = 400;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Invalid JSON" }.ToString());
return;
}
if (string.IsNullOrEmpty(requestBody))
{
context.Response.StatusCode = 400;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "No data uploaded" }.ToString());
return;
}
var data = JObject.Parse(requestBody);
List<User> users = new List<User>();
JArray usersJson = new JArray();
string html = string.Empty;
string search = data["search"]?.ToString() ?? "";
using (var connection = new SqliteConnection("Data Source=pastes.sqlite"))
{
await connection.OpenAsync();
var command = connection.CreateCommand();
command.CommandText = "SELECT * FROM users WHERE Username LIKE @Search ORDER BY UID";
command.Parameters.AddWithValue("@Search", $"%{search}%");
var reader = await command.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
var user = new User
{
UID = reader.GetString(0),
UUID = reader.GetString(1),
Username = reader.GetString(2),
PasswordHash = reader.GetString(3),
CreationDate = reader.GetString(4),
LastLoginDate = reader.GetString(5),
Type = reader.GetInt32(6),
State = reader.GetInt32(7),
};
users.Add(user);
if (htmlQuery.ToLower() == "true")
{
html += $"<a class=\"list-a\" href=\"/admin/u/{user.Username}\"><li class=\"list-item \">{user.Username}</li></a>";
}
else
{
JObject userJson = new JObject();
userJson["uid"] = user.UID;
userJson["uuid"] = user.UUID;
userJson["username"] = user.Username;
userJson["creationdate"] = user.CreationDate;
userJson["lastlogindate"] = user.LastLoginDate;
userJson["type"] = accountType[user.Type];
userJson["state"] = user.State;
usersJson.Add(userJson);
}
}
}
if (htmlQuery.ToLower() == "true")
{
context.Response.ContentType = "text/html";
await context.Response.WriteAsync(html);
}
else
{
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(usersJson.ToString());
}
}); });
#endregion #endregion
@@ -1447,8 +1852,8 @@ class Program
reader.Close(); reader.Close();
} }
ip = Convert.ToBase64String(SHA1.HashData(Encoding.UTF8.GetBytes(log.IP))); ip = Convert.ToBase64String(Encoding.UTF8.GetBytes(BCrypt.Net.BCrypt.HashPassword(log.IP, smallerSalt)));
token = Convert.ToBase64String(Encoding.UTF8.GetBytes(BCrypt.Net.BCrypt.HashPassword(Guid.NewGuid().ToString()))); token = Convert.ToBase64String(Encoding.UTF8.GetBytes(BCrypt.Net.BCrypt.HashPassword(Guid.NewGuid().ToString(), smallerSalt)));
passwordHash = BCrypt.Net.BCrypt.HashPassword(password, salt); passwordHash = BCrypt.Net.BCrypt.HashPassword(password, salt);
var insertCommand = connection.CreateCommand(); var insertCommand = connection.CreateCommand();
insertCommand.CommandText = "INSERT INTO users (UUID, Username, PasswordHash, CreationDate, LastLoginDate, Type, State) VALUES (@UUID, @Username, @PasswordHash, @CreationDate, @LastLoginDate, @Type, @State)"; insertCommand.CommandText = "INSERT INTO users (UUID, Username, PasswordHash, CreationDate, LastLoginDate, Type, State) VALUES (@UUID, @Username, @PasswordHash, @CreationDate, @LastLoginDate, @Type, @State)";
@@ -1538,7 +1943,7 @@ class Program
return; return;
} }
string ip = Convert.ToBase64String(SHA1.HashData(Encoding.UTF8.GetBytes(log.IP))); string ip = Convert.ToBase64String(Encoding.UTF8.GetBytes(BCrypt.Net.BCrypt.HashPassword(log.IP, smallerSalt)));
string passwordHash = BCrypt.Net.BCrypt.HashPassword(password, salt); string passwordHash = BCrypt.Net.BCrypt.HashPassword(password, salt);
using (var connection = new SqliteConnection("Data Source=pastes.sqlite")) using (var connection = new SqliteConnection("Data Source=pastes.sqlite"))
@@ -1558,7 +1963,7 @@ class Program
} }
if (BCrypt.Net.BCrypt.Verify(password, reader.GetString(3))) if (BCrypt.Net.BCrypt.Verify(password, reader.GetString(3)))
{ {
string token = Convert.ToBase64String(Encoding.UTF8.GetBytes(BCrypt.Net.BCrypt.HashPassword(Guid.NewGuid().ToString()))); string token = Convert.ToBase64String(Encoding.UTF8.GetBytes(BCrypt.Net.BCrypt.HashPassword(Guid.NewGuid().ToString(), smallerSalt)));
DateTime expirationDate = DateTime.Now.AddYears(1); DateTime expirationDate = DateTime.Now.AddYears(1);
var loginCommand = connection.CreateCommand(); var loginCommand = connection.CreateCommand();
@@ -1776,13 +2181,17 @@ class Program
{ {
var config = JObject.Parse(File.ReadAllText("config.json")); var config = JObject.Parse(File.ReadAllText("config.json"));
salt = config["Salt"]?.ToString() ?? BCrypt.Net.BCrypt.GenerateSalt(13); salt = config["Salt"]?.ToString() ?? BCrypt.Net.BCrypt.GenerateSalt(13);
smallerSalt = config["SmallerSalt"]?.ToString() ?? BCrypt.Net.BCrypt.GenerateSalt(8);
Logging.Api_CreateMessage = config["API_CreateMessage"]?.ToString() ?? ""; Logging.Api_CreateMessage = config["API_CreateMessage"]?.ToString() ?? "";
} }
else else
{ {
var config = new JObject(); var config = new JObject();
config["Salt"] = BCrypt.Net.BCrypt.GenerateSalt(13); config["Salt"] = BCrypt.Net.BCrypt.GenerateSalt(13);
config["SmallerSalt"] = BCrypt.Net.BCrypt.GenerateSalt(8);
salt = config["Salt"]?.ToString() ?? BCrypt.Net.BCrypt.GenerateSalt(13); salt = config["Salt"]?.ToString() ?? BCrypt.Net.BCrypt.GenerateSalt(13);
smallerSalt = config["SmallerSalt"]?.ToString() ?? BCrypt.Net.BCrypt.GenerateSalt(8);
File.WriteAllText("config.json", config.ToString()); File.WriteAllText("config.json", config.ToString());
} }
if (!Directory.Exists("pastes")) if (!Directory.Exists("pastes"))
@@ -1795,6 +2204,13 @@ class Program
return new string(Enumerable.Repeat(chars, length) return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray()); .Select(s => s[random.Next(s.Length)]).ToArray());
} }
public static string GenerateRandomPassword(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());
}
} }
public class Paste public class Paste
{ {
+1 -1
View File
@@ -4,7 +4,7 @@
"windowsAuthentication": false, "windowsAuthentication": false,
"anonymousAuthentication": true, "anonymousAuthentication": true,
"iisExpress": { "iisExpress": {
"applicationUrl": "http://*:29219", "applicationUrl": "http://localhost:29219",
"sslPort": 44358 "sslPort": 44358
} }
}, },
+58
View File
@@ -13,6 +13,34 @@
<None Remove="pastes\**" /> <None Remove="pastes\**" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Remove="assets\admin.html" />
<None Remove="assets\admin\user.html" />
<None Remove="assets\archives.html" />
<None Remove="assets\dash.html" />
<None Remove="assets\error.html" />
<None Remove="assets\login.html" />
<None Remove="assets\paste.html" />
<None Remove="assets\recent_pastes.html" />
<None Remove="assets\signup.html" />
<None Remove="assets\user.html" />
</ItemGroup>
<ItemGroup>
<Resource Include="assets\admin.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Resource>
<Resource Include="assets\admin\user.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Resource>
<Resource Include="assets\archives.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Resource>
<Resource Include="assets\index.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Resource>
</ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="BCrypt.Net-Next" Version="4.0.3" /> <PackageReference Include="BCrypt.Net-Next" Version="4.0.3" />
<PackageReference Include="Microsoft.Data.Sqlite" Version="8.0.8" /> <PackageReference Include="Microsoft.Data.Sqlite" Version="8.0.8" />
@@ -23,4 +51,34 @@
<Folder Include="wwwroot\" /> <Folder Include="wwwroot\" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Resource Include="assets\dash.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Resource>
<Resource Include="assets\error.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Resource>
<Resource Include="assets\login.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Resource>
<Resource Include="assets\paste.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Resource>
<Resource Include="assets\recent_pastes.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Resource>
<Resource Include="assets\signup.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Resource>
<Resource Include="assets\user.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Resource>
</ItemGroup>
<ItemGroup>
<Content Update="config.json">
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project> </Project>
+78 -9
View File
@@ -40,7 +40,7 @@
<div class="accounts-wrapper"> <div class="accounts-wrapper">
<h3>Accounts</h3> <h3>Accounts</h3>
<input type="text" placeholder="search" class="text-input" oninput="search()"> <input type="text" placeholder="search" class="text-input" oninput="search()">
<div class="list-container"> <div class="list-container" onscroll="getUsers()">
{accounts} {accounts}
</div> </div>
</div> </div>
@@ -51,6 +51,7 @@
</div> </div>
</body> </body>
<script> <script>
let searchTimeout;
function localizeDateTime(unixTimestamp) { function localizeDateTime(unixTimestamp) {
const date = new Date(unixTimestamp * 1000); const date = new Date(unixTimestamp * 1000);
return date.toLocaleString(); return date.toLocaleString();
@@ -66,24 +67,92 @@
creationdateElement.innerText = "Creation Date: " + localizeDateTime(parseInt(creationdateText)); creationdateElement.innerText = "Creation Date: " + localizeDateTime(parseInt(creationdateText));
lastlogindateElement.innerText = "Last Login Date: " + localizeDateTime(parseInt(lastlogindateText)); lastlogindateElement.innerText = "Last Login Date: " + localizeDateTime(parseInt(lastlogindateText));
}); });
function waitSearch() {
clearTimeout(searchTimeout);
searchTimeout = setTimeout(search, 200);
}
function search() { function search() {
const input = document.querySelector('.text-input').value; const input = document.querySelector('.text-input').value;
const accountWrapper = document.querySelector('.accounts-wrapper'); const accountWrapper = document.querySelector('.accounts-wrapper');
const accounts = accountWrapper.querySelectorAll('.list-a'); const accounts = accountWrapper.querySelectorAll('.list-a');
accounts.forEach(account => { if (input.length == 0){
const username = account.querySelector('.list-item').innerText; fetch(`/api/accounts/admin/get?html=true`, {
if (username.toLowerCase().includes(input.toLowerCase())) { method: 'POST',
account.style.display = 'flex'; headers: {
} else { 'Content-Type': 'application/json'
account.style.display = 'none'; },
body: JSON.stringify({
offset: 0,
})
})
.then(response => response.text())
.then(data => {
const listContainer = accountWrapper.querySelector('.list-container');
listContainer.innerHTML = data;
})
return;
} }
}); fetch(`/api/accounts/admin/search?html=true`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
search: input
})
})
.then(response => response.text())
.then(data => {
const listContainer = accountWrapper.querySelector('.list-container');
listContainer.innerHTML = data;
})
} }
function getUsers() {
const accountWrapper = document.querySelector('.accounts-wrapper');
const listContainer = accountWrapper.querySelector('.list-container');
const accounts = accountWrapper.querySelectorAll('.list-a');
const lastAccount = accounts[accounts.length - 1];
const lastAccountUsername = lastAccount.querySelector('.list-item').innerText;
const lastAccountUUID = lastAccount.querySelector('.list-item').getAttribute('data-uuid');
var isScrolledDown = listContainer.scrollTop + listContainer.clientHeight >= listContainer.scrollHeight;
if (!isScrolledDown) {
return;
}
fetch(`/api/accounts/admin/get?html=true`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
offset: accounts.length,
})
})
.then(response => response.text())
.then(data => {
if (data === '') {
return;
}
console.log(listContainer.innerHTML);
console.log(data);
listContainer.innerHTML += data;
}
)
}
function isScrolledDown(element){
var scrollPosition = element.scrollTop + element.clientHeight;
var scrollHeight = element.scrollHeight;
return scrollPosition >= scrollHeight;
}
</script> </script>
<style> <style>
.list-container { .list-container {
max-height: 100%; max-height: 100%;
overflow-y: auto; overflow-y: scroll;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
width: 100%; width: 100%;
+94 -3
View File
@@ -32,7 +32,7 @@
<h2 style="text-align: center;">Actions</h2> <h2 style="text-align: center;">Actions</h2>
<div class="button-wrapper"> <div class="button-wrapper">
<a onclick="banAccount()" class="button">{typeban}</a> <a onclick="banAccount()" class="button">{typeban}</a>
<a href="/dash" class="button">back</a> <a onclick="changePassword()" class="button">change password</a>
</div> </div>
</div> </div>
<div class="pastes-wrapper"> <div class="pastes-wrapper">
@@ -45,6 +45,9 @@
</div> </div>
</div> </div>
<div class="notification-div" id="notification">
<h2 id="notification-text"></h2>
</div>
</body> </body>
<script> <script>
function localizeDateTime(unixTimestamp) { function localizeDateTime(unixTimestamp) {
@@ -79,15 +82,102 @@
.then(obj => { .then(obj => {
const result = JSON.parse(obj); const result = JSON.parse(obj);
if (result.message != null) { if (result.message != null) {
alert(result.message); notification(`${result.message} for ${reason}`);
} else { } else {
alert(`Failed to {typeban} account for ${result.error}`); notification(`Failed to {typeban} ${result.error}`);
} }
}) })
} }
function changePassword() {
let password = prompt('Enter the new password');
fetch('/api/accounts/admin/change-password', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
uuid: '{uuid}',
password: `${password}`
})
}).then(response => response.json())
.then(obj => {
const result = JSON.parse(obj);
if (result.message != null) {
notification(`${result.message} to ${password}`);
} else {
notification(`Failed to change password for ${result.error}`);
}
})
}
function notification(message) {
const notification = document.getElementById('notification');
const notificationText = document.getElementById('notification-text');
notificationText.innerText = message;
notification.style.animation = 'none';
notification.style.display = 'none';
notification.style.display = 'flex';
notification.style.animation = 'hoverup 1s';
setTimeout(() => {
notification.style.animation = 'hoverdown 1s';
}, 4000);
setTimeout(() => {
notification.style.display = 'none';
}, 4900);
}
</script> </script>
<style> <style>
@keyframes hoverup {
0% {
transform: translateY(100%);
}
50% {
transform: translateY(-10px);
}
100% {
transform: translateY(0);
}
}
@keyframes hoverdown {
0% {
transform: translateY(0);
}
50% {
transform: translateY(-10px);
}
100% {
transform: translateY(200%);
}
}
.notification-div {
position: fixed;
display: none;
right: 0;
bottom: 0;
width: fit-content;
height: fit-content;
color: white;
background-color: #181818;
border-radius: 5px;
border: #222222 2px solid;
padding-left: 10px;
padding-right: 10px;
margin-right: 10px;
margin-bottom: 10px;
justify-content: center;
align-items: center;
}
h3 { h3 {
word-break: keep-all; word-break: keep-all;
@@ -164,6 +254,7 @@
justify-content: center; justify-content: center;
align-items: center; align-items: center;
background-color: #0d0d0d; background-color: #0d0d0d;
position: relative;
} }
.container-wrapper { .container-wrapper {
+19
View File
@@ -60,6 +60,16 @@
pastesWrapper.innerHTML = '<h1>no pastes found</h1>'; pastesWrapper.innerHTML = '<h1>no pastes found</h1>';
return; return;
} }
try {
json = JSON.parse(data);
if (json.error != null) {
pastesWrapper.innerHTML = `<h1>${json.error}</h1>`;
return;
}
}
catch {
}
pastesWrapper.innerHTML = data; pastesWrapper.innerHTML = data;
}); });
return; return;
@@ -80,6 +90,15 @@
pastesWrapper.innerHTML = '<h1>no pastes found</h1>'; pastesWrapper.innerHTML = '<h1>no pastes found</h1>';
return; return;
} }
try {
json = JSON.parse(data);
if (json.error != null) {
pastesWrapper.innerHTML = `<h1>${json.error}</h1>`;
return;
}
}
catch {
}
pastesWrapper.innerHTML = data; pastesWrapper.innerHTML = data;
}); });
} }
+21
View File
@@ -1,11 +1,13 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Mono:wght@100..900&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Mono:wght@100..900&display=swap" rel="stylesheet">
<title>create paste</title> <title>create paste</title>
</head> </head>
<body> <body>
<div class="nav-div"> <div class="nav-div">
<a href="/">home</a> <a href="/">home</a>
@@ -25,6 +27,7 @@
</form> </form>
</div> </div>
</div> </div>
</body> </body>
<script> <script>
document.getElementById("createForm").addEventListener("submit", function (event) { document.getElementById("createForm").addEventListener("submit", function (event) {
@@ -54,6 +57,8 @@
}); });
</script> </script>
<style> <style>
body { body {
font-family: "Noto Sans Mono", "Consolas", "SF Mono", monospace; font-family: "Noto Sans Mono", "Consolas", "SF Mono", monospace;
font-weight: bold; font-weight: bold;
@@ -62,7 +67,9 @@ body{
justify-content: center; justify-content: center;
align-items: center; align-items: center;
background-color: #0d0d0d; background-color: #0d0d0d;
position: relative;
} }
.container-wrapper { .container-wrapper {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@@ -71,9 +78,11 @@ body{
width: 100%; width: 100%;
height: 98.7vh; height: 98.7vh;
} }
#pasteContent { #pasteContent {
max-height: 500px; max-height: 500px;
} }
.creation-container { .creation-container {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@@ -89,15 +98,18 @@ body{
overflow-y: auto; overflow-y: auto;
border: #222222 2px solid; border: #222222 2px solid;
} }
#createForm { #createForm {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
width: 100%; width: 100%;
} }
.label { .label {
font-size: 1.5em; font-size: 1.5em;
} }
.textinput { .textinput {
transition: 300ms; transition: 300ms;
width: 100%; width: 100%;
@@ -113,12 +125,14 @@ body{
font-size: 1.1em; font-size: 1.1em;
outline: none; outline: none;
} }
.textinput:focus { .textinput:focus {
transition: 300ms; transition: 300ms;
background-color: #333333; background-color: #333333;
border: 2px solid #3a3a3a; border: 2px solid #3a3a3a;
outline: none; outline: none;
} }
.textarea { .textarea {
transition: 300ms; transition: 300ms;
width: 100%; width: 100%;
@@ -137,12 +151,14 @@ body{
font-size: 1.08em; font-size: 1.08em;
outline: none; outline: none;
} }
.textarea:focus { .textarea:focus {
transition: 300ms; transition: 300ms;
background-color: #333333; background-color: #333333;
border: 2px solid #3a3a3a; border: 2px solid #3a3a3a;
outline: none; outline: none;
} }
.button { .button {
transition: 300ms; transition: 300ms;
width: 100%; width: 100%;
@@ -156,11 +172,13 @@ body{
cursor: pointer; cursor: pointer;
font-size: 1.2em; font-size: 1.2em;
} }
.button:hover { .button:hover {
transition: 300ms; transition: 300ms;
background-color: #333333; background-color: #333333;
border: 2px solid #3a3a3a; border: 2px solid #3a3a3a;
} }
.nav-div { .nav-div {
top: 0; top: 0;
margin-top: 10px; margin-top: 10px;
@@ -179,6 +197,7 @@ body{
overflow-y: auto; overflow-y: auto;
border: #222222 2px solid; border: #222222 2px solid;
} }
.nav-div a { .nav-div a {
text-decoration: none; text-decoration: none;
color: white; color: white;
@@ -189,10 +208,12 @@ body{
transition: 300ms; transition: 300ms;
border: #2a2a2a00 2px solid; border: #2a2a2a00 2px solid;
} }
.nav-div a:hover { .nav-div a:hover {
transition: 300ms; transition: 300ms;
background-color: #333333; background-color: #333333;
border: #3a3a3a 2px solid; border: #3a3a3a 2px solid;
} }
</style> </style>
</html> </html>
+1 -1
View File
@@ -24,7 +24,7 @@
<label id="characterCount" for="characterCount" class="ccounter">0/20</label> <label id="characterCount" for="characterCount" class="ccounter">0/20</label>
<label for="passwordTitle" class="label" id="margin-top">Password</label> <label for="passwordTitle" class="label" id="margin-top">Password</label>
<input type="password" id="passwordInput" class="textinput" name="pasteTitle" required maxlength="50" minlength="8"> <input type="password" id="passwordInput" class="textinput" name="pasteTitle" required maxlength="50" minlength="8">
<label id="passcharacterCount" for="characterCount" class="ccounter">0/20</label> <label id="passcharacterCount" for="characterCount" class="ccounter">0/50</label>
<button type="submit" class="button" id="button-margin-top">Sign-up</button> <button type="submit" class="button" id="button-margin-top">Sign-up</button>
</form> </form>
<h3 id="error-message"></h3> <h3 id="error-message"></h3>