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/config.json
/PasteBin/Encryption.cs
/PasteBin/.config
+441 -25
View File
@@ -5,11 +5,12 @@ using Newtonsoft.Json.Linq;
using System.Data;
using System.Text;
using Sharpbin;
using System.Security.Cryptography;
class Program
{
private static string salt = string.Empty;
private static string smallerSalt = string.Empty;
public static Dictionary<int, string> accountType = new Dictionary<int, string>
{
{ 0, "User" },
@@ -76,7 +77,7 @@ class Program
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"]);
if (loggedIn)
{
@@ -96,6 +97,17 @@ class Program
await context.Response.WriteAsync(html);
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) =>
{
if (await IsLoggedInAsync(context.Request.Cookies["token"]))
@@ -103,7 +115,7 @@ class Program
context.Response.Redirect("/");
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>");
context.Response.ContentType = "text/html";
await context.Response.WriteAsync(html);
@@ -116,7 +128,7 @@ class Program
context.Response.Redirect("/");
return;
}
var html = File.ReadAllText("assets\\signup.html");
var html = File.ReadAllText("assets/signup.html");
html = html.Replace("{html}", "<a href=\"/login\">login</a>");
context.Response.ContentType = "text/html";
await context.Response.WriteAsync(html);
@@ -197,15 +209,15 @@ class Program
}
string totalSizeString = ConvertToBytes(totalSize.ToString());
var html = File.ReadAllText("assets\\dash.html");
var html = File.ReadAllText("assets/dash.html");
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"))
{
await connection.OpenAsync();
var usersCommand = connection.CreateCommand();
usersCommand.CommandText = "SELECT * FROM users";
usersCommand.CommandText = "SELECT * FROM users LIMIT 10";
var usersReader = await usersCommand.ExecuteReaderAsync();
List<User> users = new List<User>();
while (await usersReader.ReadAsync())
@@ -266,7 +278,7 @@ class Program
app.MapGet("/paste-not-found", async (HttpContext context) =>
{
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("{message}", "Paste not found");
bool loggedIn = await IsLoggedInAsync(context.Request.Cookies["token"]);
@@ -285,7 +297,7 @@ class Program
app.MapGet("/unauthorized", async (HttpContext context) =>
{
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("{message}", "Unauthorized");
bool loggedIn = await IsLoggedInAsync(context.Request.Cookies["token"]);
@@ -304,7 +316,7 @@ class Program
app.MapGet("/banned", async (HttpContext context) =>
{
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"]);
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("{pastetitle}", title);
html = html.Replace("{content}", content);
@@ -445,7 +457,7 @@ class Program
await context.Response.WriteAsync(html);
return;
}
});
}).RequireRateLimiting("fixed-bigger");
app.MapGet("/raw/{id}", async (HttpContext context) =>
{
var id = context.Request?.RouteValues?["id"]?.ToString();
@@ -458,10 +470,10 @@ class Program
context.Response.ContentType = "text/plain";
await context.Response.WriteAsync(content);
return;
});
}).RequireRateLimiting("fixed-bigger");
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"]);
if (loggedIn)
{
@@ -518,7 +530,7 @@ class Program
}).RequireRateLimiting("fixed-bigger");
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();
bool loggedIn = await IsLoggedInAsync(context.Request.Cookies["token"]);
@@ -603,7 +615,7 @@ class Program
app.MapGet("/u/{username}", async (HttpContext context) =>
{
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"))
{
await connection.OpenAsync();
@@ -614,7 +626,7 @@ class Program
await reader.ReadAsync();
if (!reader.HasRows)
{
html = File.ReadAllText(@"assets\error.html");
html = File.ReadAllText(@"assets/error.html");
html = html.Replace("{code}", "404");
html = html.Replace("{message}", "User not found");
context.Response.ContentType = "text/html";
@@ -696,7 +708,7 @@ class Program
app.MapGet("/uid/{uid}", async (HttpContext context) =>
{
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"))
{
await connection.OpenAsync();
@@ -707,7 +719,7 @@ class Program
await reader.ReadAsync();
if (!reader.HasRows)
{
html = File.ReadAllText(@"assets\error.html");
html = File.ReadAllText(@"assets/error.html");
html = html.Replace("{code}", "404");
html = html.Replace("{message}", "User not found");
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"))
{
await connection.OpenAsync();
@@ -817,7 +829,7 @@ class Program
await reader.ReadAsync();
if (!reader.HasRows)
{
html = File.ReadAllText(@"assets\error.html");
html = File.ReadAllText(@"assets/error.html");
html = html.Replace("{code}", "404");
html = html.Replace("{message}", "User not found");
context.Response.ContentType = "text/html";
@@ -1004,6 +1016,399 @@ class Program
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["message"] = "User banned" }.ToString());
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
@@ -1447,8 +1852,8 @@ class Program
reader.Close();
}
ip = Convert.ToBase64String(SHA1.HashData(Encoding.UTF8.GetBytes(log.IP)));
token = Convert.ToBase64String(Encoding.UTF8.GetBytes(BCrypt.Net.BCrypt.HashPassword(Guid.NewGuid().ToString())));
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(), smallerSalt)));
passwordHash = BCrypt.Net.BCrypt.HashPassword(password, salt);
var insertCommand = connection.CreateCommand();
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;
}
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);
using (var connection = new SqliteConnection("Data Source=pastes.sqlite"))
@@ -1558,7 +1963,7 @@ class Program
}
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);
var loginCommand = connection.CreateCommand();
@@ -1776,13 +2181,17 @@ class Program
{
var config = JObject.Parse(File.ReadAllText("config.json"));
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() ?? "";
}
else
{
var config = new JObject();
config["Salt"] = BCrypt.Net.BCrypt.GenerateSalt(13);
config["SmallerSalt"] = BCrypt.Net.BCrypt.GenerateSalt(8);
salt = config["Salt"]?.ToString() ?? BCrypt.Net.BCrypt.GenerateSalt(13);
smallerSalt = config["SmallerSalt"]?.ToString() ?? BCrypt.Net.BCrypt.GenerateSalt(8);
File.WriteAllText("config.json", config.ToString());
}
if (!Directory.Exists("pastes"))
@@ -1795,6 +2204,13 @@ class Program
return new string(Enumerable.Repeat(chars, length)
.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
{
+1 -1
View File
@@ -4,7 +4,7 @@
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://*:29219",
"applicationUrl": "http://localhost:29219",
"sslPort": 44358
}
},
+58
View File
@@ -13,6 +13,34 @@
<None Remove="pastes\**" />
</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>
<PackageReference Include="BCrypt.Net-Next" Version="4.0.3" />
<PackageReference Include="Microsoft.Data.Sqlite" Version="8.0.8" />
@@ -23,4 +51,34 @@
<Folder Include="wwwroot\" />
</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>
+78 -9
View File
@@ -40,7 +40,7 @@
<div class="accounts-wrapper">
<h3>Accounts</h3>
<input type="text" placeholder="search" class="text-input" oninput="search()">
<div class="list-container">
<div class="list-container" onscroll="getUsers()">
{accounts}
</div>
</div>
@@ -51,6 +51,7 @@
</div>
</body>
<script>
let searchTimeout;
function localizeDateTime(unixTimestamp) {
const date = new Date(unixTimestamp * 1000);
return date.toLocaleString();
@@ -66,24 +67,92 @@
creationdateElement.innerText = "Creation Date: " + localizeDateTime(parseInt(creationdateText));
lastlogindateElement.innerText = "Last Login Date: " + localizeDateTime(parseInt(lastlogindateText));
});
function waitSearch() {
clearTimeout(searchTimeout);
searchTimeout = setTimeout(search, 200);
}
function search() {
const input = document.querySelector('.text-input').value;
const accountWrapper = document.querySelector('.accounts-wrapper');
const accounts = accountWrapper.querySelectorAll('.list-a');
accounts.forEach(account => {
const username = account.querySelector('.list-item').innerText;
if (username.toLowerCase().includes(input.toLowerCase())) {
account.style.display = 'flex';
} else {
account.style.display = 'none';
if (input.length == 0){
fetch(`/api/accounts/admin/get?html=true`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
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>
<style>
.list-container {
max-height: 100%;
overflow-y: auto;
overflow-y: scroll;
display: flex;
flex-direction: column;
width: 100%;
+95 -4
View File
@@ -32,7 +32,7 @@
<h2 style="text-align: center;">Actions</h2>
<div class="button-wrapper">
<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 class="pastes-wrapper">
@@ -45,6 +45,9 @@
</div>
</div>
<div class="notification-div" id="notification">
<h2 id="notification-text"></h2>
</div>
</body>
<script>
function localizeDateTime(unixTimestamp) {
@@ -79,17 +82,104 @@
.then(obj => {
const result = JSON.parse(obj);
if (result.message != null) {
alert(result.message);
notification(`${result.message} for ${reason}`);
} 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>
<style>
@keyframes hoverup {
0% {
transform: translateY(100%);
}
h3{
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 {
word-break: keep-all;
margin-top: -5px;
}
@@ -164,6 +254,7 @@
justify-content: center;
align-items: center;
background-color: #0d0d0d;
position: relative;
}
.container-wrapper {
+21 -2
View File
@@ -40,11 +40,11 @@
function searchPastes() {
const searchInput = document.querySelector('.text-input');
if (searchInput.value.length < 3 && searchInput.value.length != 0){
if (searchInput.value.length < 3 && searchInput.value.length != 0) {
return;
}
else if (searchInput.value.length == 0) {
fetch(`/api/pastes/search?html=true`,{
fetch(`/api/pastes/search?html=true`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
@@ -60,6 +60,16 @@
pastesWrapper.innerHTML = '<h1>no pastes found</h1>';
return;
}
try {
json = JSON.parse(data);
if (json.error != null) {
pastesWrapper.innerHTML = `<h1>${json.error}</h1>`;
return;
}
}
catch {
}
pastesWrapper.innerHTML = data;
});
return;
@@ -80,6 +90,15 @@
pastesWrapper.innerHTML = '<h1>no pastes found</h1>';
return;
}
try {
json = JSON.parse(data);
if (json.error != null) {
pastesWrapper.innerHTML = `<h1>${json.error}</h1>`;
return;
}
}
catch {
}
pastesWrapper.innerHTML = data;
});
}
+51 -30
View File
@@ -1,11 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<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">
<title>create paste</title>
</head>
<body>
<div class="nav-div">
<a href="/">home</a>
@@ -25,6 +27,7 @@
</form>
</div>
</div>
</body>
<script>
document.getElementById("createForm").addEventListener("submit", function (event) {
@@ -54,7 +57,9 @@
});
</script>
<style>
body{
body {
font-family: "Noto Sans Mono", "Consolas", "SF Mono", monospace;
font-weight: bold;
display: flex;
@@ -62,19 +67,23 @@ body{
justify-content: center;
align-items: center;
background-color: #0d0d0d;
}
.container-wrapper{
position: relative;
}
.container-wrapper {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 100%;
height: 98.7vh;
}
#pasteContent {
}
#pasteContent {
max-height: 500px;
}
.creation-container{
}
.creation-container {
display: flex;
flex-direction: column;
align-items: center;
@@ -88,17 +97,20 @@ body{
min-height: 20%;
overflow-y: auto;
border: #222222 2px solid;
}
#createForm{
}
#createForm {
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
}
.label{
}
.label {
font-size: 1.5em;
}
.textinput{
}
.textinput {
transition: 300ms;
width: 100%;
padding: 10px;
@@ -112,14 +124,16 @@ body{
font-family: "Noto Sans Mono", "Consolas", "SF Mono", monospace;
font-size: 1.1em;
outline: none;
}
.textinput:focus{
}
.textinput:focus {
transition: 300ms;
background-color: #333333;
border: 2px solid #3a3a3a;
outline: none;
}
.textarea{
}
.textarea {
transition: 300ms;
width: 100%;
min-width: 100%;
@@ -136,14 +150,16 @@ body{
font-family: "Noto Sans Mono", "Consolas", "SF Mono", monospace;
font-size: 1.08em;
outline: none;
}
.textarea:focus{
}
.textarea:focus {
transition: 300ms;
background-color: #333333;
border: 2px solid #3a3a3a;
outline: none;
}
.button{
}
.button {
transition: 300ms;
width: 100%;
padding: 10px;
@@ -155,13 +171,15 @@ body{
border: #2a2a2a00 2px solid;
cursor: pointer;
font-size: 1.2em;
}
.button:hover{
}
.button:hover {
transition: 300ms;
background-color: #333333;
border: 2px solid #3a3a3a;
}
.nav-div{
}
.nav-div {
top: 0;
margin-top: 10px;
position: absolute;
@@ -178,8 +196,9 @@ body{
height: fit-content;
overflow-y: auto;
border: #222222 2px solid;
}
.nav-div a{
}
.nav-div a {
text-decoration: none;
color: white;
padding: 10px;
@@ -188,11 +207,13 @@ body{
background-color: #222222;
transition: 300ms;
border: #2a2a2a00 2px solid;
}
.nav-div a:hover{
}
.nav-div a:hover {
transition: 300ms;
background-color: #333333;
border: #3a3a3a 2px solid;
}
}
</style>
</html>
+1 -1
View File
@@ -24,7 +24,7 @@
<label id="characterCount" for="characterCount" class="ccounter">0/20</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">
<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>
</form>
<h3 id="error-message"></h3>