Add private pastes, user bans, and UI enhancements

Enhanced Program.cs with response caching, compression, CORS policy, and private paste handling.
Refactored user ban logic and added expiration date handling.
Improved admin.html with localization and overflow handling.
Introduced PrivatePaste and Punishment classes.
Enhanced Paste and User classes for private pastes and punishments.
Updated initialization logic for punishedUsers table.
Ensured salts are written back to config.json if generated.
Enhanced user.html with ban/unban functionality and animations.
Improved archives.html, dash.html, and index.html with new UI elements and styles.
Added asynchronous content loading and notifications to paste.html.
Introduced Encryption.cs for AES encryption and decryption.
Created banned.html for displaying error messages.
Added privatepaste.html with dynamic content, password protection, and user interactions.
This commit is contained in:
whoswhip
2024-09-08 16:07:59 -04:00
parent 4791b32400
commit 560ad071ab
14 changed files with 1255 additions and 133 deletions
-1
View File
@@ -374,5 +374,4 @@ PasteBin/p/2d48a001-383d-44fd-8553-4806c9de100d.html
*.sqlite-journal *.sqlite-journal
/PasteBin/logs.txt /PasteBin/logs.txt
/PasteBin/config.json /PasteBin/config.json
/PasteBin/Encryption.cs
/PasteBin/.config /PasteBin/.config
+63
View File
@@ -0,0 +1,63 @@
using System.Security.Cryptography;
using System.Text;
namespace Sharpbin
{
public class Encryption
{
public static string EncryptString(string input, string password)
{
byte[] encryptedBytes;
using (Aes aes = Aes.Create())
{
aes.KeySize = 256;
aes.Key = Encoding.UTF8.GetBytes(password.PadRight(32, ' '));
aes.IV = new byte[16];
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
using (var ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
byte[] inputBytes = Encoding.UTF8.GetBytes(input);
cs.Write(inputBytes, 0, inputBytes.Length);
}
encryptedBytes = ms.ToArray();
}
}
return Convert.ToBase64String(encryptedBytes);
}
public static string DecryptString(string input, string password)
{
byte[] encryptedBytes = Convert.FromBase64String(input);
string decryptedText;
using (Aes aes = Aes.Create())
{
aes.KeySize = 256;
aes.Key = Encoding.UTF8.GetBytes(password.PadRight(32, ' '));
aes.IV = new byte[16];
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
using (var ms = new MemoryStream(encryptedBytes))
{
using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
{
using (var sr = new StreamReader(cs))
{
decryptedText = sr.ReadToEnd();
}
}
}
}
return decryptedText;
}
}
}
+336 -68
View File
@@ -5,6 +5,8 @@ using Newtonsoft.Json.Linq;
using System.Data; using System.Data;
using System.Text; using System.Text;
using Sharpbin; using Sharpbin;
using Microsoft.AspNetCore.ResponseCompression;
using System.Reflection.Metadata;
class Program class Program
{ {
@@ -34,6 +36,8 @@ class Program
// Add services to the container. // Add services to the container.
builder.Services.AddRazorPages(); builder.Services.AddRazorPages();
builder.Services.AddCors(); builder.Services.AddCors();
builder.Services.AddResponseCaching();
builder.Services.AddResponseCompression();
builder.Services.AddRateLimiter(_ => _ builder.Services.AddRateLimiter(_ => _
@@ -62,14 +66,23 @@ class Program
app.UseHsts(); app.UseHsts();
} }
app.UseHttpsRedirection();
//app.UseHttpsRedirection();
app.UseStaticFiles(); app.UseStaticFiles();
app.UseRouting(); app.UseRouting();
app.UseRateLimiter(); app.UseRateLimiter();
app.UseCors(builder =>
{
builder.AllowAnyOrigin();
builder.AllowAnyMethod();
builder.AllowAnyHeader();
});
app.UseAuthorization(); app.UseAuthorization();
app.UseResponseCaching();
app.UseResponseCompression();
app.MapRazorPages(); app.MapRazorPages();
@@ -83,10 +96,19 @@ class Program
{ {
var user = await GetLoggedInUserAsync(context.Request.Cookies["token"]); var user = await GetLoggedInUserAsync(context.Request.Cookies["token"]);
if (user.State != 0) if (user.State != 0)
{
var punishment = await GetPunishmentAsync(user.UUID);
var unixNow = DateTimeOffset.Now.ToUnixTimeSeconds();
if (punishment.ExpirationDate > unixNow)
{ {
context.Response.Redirect("/banned"); context.Response.Redirect("/banned");
return; return;
} }
else
{
await UnbanUUIDAsync(user.UUID);
}
}
html = html.Replace("{html}", "<a href=\"/dash\">dashboard</a>"); html = html.Replace("{html}", "<a href=\"/dash\">dashboard</a>");
} }
else else
@@ -316,24 +338,34 @@ 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/banned.html");
bool loggedIn = await IsLoggedInAsync(context.Request.Cookies["token"]); bool loggedIn = await IsLoggedInAsync(context.Request.Cookies["token"]);
var user = new User();
if (loggedIn) if (loggedIn)
{ {
var user = await GetLoggedInUserAsync(context.Request.Cookies["token"]); user = await GetLoggedInUserAsync(context.Request.Cookies["token"]);
if (user.State != 1) if (user.State != 1 && user.State != 2)
{ {
context.Response.Redirect("/unauthorized"); context.Response.Redirect("/");
return; return;
} }
error_html = error_html.Replace("{html}", "<a href=\"/dash\">dashboard</a>"); error_html = error_html.Replace("{html}", "<a href=\"/dash\">dashboard</a>");
} }
else else
{ {
error_html = error_html.Replace("{html}", "<a href=\"/login\">login</a> <a href=\"/sign-up\">sign up</a>"); context.Response.Redirect("/");
return;
}
var punishment = await GetPunishmentAsync(user.UUID);
var unixNow = DateTimeOffset.Now.ToUnixTimeSeconds();
if (punishment.ExpirationDate < unixNow)
{
await UnbanUUIDAsync(user.UUID);
context.Response.Redirect("/");
return;
} }
error_html = error_html.Replace("{code}", "403"); error_html = error_html.Replace("{code}", "403");
error_html = error_html.Replace("{message}", "You are banned"); error_html = error_html.Replace("{message}", $"You are banned until <a id=\"unix-date\">{punishment.ExpirationDate}</a> for \"{punishment.Reason}\"");
context.Response.ContentType = "text/html"; context.Response.ContentType = "text/html";
await context.Response.WriteAsync(error_html); await context.Response.WriteAsync(error_html);
return; return;
@@ -407,12 +439,6 @@ class Program
{ {
user.Username = $"<a class=\"user-a\" href=\"/u/{user.Username}\">{user.Username}</a>"; user.Username = $"<a class=\"user-a\" href=\"/u/{user.Username}\">{user.Username}</a>";
} }
if (paste.Visibility == "Private")
{
// WIP Private pastes will be implemented soon enough, most likely with a password or longer ID
context.Response.StatusCode = 404;
return;
}
if (paste.Title == "" || string.IsNullOrEmpty(paste.Title)) if (paste.Title == "" || string.IsNullOrEmpty(paste.Title))
{ {
paste.Title = $"Untitled {reader.GetString(0)}"; paste.Title = $"Untitled {reader.GetString(0)}";
@@ -425,6 +451,11 @@ class Program
var html = File.ReadAllText("assets/paste.html"); var html = File.ReadAllText("assets/paste.html");
if (paste.Visibility == "Private")
{
html = File.ReadAllText("assets/privatepaste.html");
html = html.Replace("{password}", "");
}
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);
@@ -461,16 +492,69 @@ class Program
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();
if (!File.Exists($"pastes/{id}.txt")) var filePath = $"pastes/{id}.txt";
if (!File.Exists(filePath))
{ {
context.Response.StatusCode = 404; context.Response.StatusCode = 404;
return; return;
} }
var content = File.ReadAllText($"pastes/{id}.txt"); if (id.Length == 24)
context.Response.ContentType = "text/plain"; {
await context.Response.WriteAsync(content); var password = context.Request?.Query["password"].ToString();
if (string.IsNullOrEmpty(password))
{
context.Response.StatusCode = 401;
return; return;
}
using (var connection = new SqliteConnection("Data Source=pastes.sqlite"))
{
await connection.OpenAsync();
var command = connection.CreateCommand();
command.CommandText = "SELECT * FROM pastes WHERE ID = @ID";
command.Parameters.AddWithValue("@ID", id);
var reader = await command.ExecuteReaderAsync();
await reader.ReadAsync();
if (!reader.HasRows)
{
context.Response.StatusCode = 404;
return;
}
var paste = new PrivatePaste
{
Title = reader.GetString(1),
UnixDate = long.Parse(reader.GetString(2)),
Size = reader.GetString(3),
Visibility = reader.GetString(4),
Id = id,
Uploader = reader.GetString(6),
Password = reader.GetString(7),
};
string hashedPassword = BCrypt.Net.BCrypt.HashPassword(password, salt);
if (hashedPassword != paste.Password && paste.Visibility != "Private")
{
context.Response.StatusCode = 401;
return;
}
string text = Encryption.DecryptString(await File.ReadAllTextAsync(filePath), password);
context.Response.ContentType = "text/plain";
await context.Response.WriteAsync(text);
return;
}
}
var fileInfo = new FileInfo(filePath);
var fileSize = fileInfo.Length;
context.Response.ContentType = "text/plain";
context.Response.ContentLength = fileSize;
using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
await fileStream.CopyToAsync(context.Response.Body);
}
}).RequireRateLimiting("fixed-bigger"); }).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");
@@ -661,6 +745,10 @@ class Program
Visibility = pastesReader.GetString(4), Visibility = pastesReader.GetString(4),
Id = pastesReader.GetString(5), Id = pastesReader.GetString(5),
}; };
if (paste.Visibility == "Private" || paste.Visibility == "Unlisted")
{
continue;
}
pastes.Add(paste); pastes.Add(paste);
} }
string pasteList = string.Empty; string pasteList = string.Empty;
@@ -754,6 +842,10 @@ class Program
Visibility = pastesReader.GetString(4), Visibility = pastesReader.GetString(4),
Id = pastesReader.GetString(5), Id = pastesReader.GetString(5),
}; };
if (paste.Visibility == "Private" || paste.Visibility == "Unlisted")
{
continue;
}
pastes.Add(paste); pastes.Add(paste);
} }
string pasteList = string.Empty; string pasteList = string.Empty;
@@ -949,6 +1041,8 @@ class Program
var data = JObject.Parse(requestBody); var data = JObject.Parse(requestBody);
var uuid = SanitizeInput(data["uuid"]?.ToString() ?? ""); var uuid = SanitizeInput(data["uuid"]?.ToString() ?? "");
var reason = SanitizeInput(data["reason"]?.ToString() ?? "No reason provided"); var reason = SanitizeInput(data["reason"]?.ToString() ?? "No reason provided");
var expiration = SanitizeInput(data["expiration"]?.ToString() ?? "64060635661");
try { DateTimeOffset.FromUnixTimeSeconds(long.Parse(expiration)); } catch { expiration = "64060635661"; }
if (string.IsNullOrEmpty(uuid) || string.IsNullOrWhiteSpace(uuid)) if (string.IsNullOrEmpty(uuid) || string.IsNullOrWhiteSpace(uuid))
{ {
context.Response.StatusCode = 400; context.Response.StatusCode = 400;
@@ -1003,10 +1097,11 @@ class Program
await banUserCommand.ExecuteNonQueryAsync(); await banUserCommand.ExecuteNonQueryAsync();
var punishedUsersCommand = connection.CreateCommand(); var punishedUsersCommand = connection.CreateCommand();
punishedUsersCommand.CommandText = "INSERT INTO punishedUsers (UUID,State, Reason, Punisher) VALUES (@UUID, @State, @Reason, @Punisher)"; punishedUsersCommand.CommandText = "INSERT INTO punishedUsers (UUID,State, Reason,ExpirationDate, Punisher) VALUES (@UUID, @State, @Reason,@ExpirationDate, @Punisher)";
punishedUsersCommand.Parameters.AddWithValue("@UUID", uuid); punishedUsersCommand.Parameters.AddWithValue("@UUID", uuid);
punishedUsersCommand.Parameters.AddWithValue("@State", 1); punishedUsersCommand.Parameters.AddWithValue("@State", 1);
punishedUsersCommand.Parameters.AddWithValue("@Reason", reason); punishedUsersCommand.Parameters.AddWithValue("@Reason", reason);
punishedUsersCommand.Parameters.AddWithValue("@ExpirationDate", expiration);
punishedUsersCommand.Parameters.AddWithValue("@Punisher", loggedInUser.UUID); punishedUsersCommand.Parameters.AddWithValue("@Punisher", loggedInUser.UUID);
await punishedUsersCommand.ExecuteNonQueryAsync(); await punishedUsersCommand.ExecuteNonQueryAsync();
} }
@@ -1067,52 +1162,9 @@ class Program
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Invalid request body" }.ToString()); await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Invalid request body" }.ToString());
return; return;
} }
var user = new User(); var user = await UnbanUUIDAsync(uuid);
using (var connection = new SqliteConnection("Data Source = pastes.sqlite")) Console.WriteLine($"[{DateTime.Now}] Account {user.Username}({user.UUID}) has been unbanned by {loggedInUser.Username}({loggedInUser.UUID}) for {reason}");
{ await File.AppendAllTextAsync("logs.log", $"[{DateTime.Now}] Account {user.Username}({user.UUID}) has been unbanned by {loggedInUser.Username}({loggedInUser.UUID}) for {reason}\n");
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.StatusCode = 200;
context.Response.ContentType = "application/json"; context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["message"] = "User unbanned" }.ToString()); await context.Response.WriteAsJsonAsync(new JObject { ["message"] = "User unbanned" }.ToString());
@@ -1480,7 +1532,6 @@ class Program
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Content or Title is too long" }.ToString()); await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Content or Title is too long" }.ToString());
return; return;
} }
if (visibility != "Public" && visibility != "Unlisted" && visibility != "Private") if (visibility != "Public" && visibility != "Unlisted" && visibility != "Private")
{ {
context.Response.StatusCode = 400; context.Response.StatusCode = 400;
@@ -1495,8 +1546,45 @@ class Program
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Invalid request body" }.ToString()); await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Invalid request body" }.ToString());
return; return;
} }
var paste = new Paste();
if (visibility == "Private")
{
var password = SanitizeInput(data["password"]?.ToString() ?? GenerateRandomPassword(30));
var privatePaste = await CreatePrivatePaste(title, content, password, uploaderUUID);
if (privatePaste == null)
{
context.Response.StatusCode = 500;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Failed to create paste" }.ToString());
return;
}
if (!File.Exists($"pastes/{privatePaste.Id}.txt"))
{
context.Response.StatusCode = 500;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Failed to create paste" }.ToString());
return;
}
context.Response.StatusCode = 200;
context.Response.ContentType = "application/json";
string _time = DateTimeOffset.FromUnixTimeSeconds(privatePaste.UnixDate ?? 0).ToString().Split("+")[0].TrimEnd();
JObject _responseJson = new JObject();
_responseJson["pasteId"] = privatePaste.Id;
_responseJson["pasteSize"] = ConvertToBytes(privatePaste.Size ?? string.Empty);
_responseJson["pasteDate"] = _time;
_responseJson["pasteVisibility"] = privatePaste.Visibility;
Log _log = await Logging.LogRequestAsync(context);
Console.WriteLine($"[{_time}] Private Paste created, {ConvertToBytes(privatePaste.Size ?? string.Empty)}, {privatePaste.Id} by {uploaderUUID}");
await File.AppendAllTextAsync("logs.log", $"[{_time}] {privatePaste.Id} {_log.IP} {_log.Method} {_log.Path} {_log.UserAgent} {_log.Referer} {_log.Body} {uploaderUUID}\n");
await context.Response.WriteAsJsonAsync(_responseJson.ToString());
return;
}
else
{
paste = await CreatePaste(content, title, visibility, uploaderUUID);
}
var paste = await CreatePaste(content, title, visibility, uploaderUUID);
if (!File.Exists($"pastes/{paste?.Id}.txt") || paste == null) if (!File.Exists($"pastes/{paste?.Id}.txt") || paste == null)
{ {
@@ -1768,6 +1856,83 @@ class Program
} }
}).RequireRateLimiting("fixed"); }).RequireRateLimiting("fixed");
app.MapPost("/api/pastes/password/{pasteid}", async (HttpContext context) =>
{
var body = await new StreamReader(context.Request.Body).ReadToEndAsync();
if (string.IsNullOrEmpty(body))
{
context.Response.StatusCode = 400;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "No data uploaded" }.ToString());
return;
}
try
{
JObject.Parse(body);
}
catch
{
context.Response.StatusCode = 400;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Invalid JSON" }.ToString());
return;
}
var data = JObject.Parse(body);
var password = SanitizeInput(data["password"]?.ToString() ?? "");
var pasteId = context.Request.RouteValues["pasteid"].ToString();
if (string.IsNullOrEmpty(password) || string.IsNullOrWhiteSpace(password))
{
context.Response.StatusCode = 400;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Invalid request body" }.ToString());
return;
}
if (!File.Exists($"pastes/{pasteId}.txt"))
{
context.Response.StatusCode = 404;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Paste not found" }.ToString());
return;
}
using (var connection = new SqliteConnection("Data Source=pastes.sqlite"))
{
await connection.OpenAsync();
var command = connection.CreateCommand();
command.CommandText = "SELECT * FROM pastes WHERE ID = @ID";
command.Parameters.AddWithValue("@ID", pasteId);
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"] = "Paste not found" }.ToString());
return;
}
var paste = new PrivatePaste
{
Id = reader.GetString(5),
Title = reader.GetString(1),
Size = reader.GetString(3),
UnixDate = long.Parse(reader.GetString(2)),
Visibility = reader.GetString(4),
Password = reader.GetString(7),
};
string passwordHash = BCrypt.Net.BCrypt.HashPassword(password, salt);
if (paste.Password != passwordHash)
{
context.Response.StatusCode = 401;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Invalid password" }.ToString());
return;
}
}
string decryptedText = Encryption.DecryptString(File.ReadAllText($"pastes/{pasteId}.txt"), password);
context.Response.StatusCode = 200;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["content"] = decryptedText }.ToString());
});
app.MapPost("/api/accounts/create", async (HttpContext context) => app.MapPost("/api/accounts/create", async (HttpContext context) =>
{ {
@@ -2040,6 +2205,37 @@ class Program
} }
return paste; return paste;
} }
public static async Task<PrivatePaste> CreatePrivatePaste(string title, string content, string password, string UUID)
{
string encryptedText = Encryption.EncryptString($"{content}", password);
string passwordHash = BCrypt.Net.BCrypt.HashPassword(password, salt);
var paste = new PrivatePaste
{
Title = title,
UnixDate = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
Size = content.Length.ToString(),
Id = GenerateRandomString(24),
Uploader = UUID,
Password = passwordHash
};
await File.WriteAllTextAsync($"pastes/{paste.Id}.txt", encryptedText);
using (var connection = new SqliteConnection("Data Source=pastes.sqlite"))
{
await connection.OpenAsync();
var command = connection.CreateCommand();
command.CommandText = "INSERT INTO pastes (Title, Date, Size, Visibility, ID, Uploader, PasswordHash) VALUES (@Title, @Date, @Size, @Visibility, @ID, @Uploader, @PasswordHash)";
command.Parameters.AddWithValue("@Title", paste.Title);
command.Parameters.AddWithValue("@Date", paste.UnixDate);
command.Parameters.AddWithValue("@Size", paste.Size);
command.Parameters.AddWithValue("@Visibility", "Private");
command.Parameters.AddWithValue("@ID", paste.Id);
command.Parameters.AddWithValue("@Uploader", paste.Uploader);
command.Parameters.AddWithValue("@PasswordHash", paste.Password);
await command.ExecuteNonQueryAsync();
}
return paste;
}
public static string SanitizeInput(string input) public static string SanitizeInput(string input)
{ {
return input?.Replace("<", "&lt;").Replace(">", "&gt;") ?? string.Empty + input; return input?.Replace("<", "&lt;").Replace(">", "&gt;") ?? string.Empty + input;
@@ -2153,6 +2349,63 @@ class Program
}; };
} }
} }
public static async Task<Punishment> GetPunishmentAsync(string UUID)
{
using (var connection = new SqliteConnection("Data Source=pastes.sqlite"))
{
await connection.OpenAsync();
var command = connection.CreateCommand();
command.CommandText = "SELECT * FROM punishedUsers WHERE UUID = @UUID";
command.Parameters.AddWithValue("@UUID", UUID);
var reader = await command.ExecuteReaderAsync();
await reader.ReadAsync();
if (!reader.HasRows || reader.IsDBNull(3))
{
return new Punishment();
}
return new Punishment
{
UUID = reader.GetString(0),
State = reader.GetInt32(1),
Reason = reader.GetString(2),
ExpirationDate = long.Parse(reader.GetString(3)),
Punisher = reader.GetString(4)
};
}
}
public static async Task<User> UnbanUUIDAsync(string UUID)
{
User user = new User();
using (var connection = new SqliteConnection("Data Source=pastes.sqlite"))
{
await connection.OpenAsync();
var command = connection.CreateCommand();
command.CommandText = "DELETE FROM punishedUsers WHERE UUID = @UUID";
command.Parameters.AddWithValue("@UUID", UUID);
await command.ExecuteNonQueryAsync();
var userCommand = connection.CreateCommand();
userCommand.CommandText = "UPDATE users SET State = 0 WHERE UUID = @UUID";
userCommand.Parameters.AddWithValue("@UUID", UUID);
await userCommand.ExecuteNonQueryAsync();
var selectCommand = connection.CreateCommand();
selectCommand.CommandText = "SELECT * FROM users WHERE UUID = @UUID";
selectCommand.Parameters.AddWithValue("@UUID", UUID);
var reader = await selectCommand.ExecuteReaderAsync();
await reader.ReadAsync();
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)
};
}
return user;
}
public static async Task InitializeAsync() public static async Task InitializeAsync()
{ {
if (!File.Exists("pastes.sqlite")) if (!File.Exists("pastes.sqlite"))
@@ -2161,7 +2414,7 @@ class Program
{ {
await connection.OpenAsync(); await connection.OpenAsync();
var command = connection.CreateCommand(); var command = connection.CreateCommand();
command.CommandText = "CREATE TABLE pastes (UID INTEGER,Title TEXT, Date TEXT, Size TEXT, Visibility TEXT, ID TEXT,Uploader TEXT, PRIMARY KEY(UID AUTOINCREMENT))"; command.CommandText = "CREATE TABLE pastes (UID INTEGER,Title TEXT, Date TEXT, Size TEXT, Visibility TEXT, ID TEXT,Uploader TEXT, PasswordHash TEXT, PRIMARY KEY(UID AUTOINCREMENT))";
await command.ExecuteNonQueryAsync(); await command.ExecuteNonQueryAsync();
var usersTableCommand = connection.CreateCommand(); var usersTableCommand = connection.CreateCommand();
@@ -2173,7 +2426,7 @@ class Program
await loginsTableCommand.ExecuteNonQueryAsync(); await loginsTableCommand.ExecuteNonQueryAsync();
var punishedUsersTableCommand = connection.CreateCommand(); var punishedUsersTableCommand = connection.CreateCommand();
punishedUsersTableCommand.CommandText = "CREATE TABLE punished_users (UUID TEXT,Username TEXT,State INTEGER,Reason TEXT,ExpirationDate TEXT"; punishedUsersTableCommand.CommandText = "CREATE TABLE punishedUsers (UUID TEXT,Username TEXT,State INTEGER,Reason TEXT,ExpirationDate TEXT";
await punishedUsersTableCommand.ExecuteNonQueryAsync(); await punishedUsersTableCommand.ExecuteNonQueryAsync();
} }
} }
@@ -2182,6 +2435,7 @@ 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); smallerSalt = config["SmallerSalt"]?.ToString() ?? BCrypt.Net.BCrypt.GenerateSalt(8);
File.WriteAllText("config.json", config.ToString());
Logging.Api_CreateMessage = config["API_CreateMessage"]?.ToString() ?? ""; Logging.Api_CreateMessage = config["API_CreateMessage"]?.ToString() ?? "";
} }
@@ -2222,6 +2476,10 @@ public class Paste
public string? Id { get; set; } public string? Id { get; set; }
public string? Uploader { get; set; } public string? Uploader { get; set; }
} }
public class PrivatePaste : Paste
{
public string? Password { get; set; }
}
public class User public class User
{ {
public string? UID { get; set; } public string? UID { get; set; }
@@ -2233,4 +2491,14 @@ public class User
public int Type { get; set; } public int Type { get; set; }
public int State { get; set; } public int State { get; set; }
} }
public class Punishment
{
public string? UUID { get; set; }
public int State { get; set; }
public string? Reason { get; set; }
public long? ExpirationDate { get; set; }
public string? Punisher { get; set; }
}
+27 -22
View File
@@ -17,6 +17,7 @@
<None Remove="assets\admin.html" /> <None Remove="assets\admin.html" />
<None Remove="assets\admin\user.html" /> <None Remove="assets\admin\user.html" />
<None Remove="assets\archives.html" /> <None Remove="assets\archives.html" />
<None Remove="assets\banned.html" />
<None Remove="assets\dash.html" /> <None Remove="assets\dash.html" />
<None Remove="assets\error.html" /> <None Remove="assets\error.html" />
<None Remove="assets\login.html" /> <None Remove="assets\login.html" />
@@ -27,22 +28,26 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Resource Include="assets\admin.html"> <Content Include="assets\admin.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Resource> </Content>
<Resource Include="assets\admin\user.html"> <Content Include="assets\admin\user.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Resource> </Content>
<Resource Include="assets\archives.html"> <Content Include="assets\archives.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Resource> </Content>
<Resource Include="assets\index.html"> <Content Include="assets\banned.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Resource> </Content>
<Content Include="assets\index.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="BCrypt.Net-Next" Version="4.0.3" /> <PackageReference Include="BCrypt.Net-Next" Version="4.0.3" />
<PackageReference Include="BouncyCastle.Cryptography" Version="2.4.0" />
<PackageReference Include="Microsoft.Data.Sqlite" Version="8.0.8" /> <PackageReference Include="Microsoft.Data.Sqlite" Version="8.0.8" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup> </ItemGroup>
@@ -52,27 +57,27 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Resource Include="assets\dash.html"> <Content Include="assets\dash.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Resource> </Content>
<Resource Include="assets\error.html"> <Content Include="assets\error.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Resource> </Content>
<Resource Include="assets\login.html"> <Content Include="assets\login.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Resource> </Content>
<Resource Include="assets\paste.html"> <Content Include="assets\paste.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Resource> </Content>
<Resource Include="assets\recent_pastes.html"> <Content Include="assets\recent_pastes.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Resource> </Content>
<Resource Include="assets\signup.html"> <Content Include="assets\signup.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Resource> </Content>
<Resource Include="assets\user.html"> <Content Include="assets\user.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Resource> </Content>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
+7
View File
@@ -5,5 +5,12 @@
"Microsoft.AspNetCore": "Warning" "Microsoft.AspNetCore": "Warning"
} }
}, },
"Kestrel": {
"EndPoints": {
"Http": {
"Url": "http://*:5240"
}
}
},
"AllowedHosts": "*" "AllowedHosts": "*"
} }
+4 -1
View File
@@ -49,6 +49,7 @@
</div> </div>
</div> </div>
</div> </div>
</body> </body>
<script> <script>
let searchTimeout; let searchTimeout;
@@ -220,7 +221,7 @@
overflow-x: hidden; overflow-x: hidden;
overflow-y: auto; overflow-y: auto;
background-color: #222222; background-color: #222222;
max-height: 70vh; max-height: 30vh;
} }
.accounts-wrapper { .accounts-wrapper {
@@ -267,6 +268,8 @@
.list-item { .list-item {
list-style: none; list-style: none;
max-width: 100%;
overflow-x: auto;
} }
.text-input { .text-input {
+155 -2
View File
@@ -31,7 +31,7 @@
<div class="action-wrapper"> <div class="action-wrapper">
<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="banorunban()" class="button">{typeban}</a>
<a onclick="changePassword()" class="button">change password</a> <a onclick="changePassword()" class="button">change password</a>
</div> </div>
</div> </div>
@@ -48,6 +48,12 @@
<div class="notification-div" id="notification"> <div class="notification-div" id="notification">
<h2 id="notification-text"></h2> <h2 id="notification-text"></h2>
</div> </div>
<div class="input-div" id="ban-div" style="display: none;">
<button onclick="banorunban()" class="exit-button">X</button>
<input type="date" id="ban-date" placeholder="{typeban} date">
<input type="text" id="ban-reason" placeholder="{typeban} reason">
<button id="ban-button" onclick="banAccount()">{typeban}</button>
</div>
</body> </body>
<script> <script>
function localizeDateTime(unixTimestamp) { function localizeDateTime(unixTimestamp) {
@@ -65,9 +71,46 @@
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));
if ('{typeban}' == 'unban') {
document.getElementById('ban-date').style.display = 'none';
}
}); });
function banorunban() {
const banDiv = document.getElementById('ban-div');
console.log(banDiv.style.display);
if (banDiv.style.display == 'none') {
banDiv.style.animation = 'hoverup 1s';
banDiv.style.display = 'flex';
} else {
banDiv.style.animation = 'hoverdown 1s';
setTimeout(() => {
banDiv.style.transition = '200ms';
banDiv.style.opacity = 0;
}, 600);
setTimeout(() => {
banDiv.style.display = 'none';
banDiv.style.opacity = 1;
}, 1000);
}
console.log(banDiv.style.display);
}
function banAccount() { function banAccount() {
let reason = prompt('Enter the reason for {typeban}ning the account'); let date = document.getElementById('ban-date').value;
date = new Date(date).getTime() / 1000;
let reason = document.getElementById('ban-reason').value;
if (date == null || reason == null) {
notification('Please fill out all fields');
return;
}
if (date < new Date().getTime() / 1000) {
notification('Please select a date in the future');
return;
}
if ('{typeban}' == 'unban') {
fetch('/api/accounts/admin/{typeban}', { fetch('/api/accounts/admin/{typeban}', {
method: 'POST', method: 'POST',
headers: { headers: {
@@ -87,7 +130,30 @@
notification(`Failed to {typeban} ${result.error}`); notification(`Failed to {typeban} ${result.error}`);
} }
}) })
} else {
fetch('/api/accounts/admin/{typeban}', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
uuid: '{uuid}',
expiration: `${date}`,
reason: `${reason}`
})
}).then(response => response.json())
.then(obj => {
const result = JSON.parse(obj);
if (result.message != null) {
notification(`${result.message} for ${reason}`);
} else {
notification(`Failed to {typeban} ${result.error}`);
}
})
}
console.log(date);
banorunban();
} }
function changePassword() { function changePassword() {
let password = prompt('Enter the new password'); let password = prompt('Enter the new password');
@@ -131,16 +197,103 @@
} }
</script> </script>
<style> <style>
.exit-button {
position: absolute;
right: 10px;
top: 10px;
background-color: #222222;
color: white;
border: #222222 2px solid;
border-radius: 5px;
padding: 5px;
padding-left: 10px;
padding-right: 10px;
cursor: pointer;
font-family: "Noto Sans Mono", "Consolas", "SF Mono", monospace;
font-weight: bold;
width: fit-content;
height: fit-content;
}
#ban-div {
display: none;
}
.input-div {
z-index: 2;
position: fixed;
background-color: #121212;
border-radius: 10px;
width: fit-content;
max-width: 50%;
display: none;
flex-direction: column;
align-items: center;
justify-content: center;
height: fit-content;
padding: 60px;
max-height: 50%;
border: #181818 3px solid;
}
input {
transition: 300ms;
width: 80%;
max-width: 80%;
padding: 10px;
margin: 10px;
border-radius: 5px;
border: #222222 2px solid;
background-color: #222222;
color: white;
font-family: "Noto Sans Mono", "Consolas", "SF Mono", monospace;
}
input:focus {
transition: 300ms;
outline: none;
border: #3a3a3a 2px solid;
}
#ban-button {
transition: 300ms;
width: 80%;
max-width: 80%;
padding: 10px;
margin: 10px;
border-radius: 5px;
border: #222222 2px solid;
background-color: #222222;
color: white;
font-family: "Noto Sans Mono", "Consolas", "SF Mono", monospace;
font-weight: bold;
cursor: pointer;
box-sizing: content-box;
}
#ban-button:hover {
transition: 300ms;
background-color: #333333;
border: #3a3a3a 2px solid;
}
@keyframes hoverup { @keyframes hoverup {
0% { 0% {
opacity: 0;
transform: translateY(100%); transform: translateY(100%);
} }
25% {
opacity: 1;
}
50% { 50% {
transform: translateY(-10px); transform: translateY(-10px);
} }
100% { 100% {
opacity: 1;
transform: translateY(0); transform: translateY(0);
} }
} }
+14 -10
View File
@@ -21,6 +21,7 @@
<input type="text" placeholder="search" class="text-input" oninput="search()"> <input type="text" placeholder="search" class="text-input" oninput="search()">
<div class="pastes-wrapper"> <div class="pastes-wrapper">
{pastes} {pastes}
<a title="" href="/yZXC7EmRpexG"><li>Untitled 46 2.1 hrs ago 488.28KB</li></a>
</div> </div>
<div class="buttons-wrapper"> <div class="buttons-wrapper">
<a class="arrow-button" href="/archive?page={backpagenum}">&lt;</a> <a class="arrow-button" href="/archive?page={backpagenum}">&lt;</a>
@@ -144,21 +145,14 @@
display: flex; display: flex;
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
width: 95%; width: 100%;
padding: 20px; padding: 20px;
overflow-x: hidden; overflow-x: hidden;
overflow-y: auto; overflow-y: auto;
max-height: 70vh; max-height: 70vh;
} }
.pastes-wrapper a {
text-decoration: none;
color: white;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
}
li { li {
transition: 300ms; transition: 300ms;
@@ -211,12 +205,22 @@
border: 2px solid #3a3a3a; border: 2px solid #3a3a3a;
} }
.pastes-wrapper a {
text-decoration: none;
color: white;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.text-input { .text-input {
transition: border 300ms; transition: border 300ms;
width: 90.62%; width: calc(100% - 44px);
height: 1.2rem; height: 1.2rem;
padding: 10px; padding: 10px;
margin: 10px; margin: 10px;
margin-left: 12px;
border-radius: 5px; border-radius: 5px;
border: #222222 2px solid; border: #222222 2px solid;
background-color: #222222; background-color: #222222;
+122
View File
@@ -0,0 +1,122 @@
<!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>Error {code}</title>
</head>
<body>
<div class="nav-div">
<a href="/">home</a>
<a href="/pastes">recent pastes</a>
<a href="/archive">archive</a>
{html}
</div>
<div class="container-wrapper">
<div class="error-container">
<h1>Error {code}</h1>
<h2>{message}</h2>
</div>
</div>
</body>
<script>
function localizeDateTime(unixTimestamp) {
const date = new Date(unixTimestamp * 1000);
return date.toLocaleString();
}
document.addEventListener("DOMContentLoaded", function () {
const dateElement = document.getElementById('unix-date');
const time = localizeDateTime(parseInt(dateElement.innerText.trim()));
dateElement.innerText = time;
});
</script>
<style>
body{
font-family: "Noto Sans Mono", "Consolas", "SF Mono", monospace;
font-weight: bold;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #0d0d0d;
}
.container-wrapper{
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 100%;
height: 98.7vh;
}
.error-container{
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 80%;
padding: 20px;
background-color: #181818;
color: white;
border-radius: 5px;
height: fit-content;
max-height: 80vh;
overflow-y: auto;
border: #222222 2px solid;
}
.button{
text-decoration: none;
transition: 300ms;
width: fit-content;
padding: 10px;
margin: 10px 0;
border-radius: 5px;
border: none;
background-color: #222222;
color: white;
border: #2a2a2a00 2px solid;
cursor: pointer;
font-size: 1.2em;
}
.button:hover{
transition: 300ms;
background-color: #333333;
border: 2px solid #3a3a3a;
}
.nav-div{
top: 0;
margin-top: 10px;
position: absolute;
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
width: fit-content;
background-color: #181818;
padding-left: 10px;
padding-right: 10px;
color: white;
border-radius: 5px;
height: fit-content;
overflow-y: auto;
border: #222222 2px solid;
}
.nav-div a{
text-decoration: none;
color: white;
padding: 10px;
margin: 10px;
border-radius: 5px;
background-color: #222222;
transition: 300ms;
border: #2a2a2a00 2px solid;
}
.nav-div a:hover{
transition: 300ms;
background-color: #333333;
border: #3a3a3a 2px solid;
}
</style>
</html>
+4 -2
View File
@@ -80,20 +80,21 @@ body{
border-radius: 5px; border-radius: 5px;
width: 80%; width: 80%;
max-height: 80vh; max-height: 80vh;
min-height: 20%; height: 50%;
height: fit-content;
border: #222222 2px solid; border: #222222 2px solid;
} }
.idek-wrapper{ .idek-wrapper{
display: flex; display: flex;
flex-direction: row; flex-direction: row;
width: 100%; width: 100%;
height: 100%;
} }
.account-info{ .account-info{
display: flex; display: flex;
flex-direction: column; flex-direction: column;
background-color: #222222; background-color: #222222;
width: 48%; width: 48%;
height: calc(100% - 40px);
padding: 20px; padding: 20px;
margin-right: 5px; margin-right: 5px;
border-radius: 5px; border-radius: 5px;
@@ -105,6 +106,7 @@ body{
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
width: 48%; width: 48%;
height: calc(100% - 40px);
margin-left: 5px; margin-left: 5px;
border-radius: 5px; border-radius: 5px;
padding: 20px; padding: 20px;
+112 -5
View File
@@ -23,41 +23,148 @@
<input type="text" id="pasteTitle" class="textinput" name="pasteTitle" maxlength="500"> <input type="text" id="pasteTitle" class="textinput" name="pasteTitle" maxlength="500">
<label for="pasteContent" class="label">Content</label> <label for="pasteContent" class="label">Content</label>
<textarea id="pasteContent" class="textarea" name="pasteContent" required maxlength="500000"></textarea> <textarea id="pasteContent" class="textarea" name="pasteContent" required maxlength="500000"></textarea>
<select for="pasteVisibility" id="pasteVisibility" class="textinput" name="pasteVisibility" required>
<option value="Public">Public</option>
<option value="Unlisted">Unlisted</option>
<option value="Private">Private</option>
</select>
<label for="pastePassword" class="label" id="pastePasswordLabel">Paste Password</label>
<input type="password" id="pastePassword" class="textinput" name="pastePassword" maxlength="500">
<button type="submit" class="button">Create</button> <button type="submit" class="button">Create</button>
</form> </form>
</div> </div>
</div> </div>
<div class="notification-div" id="notification">
<h2 id="notification-text"></h2>
</div>
</body> </body>
<script> <script>
document.addEventListener("DOMContentLoaded", function () {
document.getElementById("pasteVisibility").value = "Public";
});
document.getElementById("createForm").addEventListener("submit", function (event) { document.getElementById("createForm").addEventListener("submit", function (event) {
event.preventDefault(); event.preventDefault();
var textAreaContent = document.getElementById("pasteContent").value; var textAreaContent = document.getElementById("pasteContent").value;
var textTitleContent = document.getElementById("pasteTitle").value; var textTitleContent = document.getElementById("pasteTitle").value;
var textVisibilityContent = document.getElementById("pasteVisibility").value;
var requestUrl = "/api/pastes/create"; var requestUrl = "/api/pastes/create";
var fetchBody = {
title: textTitleContent,
content: textAreaContent,
visibility: textVisibilityContent
};
if (textVisibilityContent == "Private") {
fetchBody.password = document.getElementById("pastePassword").value;
}
fetch(requestUrl, { fetch(requestUrl, {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
body: JSON.stringify({ body: JSON.stringify(fetchBody)
title: textTitleContent,
content: textAreaContent
})
}) })
.then(response => response.json()) .then(response => response.json())
.then(obj => { .then(obj => {
const result = JSON.parse(obj); const result = JSON.parse(obj);
if (result.pasteId != null) { if (result.pasteId != null) {
window.location.href = `/${result.pasteId}`; window.location.href = `/${result.pasteId}`;
}else if (result.error != null) {
notification(result.error);
} }
}) })
}); });
document.getElementById("pasteVisibility").addEventListener("change", function (event) {
var visibility = document.getElementById("pasteVisibility").value;
if (visibility == "Private") {
document.getElementById("pastePassword").style.display = "block";
document.getElementById("pastePasswordLabel").style.display = "block";
} else {
document.getElementById("pastePassword").style.display = "none";
document.getElementById("pastePasswordLabel").style.display = "none";
}
});
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% {
opacity: 0;
transform: translateY(100%);
}
25% {
opacity: 1;
}
50% {
transform: translateY(-10px);
}
100% {
opacity: 1;
transform: translateY(0);
}
}
@keyframes hoverdown {
0% {
transform: translateY(0);
}
50% {
transform: translateY(-10px);
}
100% {
transform: translateY(200%);
}
}
#pastePassword{
display: none;
}
#pastePasswordLabel{
display: none;
}
.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;
}
body { body {
font-family: "Noto Sans Mono", "Consolas", "SF Mono", monospace; font-family: "Noto Sans Mono", "Consolas", "SF Mono", monospace;
+22 -1
View File
@@ -19,7 +19,7 @@
<h1 id="paste-title" title="{pastetitleattribute}">{pastetitle}</h1> <h1 id="paste-title" title="{pastetitleattribute}">{pastetitle}</h1>
<h3 class="uploader-text">{username} <a id="creationdate">{creationdate}</a> {pastesize}</h3> <h3 class="uploader-text">{username} <a id="creationdate">{creationdate}</a> {pastesize}</h3>
<div class="paste-wrapper"> <div class="paste-wrapper">
<p>{content}</p> <p id="text"></p>
</div> </div>
<div class="buttons-wrapper"> <div class="buttons-wrapper">
<a href="/raw/{pasteid}"> <a href="/raw/{pasteid}">
@@ -41,8 +41,29 @@
document.addEventListener("DOMContentLoaded", function() { document.addEventListener("DOMContentLoaded", function() {
const creationdateElement = document.getElementById('creationdate'); const creationdateElement = document.getElementById('creationdate');
const creationdateText = creationdateElement.innerText.trim(); const creationdateText = creationdateElement.innerText.trim();
const textElement = document.getElementById('text');
creationdateElement.innerText = localizeDateTime(parseInt(creationdateText)); creationdateElement.innerText = localizeDateTime(parseInt(creationdateText));
textElement.innerText = "Loading...";
fetch(`/raw/{pasteid}`)
.then(response => response.body)
.then(stream => {
const reader = stream.getReader();
let text = '';
const read = () => {
return reader.read().then(({ done, value }) => {
if (done) {
textElement.innerText = text;
return;
}
text += new TextDecoder().decode(value);
return read();
});
};
return read();
});
}); });
document.getElementById("copy-button").addEventListener("click", function () { document.getElementById("copy-button").addEventListener("click", function () {
+367
View File
@@ -0,0 +1,367 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{pastetitle}</title>
</head>
<body>
<div class="nav-div">
<a href="/">home</a>
<a href="/pastes">recent pastes</a>
<a href="/archive">archive</a>
{html}
</div>
<div class="container-wrapper">
<div class="paste-container">
<h1 id="paste-title" title="{pastetitleattribute}">{pastetitle}</h1>
<h3 class="uploader-text">{username} <a id="creationdate">{creationdate}</a> {pastesize}</h3>
<div class="paste-wrapper">
<p id="text"></p>
</div>
<div class="buttons-wrapper">
<a href="" id="view-raw-a">
<button id="view-raw-button" class="button">view raw</button>
</a>
<button id="copy-button" class="button">copy</button>
<button id="download-button" class="button">download</button>
{deletebutton}
</div>
</div>
<div class="passwordDiv">
<div class="inputDiv">
<h1>This paste is password protected</h1>
<input type="password" id="password" class="textinput" name="password" maxlength="500" placeholder="password">
<button id="submitPassword" class="button-input">Submit</button>
</div>
</div>
</div>
<div class="notification-div" id="notification">
<h2 id="notification-text"></h2>
</div>
</body>
<script>
document.getElementById("submitPassword").addEventListener("click", function () {
var password = document.getElementById("password").value;
fetch(`/api/pastes/password/{pasteid}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
password: password
})
})
.then(response => response.json())
.then(obj => {
const result = JSON.parse(obj);
if (result.content != null){
const textElement = document.getElementById('text');
textElement.innerText = result.content;
document.querySelector(".passwordDiv").style.display = "none";
const viewRawButton = document.getElementById('view-raw-a');
viewRawButton.href = `/raw/{pasteid}?password=${password}`;
}
else {
notification(`Error: ${result.error}`);
}
});
});
function localizeDateTime(unixTimestamp) {
const date = new Date(unixTimestamp * 1000);
return date.toLocaleString();
}
document.addEventListener("DOMContentLoaded", function() {
const creationdateElement = document.getElementById('creationdate');
const creationdateText = creationdateElement.innerText.trim();
creationdateElement.innerText = localizeDateTime(parseInt(creationdateText));
});
document.getElementById("copy-button").addEventListener("click", function () {
navigator.clipboard.writeText(document.querySelector(".paste-wrapper").innerText);
});
document.getElementById("download-button").addEventListener("click", function () {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(document.querySelector(".paste-wrapper").innerText));
element.setAttribute('download', '{pasteid}.txt');
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
});
{deletescript}
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>
</html>
<style>
@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+Mono:wght@100..900&display=swap');
body {
font-family: "Noto Sans Mono", "Consolas", "SF Mono", monospace;
font-weight: bold;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #0d0d0d;
}
.container-wrapper {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 100%;
height: 98.7vh;
}
.button-input {
transition: 300ms;
background-color: #222222;
color: white;
border: 2px solid #33333300;
border-radius: 5px;
padding: 5px;
margin: 5px;
cursor: pointer;
font-weight: 500;
font-size: 1.05rem;
width: 100%;
padding: 10px;
font-family: "Noto Sans Mono", "Consolas", "SF Mono", monospace;
font-weight: 625;
box-sizing: content-box;
}
.button-input:hover {
transition: 300ms;
background-color: #333333;
border: 2px solid #3a3a3a;
}
.passwordDiv {
z-index: 100;
position: absolute;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.4);
backdrop-filter: blur(8px);
color: white;
display: flex;
justify-content: center;
align-items: center;
}
.inputDiv {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: fit-content;
color: white;
}
.textinput {
width: 100%;
height: 50px;
border-radius: 5px;
border: 2px solid #222222;
background-color: #181818;
padding: 10px;
font-size: 1.05rem;
font-family: "Noto Sans Mono", "Consolas", "SF Mono", monospace;
font-weight: 625;
color: white;
}
.textinput:focus {
outline: none;
border: 2px solid #333333;
}
.paste-container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 80%;
padding: 20px;
background-color: #181818;
color: white;
border-radius: 5px;
height: fit-content;
max-height: 80vh;
min-height: 20%;
overflow-y: auto;
border: #222222 2px solid;
}
.paste-wrapper {
width: 95%;
height: fit-content;
padding-left: 10px;
padding-right: 10px;
background-color: #1d1d1d;
color: white;
border-radius: 5px;
margin-top: 10px;
text-wrap: wrap;
font-weight: 500;
max-height: 80%;
overflow-y: auto;
border: #222222 2px solid;
}
.buttons-wrapper {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
width: fit-content;
margin-top: 10px;
}
.buttons-wrapper a {
text-decoration: none;
}
.button {
transition: 300ms;
background-color: #222222;
color: white;
border: 2px solid #33333300;
border-radius: 5px;
padding: 5px;
margin: 5px;
cursor: pointer;
font-weight: 500;
font-size: 1.05rem;
padding: 10px;
font-family: "Noto Sans Mono", "Consolas", "SF Mono", monospace;
font-weight: 625;
}
.button:hover {
transition: 300ms;
background-color: #333333;
border: 2px solid #3a3a3a;
}
.uploader-text {
margin-top: -1.2rem;
font-weight: 600;
}
.user-a {
color: rgb(190, 190, 190);
text-decoration: none;
text-decoration: underline;
}
.nav-div {
top: 0;
margin-top: 10px;
position: absolute;
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
width: fit-content;
background-color: #181818;
padding-left: 10px;
padding-right: 10px;
color: white;
border-radius: 5px;
height: fit-content;
overflow-y: auto;
border: #222222 2px solid;
z-index: 102;
}
.nav-div a {
text-decoration: none;
color: white;
padding: 10px;
margin: 10px;
border-radius: 5px;
background-color: #222222;
transition: 300ms;
border: #2a2a2a00 2px solid;
}
.nav-div a:hover {
transition: 300ms;
background-color: #333333;
border: #3a3a3a 2px solid;
}
@keyframes hoverup {
0% {
opacity: 0;
transform: translateY(100%);
}
25% {
opacity: 1;
}
50% {
transform: translateY(-10px);
}
100% {
opacity: 1;
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;
z-index: 101;
}
</style>
+1
View File
@@ -0,0 +1 @@
5E9VIheekb5Vt/0qrAQFUg==