Compare commits

..
9 Commits
Author SHA1 Message Date
whoswhip 92f1ef1dbf Update install.sh 2024-10-19 00:14:23 -04:00
whoswhip 553b1a12db Update install.sh 2024-10-19 00:12:01 -04:00
whoswhip bdcc3a1dc6 Refactor for async operations and add new features
Updated Compression.cs to support asynchronous operations, including new methods for decompressing byte arrays and checking compression status.
Enhanced Logging.cs with asynchronous logging methods.
Refactored Program.cs to replace synchronous calls with asynchronous ones, added a new endpoint for editing pastes, and implemented rate limiting.
Removed outdated logging configuration.
2024-10-19 00:05:59 -04:00
whoswhip c28b9b92b1 merge 2024-10-18 20:45:31 -04:00
whoswhip 0d5fd3bc5d Extra checks and delete confirmation for pastes
## Copilot Generated Commit Details Below

Enhance auth and UI with notifications and delete confirmation

Enhanced authentication in Program.cs by adding checks for the
logged-in user and ensuring proper response handling. Improved
UI in paste.html and privatepaste.html by adding a confirmation
dialog for deletions and a notification system to inform users
of actions and errors. Added CSS styles to support these new
features with appropriate styling and animations.
2024-10-18 20:44:19 -04:00
whoswhip ab04010c30 Didnt mean to merge this! 2024-10-18 20:15:00 -04:00
whoswhip 49f8911be2 Merge files 2024-10-18 20:13:47 -04:00
whoswhip eb21e6d662 Pretty big update, this adds file compression on the server side to preserve space on the disk.
Switched the paste info displaying from server side to client side, which also added a new api to fetch the info.
A new api to check if the user is authorized, (/api/accounts/authenticated)

## Commit Message Details Below Generated by Copilot
Add compression, and install script

Added EncryptByteArray and DecryptByteArray methods to the Encryption class for handling byte array encryption and decryption.
Removed unused namespaces from Program.cs.
Replaced direct file content reading and HTML manipulation with database queries and JSON responses for better error handling and response consistency.
Added JSON error responses for various error conditions.
Implemented content compression and decompression using GZip in Compression.cs to reduce file size and improve performance.
Updated paste creation and retrieval logic to handle compressed and encrypted content.
Added new API endpoints for fetching paste information and checking user authentication status.
Modified HTML templates to dynamically fetch and display paste information and user authentication status using JavaScript.
Added Paste UID property to the Paste class to store unique identifiers for pastes.
Created a new Compression class to handle string compression and decompression using GZip.
Updated the InitializeAsync method to create the pastes.sqlite file if it does not exist.
Enhanced the user interface to show or hide elements based on user authentication status and paste ownership (client side).
Improved error handling and user feedback in the JavaScript code.
Added logic to handle compressed and encrypted content in various parts of the application.
Added a new Bash script (install.sh) to install Sharpbin on a Linux system, which includes fetching the latest release, extracting it, and configuring Cloudflare keys.
2024-10-18 20:12:48 -04:00
whoswhip 233b338f9b Fix Deletion Button Not Appearing
There was an extra space in the html for some reason around the area where its usually supposed to replace it with a variable server side. This commit fixes that issue.
2024-10-08 17:29:19 -04:00
8 changed files with 933 additions and 118 deletions
+62
View File
@@ -0,0 +1,62 @@
using System.IO.Compression;
using System.Text;
using System.Threading.Tasks;
namespace Sharpbin
{
public class Compression
{
public static async Task<byte[]> CompressString(string text)
{
byte[] compressedBytes;
using (var ms = new MemoryStream())
{
using (var cs = new GZipStream(ms, CompressionMode.Compress))
{
byte[] inputBytes = Encoding.UTF8.GetBytes(text);
await cs.WriteAsync(inputBytes, 0, inputBytes.Length);
}
compressedBytes = ms.ToArray();
}
return compressedBytes;
}
public static async Task<string> DecompressByteArrayToString(byte[] compressedBytes)
{
string decompressedText;
using (var ms = new MemoryStream(compressedBytes))
{
using (var cs = new GZipStream(ms, CompressionMode.Decompress))
{
using (var sr = new StreamReader(cs))
{
decompressedText = await sr.ReadToEndAsync();
}
}
}
return decompressedText;
}
public static async Task<byte[]> DecompressByteArray(byte[] compressedBytes)
{
byte[] decompressedBytes;
using (var ms = new MemoryStream(compressedBytes))
{
using (var cs = new GZipStream(ms, CompressionMode.Decompress))
{
using (var msDecompressed = new MemoryStream())
{
await cs.CopyToAsync(msDecompressed);
decompressedBytes = msDecompressed.ToArray();
}
}
}
return decompressedBytes;
}
public static bool IsCompressed(byte[] data)
{
return data.Length >= 2 && data[0] == 0x1F && data[1] == 0x8B;
}
}
}
+49
View File
@@ -31,6 +31,31 @@ namespace Sharpbin
return Convert.ToBase64String(encryptedBytes); return Convert.ToBase64String(encryptedBytes);
} }
public static string EncryptByteArray(byte[] bytes, 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))
{
cs.Write(bytes, 0, bytes.Length);
}
encryptedBytes = ms.ToArray();
}
}
return Convert.ToBase64String(encryptedBytes);
}
public static string DecryptString(string input, string password) public static string DecryptString(string input, string password)
{ {
@@ -59,5 +84,29 @@ namespace Sharpbin
return decryptedText; return decryptedText;
} }
public static byte[] DecryptByteArray(byte[] input, string password)
{
byte[] decryptedBytes;
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(input))
{
using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
{
decryptedBytes = new byte[ms.Length];
cs.Read(decryptedBytes, 0, decryptedBytes.Length);
}
}
}
return decryptedBytes;
}
} }
} }
+26 -2
View File
@@ -1,8 +1,9 @@
namespace Sharpbin using Org.BouncyCastle.Asn1.Cms;
namespace Sharpbin
{ {
public class Logging public class Logging
{ {
public static string Api_CreateMessage = "";
public static async Task<Log> LogRequestAsync(HttpContext context) public static async Task<Log> LogRequestAsync(HttpContext context)
{ {
Log log = new Log(); Log log = new Log();
@@ -14,6 +15,29 @@
log.IP = context.Request.Headers["X-Forwarded-For"].ToString() ?? context.Connection.RemoteIpAddress.ToString(); log.IP = context.Request.Headers["X-Forwarded-For"].ToString() ?? context.Connection.RemoteIpAddress.ToString();
return log; return log;
} }
public static async Task LogError(string message)
{
Console.BackgroundColor = ConsoleColor.Red;
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine($"[ERROR - {DateTime.Now}] {message}");
await File.AppendAllTextAsync("logs.log", $"[ERROR - {DateTime.Now}] {message}\n");
Console.ResetColor();
}
public static async Task LogInfo(string message)
{
Console.WriteLine($"[INFO - {DateTime.Now}] {message}");
await File.AppendAllTextAsync("logs.log", $"[INFO - {DateTime.Now}] {message}\n");
Console.ResetColor();
}
public static async Task LogWarning(string message)
{
Console.BackgroundColor = ConsoleColor.Yellow;
Console.ForegroundColor = ConsoleColor.Black;
Console.WriteLine($"[WARNING - {DateTime.Now}] {message}");
await File.AppendAllTextAsync("logs.log", $"[WARNING - {DateTime.Now}] {message}\n");
Console.ResetColor();
}
} }
public class Log public class Log
{ {
+281 -79
View File
@@ -5,8 +5,7 @@ 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;
using System.Reflection.Metadata;
class Program class Program
{ {
@@ -402,8 +401,6 @@ class Program
context.Response.Redirect("/paste-not-found"); context.Response.Redirect("/paste-not-found");
return; return;
} }
var content = File.ReadAllText($"pastes/{id}.txt");
content = content.Replace("\n", "<br>").Replace("\r", "");
using (var connection = new SqliteConnection("Data Source=pastes.sqlite")) using (var connection = new SqliteConnection("Data Source=pastes.sqlite"))
{ {
await connection.OpenAsync(); await connection.OpenAsync();
@@ -452,24 +449,6 @@ class Program
user.LastLoginDate = userReader.GetString(5); user.LastLoginDate = userReader.GetString(5);
user.Type = userReader.GetInt32(6); user.Type = userReader.GetInt32(6);
} }
if (paste.Uploader.Contains("Anonymous"))
{
user.Username = "Anonymous";
}
else
{
user.Username = $"<a class=\"user-a\" href=\"/u/{user.Username}\">{user.Username}</a>";
}
if (paste.Title == "" || string.IsNullOrEmpty(paste.Title))
{
paste.Title = $"Untitled {reader.GetString(0)}";
title = $"Untitled {reader.GetString(0)}";
}
if (paste.Title.Length > 40)
{
title = paste.Title.Substring(0, 40) + "...";
}
var html = File.ReadAllText("assets/paste.html"); var html = File.ReadAllText("assets/paste.html");
if (paste.Visibility == "Private") if (paste.Visibility == "Private")
@@ -477,33 +456,7 @@ class Program
html = File.ReadAllText("assets/privatepaste.html"); html = File.ReadAllText("assets/privatepaste.html");
html = html.Replace("{password}", ""); html = html.Replace("{password}", "");
} }
html = html.Replace("{pastetitleattribute}", paste.Title);
html = html.Replace("{pastetitle}", title);
html = html.Replace("{content}", content);
html = html.Replace("{pasteid}", paste.Id); html = html.Replace("{pasteid}", paste.Id);
html = html.Replace("{username}", user.Username);
html = html.Replace("{creationdate}", paste.UnixDate.ToString());
html = html.Replace("{pastesize}", ConvertToBytes(paste.Size));
if (paste.Uploader == loggedInUser.UUID || loggedInUser.Type == 255)
{
html = html.Replace("{deletebutton}", "<button id=\"delete-button\" class=\"button\">delete</button>");
html = html.Replace("{deletescript}", " document.getElementById(\"delete-button\").addEventListener(\"click\", function () {\r\n alert(\"Deletion cannot be undone. Are you sure you want to delete this paste?\");\r\n var requestUrl = \"/api/pastes/delete\";\r\n fetch(requestUrl, {\r\n method: \"POST\",\r\n headers: {\r\n \"Content-Type\": \"application/json\",\r\n },\r\n body: JSON.stringify({\r\n id: \"" + paste.Id + "\"\r\n })\r\n })\r\n .then(response => response.json())\r\n .then(obj => {\r\n const result = JSON.parse(obj);\r\n if (result.message != null) {\r\n window.location.href = `/`;\r\n }\r\n })\r\n });");
}
else
{
html = html.Replace("{deletebutton}", "");
html = html.Replace("{deletescript}", "");
}
bool loggedIn = await IsLoggedInAsync(context.Request.Cookies["token"]);
if (loggedIn)
{
html = html.Replace("{html}", "<a href=\"/dash\">dashboard</a>");
}
else
{
html = html.Replace("{html}", "<a href=\"/login\">login</a> <a href=\"/sign-up\">sign up</a>");
}
context.Response.ContentType = "text/html"; context.Response.ContentType = "text/html";
await context.Response.WriteAsync(html); await context.Response.WriteAsync(html);
@@ -518,6 +471,10 @@ class Program
if (!File.Exists(filePath)) if (!File.Exists(filePath))
{ {
context.Response.StatusCode = 404; context.Response.StatusCode = 404;
var json = new JObject
{
["error"] = "Paste not found"
};
return; return;
} }
if (id.Length == 24) if (id.Length == 24)
@@ -526,6 +483,10 @@ class Program
if (string.IsNullOrEmpty(password)) if (string.IsNullOrEmpty(password))
{ {
context.Response.StatusCode = 401; context.Response.StatusCode = 401;
var json = new JObject
{
["error"] = "Password required"
};
return; return;
} }
using (var connection = new SqliteConnection("Data Source=pastes.sqlite")) using (var connection = new SqliteConnection("Data Source=pastes.sqlite"))
@@ -539,6 +500,10 @@ class Program
if (!reader.HasRows) if (!reader.HasRows)
{ {
context.Response.StatusCode = 404; context.Response.StatusCode = 404;
var json = new JObject
{
["error"] = "Paste not found"
};
return; return;
} }
var paste = new PrivatePaste var paste = new PrivatePaste
@@ -555,11 +520,29 @@ class Program
if (hashedPassword != paste.Password && paste.Visibility != "Private") if (hashedPassword != paste.Password && paste.Visibility != "Private")
{ {
context.Response.StatusCode = 401; context.Response.StatusCode = 401;
var json = new JObject
{
["error"] = "Invalid password"
};
return;
}
try
{
string decompressedEncryptedContent = await Compression.DecompressByteArrayToString(await File.ReadAllBytesAsync(filePath));
string text = Encryption.DecryptString(decompressedEncryptedContent, password);
context.Response.ContentType = "text/plain";
await context.Response.WriteAsync(text);
}
catch (Exception e)
{
await Logging.LogError(e.Message);
context.Response.StatusCode = 401;
var json = new JObject
{
["error"] = "Invalid password or Failed to decompress text"
};
return; return;
} }
string text = Encryption.DecryptString(await File.ReadAllTextAsync(filePath), password);
context.Response.ContentType = "text/plain";
await context.Response.WriteAsync(text);
return; return;
} }
} }
@@ -569,10 +552,14 @@ class Program
context.Response.ContentType = "text/plain"; context.Response.ContentType = "text/plain";
context.Response.ContentLength = fileSize; context.Response.ContentLength = fileSize;
var _content = await File.ReadAllBytesAsync(filePath);
using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) if (Compression.IsCompressed(_content))
{ {
await fileStream.CopyToAsync(context.Response.Body); _content = await Compression.DecompressByteArray(_content);
}
using (var stream = new MemoryStream(_content))
{
await stream.CopyToAsync(context.Response.Body);
} }
}).RequireRateLimiting("fixed-bigger"); }).RequireRateLimiting("fixed-bigger");
@@ -1128,8 +1115,7 @@ class Program
punishedUsersCommand.Parameters.AddWithValue("@Punisher", loggedInUser.UUID); punishedUsersCommand.Parameters.AddWithValue("@Punisher", loggedInUser.UUID);
await punishedUsersCommand.ExecuteNonQueryAsync(); await punishedUsersCommand.ExecuteNonQueryAsync();
} }
Console.WriteLine($"[{DateTime.Now}] Account {user.Username}({user.UUID}) has been banned by {loggedInUser.Username}({loggedInUser.UUID}) for {reason}"); await Logging.LogInfo($"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 banned" }.ToString()); await context.Response.WriteAsJsonAsync(new JObject { ["message"] = "User banned" }.ToString());
@@ -1186,8 +1172,7 @@ class Program
return; return;
} }
var user = await UnbanUUIDAsync(uuid); var user = await UnbanUUIDAsync(uuid);
Console.WriteLine($"[{DateTime.Now}] Account {user.Username}({user.UUID}) has been unbanned by {loggedInUser.Username}({loggedInUser.UUID}) for {reason}"); await Logging.LogInfo($"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");
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());
@@ -1283,8 +1268,7 @@ class Program
deleteLoginsCommand.Parameters.AddWithValue("@UUID", uuid); deleteLoginsCommand.Parameters.AddWithValue("@UUID", uuid);
await deleteLoginsCommand.ExecuteNonQueryAsync(); await deleteLoginsCommand.ExecuteNonQueryAsync();
} }
Console.WriteLine($"[{DateTime.Now}] Account {user.Username}({user.UUID}) has had their password changed by {loggedInUser.Username}({loggedInUser.UUID})"); await Logging.LogInfo($"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.StatusCode = 200;
context.Response.ContentType = "application/json"; context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["message"] = "Password changed", ["password"] = newPassword }.ToString()); await context.Response.WriteAsJsonAsync(new JObject { ["message"] = "Password changed", ["password"] = newPassword }.ToString());
@@ -1483,7 +1467,7 @@ class Program
context.Response.ContentType = "application/json"; context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(usersJson.ToString()); await context.Response.WriteAsJsonAsync(usersJson.ToString());
} }
}); }).RequireRateLimiting("fixed-bigger"); ;
#endregion #endregion
@@ -1597,8 +1581,7 @@ class Program
_responseJson["pasteVisibility"] = privatePaste.Visibility; _responseJson["pasteVisibility"] = privatePaste.Visibility;
Log _log = await Logging.LogRequestAsync(context); Log _log = await Logging.LogRequestAsync(context);
Console.WriteLine($"[{_time}] Private Paste created, {ConvertToBytes(privatePaste.Size ?? string.Empty)}, {privatePaste.Id} by {uploaderUUID}"); await Logging.LogInfo($"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()); await context.Response.WriteAsJsonAsync(_responseJson.ToString());
return; return;
} }
@@ -1629,13 +1612,101 @@ class Program
Log log = await Logging.LogRequestAsync(context); Log log = await Logging.LogRequestAsync(context);
Console.WriteLine($"[{time}] Paste created, {ConvertToBytes(paste.Size ?? string.Empty)}, {paste.Id} by {uploaderUUID}"); await Logging.LogInfo($"Paste created, {ConvertToBytes(paste.Size ?? string.Empty)}, {paste.Id} by {uploaderUUID}");
await File.AppendAllTextAsync("logs.log", $"[{time}] {paste.Id} {log.IP} {log.Method} {log.Path} {log.UserAgent} {log.Referer} {log.Body} {uploaderUUID}\n");
await context.Response.WriteAsJsonAsync(responseJson.ToString()); await context.Response.WriteAsJsonAsync(responseJson.ToString());
return; return;
}).RequireRateLimiting("fixed"); }).RequireRateLimiting("fixed");
app.MapPost("/api/pastes/edit", async (HttpContext context) =>
{
var token = context.Request.Cookies["token"] ?? context.Request.Headers["Authorization"];
var user = await GetLoggedInUserAsync(token);
if (user.UUID == null || user.UID == null)
{
context.Response.StatusCode = 401;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Unauthorized" }.ToString());
return;
}
if (user.State != 0)
{
context.Response.StatusCode = 401;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "User is banned/suspended" }.ToString());
return;
}
string requestBody = await new StreamReader(context.Request.Body).ReadToEndAsync();
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;
}
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;
}
var data = JObject.Parse(requestBody);
var id = SanitizeInput(data["id"]?.ToString() ?? "");
var content = SanitizeInput(data["text"]?.ToString() ?? "");
if (string.IsNullOrEmpty(id) || string.IsNullOrWhiteSpace(id) || string.IsNullOrEmpty(content) || string.IsNullOrWhiteSpace(content))
{
context.Response.StatusCode = 400;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Invalid request body" }.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", id);
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 Paste
{
Title = reader.GetString(1),
UnixDate = long.Parse(reader.GetString(2)),
Size = reader.GetString(3),
Visibility = reader.GetString(4),
Id = reader.GetString(5),
};
if (paste.Visibility == "Private")
{
context.Response.StatusCode = 501;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Editing private pastes has not been implemented." }.ToString());
return;
}
var compressedContent = await Compression.CompressString(content);
await File.WriteAllBytesAsync($"pastes/{id}.txt", compressedContent);
await Logging.LogInfo($"{user.Username}({user.UUID}) edited their paste {paste.Id}");
}
context.Response.StatusCode = 200;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["message"] = "Paste edited" }.ToString());
});
app.MapPost("/api/pastes/delete", async (HttpContext context) => app.MapPost("/api/pastes/delete", async (HttpContext context) =>
{ {
string token = context.Request.Cookies["token"] ?? context.Request.Headers["Authorization"]; string token = context.Request.Cookies["token"] ?? context.Request.Headers["Authorization"];
@@ -1717,8 +1788,7 @@ class Program
deleteCommand.Parameters.AddWithValue("@ID", id); deleteCommand.Parameters.AddWithValue("@ID", id);
await deleteCommand.ExecuteNonQueryAsync(); await deleteCommand.ExecuteNonQueryAsync();
File.Delete($"pastes/{id}.txt"); File.Delete($"pastes/{id}.txt");
Console.WriteLine($"[{log.Now}] Paste {id} deleted by {user.Username}({user.UUID})"); await Logging.LogInfo($"Paste {id} deleted by {user.Username}({user.UUID})");
await File.AppendAllTextAsync("logs.log", $"[{log.Now}] PASTE DELETED {id} {log.IP} {log.Method} {log.Path} {log.UserAgent} {log.Referer} {log.Body} {user.UUID}\n");
context.Response.StatusCode = 200; context.Response.StatusCode = 200;
await context.Response.WriteAsJsonAsync(new JObject { ["message"] = "Paste deleted" }.ToString()); await context.Response.WriteAsJsonAsync(new JObject { ["message"] = "Paste deleted" }.ToString());
} }
@@ -1878,6 +1948,69 @@ class Program
} }
}).RequireRateLimiting("fixed"); }).RequireRateLimiting("fixed");
app.MapGet("/api/pastes/info", async (HttpContext context) =>
{
var query = context.Request.Query;
var id = query["id"].ToString();
if (string.IsNullOrEmpty(id) || string.IsNullOrWhiteSpace(id))
{
context.Response.StatusCode = 400;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Invalid request" }.ToString());
return;
}
if (!File.Exists($"pastes/{id}.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", id);
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 Paste
{
Title = reader.GetString(1),
UnixDate = long.Parse(reader.GetString(2)),
Size = reader.GetString(3),
Visibility = reader.GetString(4),
Id = reader.GetString(5),
UID = long.Parse(reader.GetString(0)),
Uploader = reader.GetString(6)
};
var filelength = new FileInfo($"pastes/{id}.txt").Length;
var user = await GetUserFromUUID(paste.Uploader);
JObject responseJson = new JObject();
responseJson["title"] = paste.Title;
responseJson["id"] = paste.Id;
responseJson["uid"] = paste.UID;
responseJson["size"] = ConvertToBytes(paste.Size);
responseJson["compressedSize"] = ConvertToBytes(filelength.ToString());
responseJson["date"] = paste.UnixDate;
responseJson["visibility"] = paste.Visibility;
responseJson["uploader"] = user.Username;
context.Response.StatusCode = 200;
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(responseJson.ToString());
}
}).RequireRateLimiting("fixed");
app.MapPost("/api/pastes/password/{pasteid}", async (HttpContext context) => app.MapPost("/api/pastes/password/{pasteid}", async (HttpContext context) =>
{ {
var body = await new StreamReader(context.Request.Body).ReadToEndAsync(); var body = await new StreamReader(context.Request.Body).ReadToEndAsync();
@@ -1948,13 +2081,14 @@ class Program
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Invalid password" }.ToString()); await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Invalid password" }.ToString());
return; return;
} }
} }
string decryptedText = Encryption.DecryptString(File.ReadAllText($"pastes/{pasteId}.txt"), password); string decompressedEncryptedText = await Compression.DecompressByteArrayToString(File.ReadAllBytes($"pastes/{pasteId}.txt"));
string decryptedText = Encryption.DecryptString(decompressedEncryptedText, password);
context.Response.StatusCode = 200; context.Response.StatusCode = 200;
context.Response.ContentType = "application/json"; context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["content"] = decryptedText }.ToString()); await context.Response.WriteAsJsonAsync(new JObject { ["content"] = decryptedText }.ToString());
}); }).RequireRateLimiting("fixed");
app.MapPost("/api/accounts/create", async (HttpContext context) => app.MapPost("/api/accounts/create", async (HttpContext context) =>
{ {
@@ -2091,8 +2225,7 @@ class Program
context.Response.Cookies.Append("token", token, cookie); context.Response.Cookies.Append("token", token, cookie);
context.Response.StatusCode = 200; context.Response.StatusCode = 200;
context.Response.ContentType = "application/json"; context.Response.ContentType = "application/json";
Console.WriteLine($"[{DateTime.Now}] Account {username} has been created"); await Logging.LogInfo($"Account {username} has been created");
File.AppendAllText("logs.log", $"[{DateTime.Now}] Account {username} has been created by {log.IP}\n");
await context.Response.WriteAsJsonAsync(new JObject { ["message"] = "Account created" }.ToString()); await context.Response.WriteAsJsonAsync(new JObject { ["message"] = "Account created" }.ToString());
@@ -2212,8 +2345,7 @@ class Program
context.Response.Cookies.Append("token", token, cookie); context.Response.Cookies.Append("token", token, cookie);
context.Response.StatusCode = 200; context.Response.StatusCode = 200;
context.Response.ContentType = "application/json"; context.Response.ContentType = "application/json";
Console.WriteLine($"[{DateTime.Now}] Account {username} has logged in"); await Logging.LogInfo($"Account {username} has logged in");
File.AppendAllText("logs.log", $"[{DateTime.Now}] Account {username} has logged in from {log.IP}\n");
await context.Response.WriteAsJsonAsync(new JObject { ["message"] = "Logged in" }.ToString()); await context.Response.WriteAsJsonAsync(new JObject { ["message"] = "Logged in" }.ToString());
return; return;
} }
@@ -2225,6 +2357,47 @@ class Program
} }
} }
})).RequireRateLimiting("fixed"); })).RequireRateLimiting("fixed");
app.MapGet("/api/accounts/authenticated", (async (HttpContext context) =>
{
var token = context.Request.Cookies["token"] ?? context.Request.Headers["Authorization"];
if (string.IsNullOrEmpty(token) || string.IsNullOrWhiteSpace(token))
{
context.Response.StatusCode = 401;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Unauthorized" }.ToString());
return;
}
var user = await GetLoggedInUserAsync(token);
if (user == null)
{
context.Response.StatusCode = 401;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Unauthorized" }.ToString());
return;
}
if (user.UUID == null)
{
context.Response.StatusCode = 401;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Unauthorized" }.ToString());
return;
}
var responseJson = new JObject();
responseJson["message"] = "Authenticated";
responseJson["username"] = user.Username;
responseJson["uid"] = user.UID;
responseJson["uuid"] = user.UUID;
responseJson["type"] = accountType[user.Type];
responseJson["state"] = accountState[user.State];
responseJson["creationDate"] = DateTimeOffset.FromUnixTimeSeconds(long.Parse(user.CreationDate)).ToString().Split("+")[0].TrimEnd();
responseJson["lastLoginDate"] = DateTimeOffset.FromUnixTimeSeconds(long.Parse(user.LastLoginDate)).ToString().Split("+")[0].TrimEnd();
context.Response.StatusCode = 200;
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(responseJson.ToString());
})).RequireRateLimiting("fixed"); ;
#endregion #endregion
@@ -2243,7 +2416,8 @@ class Program
Id = GenerateRandomString(12), Id = GenerateRandomString(12),
Uploader = UUID Uploader = UUID
}; };
await File.WriteAllTextAsync($"pastes/{paste.Id}.txt", paste.Content); var compressedText = await Compression.CompressString(paste.Content);
await File.WriteAllBytesAsync($"pastes/{paste.Id}.txt", compressedText);
using (var connection = new SqliteConnection("Data Source=pastes.sqlite")) using (var connection = new SqliteConnection("Data Source=pastes.sqlite"))
{ {
await connection.OpenAsync(); await connection.OpenAsync();
@@ -2261,7 +2435,8 @@ class Program
} }
public static async Task<PrivatePaste> CreatePrivatePaste(string title, string content, string password, string UUID) public static async Task<PrivatePaste> CreatePrivatePaste(string title, string content, string password, string UUID)
{ {
string encryptedText = Encryption.EncryptString($"{content}", password); string encryptedText = Encryption.EncryptString(content, password);
var compressedEncryptedText = await Compression.CompressString(encryptedText);
string passwordHash = BCrypt.Net.BCrypt.HashPassword(password, salt); string passwordHash = BCrypt.Net.BCrypt.HashPassword(password, salt);
var paste = new PrivatePaste var paste = new PrivatePaste
{ {
@@ -2273,7 +2448,7 @@ class Program
Password = passwordHash Password = passwordHash
}; };
await File.WriteAllTextAsync($"pastes/{paste.Id}.txt", encryptedText); await File.WriteAllBytesAsync($"pastes/{paste.Id}.txt", compressedEncryptedText);
using (var connection = new SqliteConnection("Data Source=pastes.sqlite")) using (var connection = new SqliteConnection("Data Source=pastes.sqlite"))
{ {
await connection.OpenAsync(); await connection.OpenAsync();
@@ -2427,6 +2602,33 @@ class Program
}; };
} }
} }
public static async Task<User> GetUserFromUUID(string UUID)
{
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)
{
return new User();
}
return 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)
};
}
}
public static async Task<User> UnbanUUIDAsync(string UUID) public static async Task<User> UnbanUUIDAsync(string UUID)
{ {
User user = new User(); User user = new User();
@@ -2464,6 +2666,7 @@ class Program
{ {
if (!File.Exists("pastes.sqlite")) if (!File.Exists("pastes.sqlite"))
{ {
File.Create("pastes.sqlite").Close();
using (var connection = new SqliteConnection("Data Source=pastes.sqlite")) using (var connection = new SqliteConnection("Data Source=pastes.sqlite"))
{ {
await connection.OpenAsync(); await connection.OpenAsync();
@@ -2495,8 +2698,6 @@ class Program
config["Salt"] = salt; config["Salt"] = salt;
config["SmallerSalt"] = smallerSalt; config["SmallerSalt"] = smallerSalt;
File.WriteAllText("config.json", config.ToString()); File.WriteAllText("config.json", config.ToString());
Logging.Api_CreateMessage = config["API_CreateMessage"]?.ToString() ?? "";
} }
else else
{ {
@@ -2542,6 +2743,7 @@ public class Paste
public long? UnixDate { get; set; } public long? UnixDate { get; set; }
public string? Visibility { get; set; } public string? Visibility { get; set; }
public string? Id { get; set; } public string? Id { get; set; }
public long? UID { get; set; }
public string? Uploader { get; set; } public string? Uploader { get; set; }
} }
public class PrivatePaste : Paste public class PrivatePaste : Paste
+2 -2
View File
@@ -49,7 +49,7 @@
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content> </Content>
<Content Include="pastes.sqlite"> <Content Include="pastes.sqlite">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content> </Content>
</ItemGroup> </ItemGroup>
@@ -90,7 +90,7 @@
<ItemGroup> <ItemGroup>
<Content Update="config.json"> <Content Update="config.json">
<CopyToOutputDirectory>Never</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content> </Content>
</ItemGroup> </ItemGroup>
+279 -9
View File
@@ -4,7 +4,6 @@
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{pastetitle}</title>
</head> </head>
<body> <body>
@@ -12,7 +11,9 @@
<a href="/">home</a> <a href="/">home</a>
<a href="/pastes">recent pastes</a> <a href="/pastes">recent pastes</a>
<a href="/archive">archive</a> <a href="/archive">archive</a>
{html} <a href="login" id="login-signup-btn" style="display: none;" >login</a>
<a href="sign-up" id="login-signup-btn" style="display: none;">sign up</a>
<a href="dash" id="dash-btn" style="display: none;">dashboard</a>
</div> </div>
<div class="nav-hamburger-menu"> <div class="nav-hamburger-menu">
<svg xmlns="http://www.w3.org/2000/svg" width="56" height="56" fill="currentColor" class="bi bi-list" <svg xmlns="http://www.w3.org/2000/svg" width="56" height="56" fill="currentColor" class="bi bi-list"
@@ -24,13 +25,16 @@
<a href="/">home</a> <a href="/">home</a>
<a href="/pastes">recent pastes</a> <a href="/pastes">recent pastes</a>
<a href="/archive">archive</a> <a href="/archive">archive</a>
{html} <a href="login" id="login-signup-btn" style="display: none;" >login</a>
<a href="sign-up" id="login-signup-btn" style="display: none;">sign up</a>
<a href="dash" id="dash-btn" style="display: none;">dashboard</a>
</div> </div>
</div> </div>
<div class="container-wrapper"> <div class="container-wrapper">
<div class="paste-container"> <div class="paste-container">
<h1 id="paste-title" title="{pastetitleattribute}">{pastetitle}</h1> <h1 id="paste-title"></h1>
<h3 class="uploader-text">{username} <a id="creationdate">{creationdate}</a> {pastesize}</h3> <h3 class="uploader-text"><a id="uploader-username" class="user-a"></a> <a id="creationdate"></a> <a id="paste-size"></a>
</h3>
<div class="paste-wrapper"> <div class="paste-wrapper">
<p id="text"></p> <p id="text"></p>
</div> </div>
@@ -40,22 +44,92 @@
</a> </a>
<button id="copy-button" class="button">copy</button> <button id="copy-button" class="button">copy</button>
<button id="download-button" class="button">download</button> <button id="download-button" class="button">download</button>
{deletebutton} <button id="delete-button" class="button" style="display: none;">delete</button>
<button id="edit-button" class="button" style="display: none;">edit</button>
</div>
</div>
</div>
<div class="notifcations-wrapper" id="notifications"></div>
<div class="input-wrapper" id="input-wrapper">
<div class="input-wrapper-container">
<h2 id="input-message"></h2>
<div>
<button id="yes-button" class="button">Yes</button>
<button id="no-button" class="button">No</button>
</div> </div>
</div> </div>
</div> </div>
</body> </body>
<script> <script>
info = "";
editing = false;
function localizeDateTime(unixTimestamp) { function localizeDateTime(unixTimestamp) {
const date = new Date(unixTimestamp * 1000); const date = new Date(unixTimestamp * 1000);
return date.toLocaleString(); return date.toLocaleString();
} }
function authenticated() {
fetch('/api/accounts/authenticated')
.then(response => response.json())
.then(data => {
if (data.message == "Authenticated") {
if (info.uploader == data.username || data.type == "Admin") {
document.getElementById('delete-button').style.display = 'block';
document.getElementById('edit-button').style.display = 'block';
}
document.querySelectorAll("#login-signup-btn").forEach(element => {
element.style.display = 'none';
});
document.getElementById('dash-btn').style.display = 'block';
}else{
document.querySelectorAll("#login-signup-btn").forEach(element => {
element.style.display = 'block';
});
}
});
}
function fetchInfo() {
fetch('/api/pastes/info?id={pasteid}')
.then(response => response.json())
.then(json => {
info = json;
document.getElementById('uploader-username').innerText = json.uploader || 'Anonymous';
document.getElementById('creationdate').innerText = localizeDateTime(json.date);
document.getElementById('paste-size').innerText = json.size;
document.getElementById('paste-size').title = `Compressed Size: ${json.compressedSize}`;
document.getElementById('paste-title').innerText = json.title;
document.getElementById('paste-title').title = json.title;
if (json.title == "") {
document.getElementById('paste-title').innerText = `Untitled ${json.uid}`;
document.title = `Untitled ${json.uid}`;
}
if (json.uploader && json.uploader.startsWith("Anonymous") && json.uploader.length == 46) {
document.getElementById('uploader-username').innerText = 'Anonymous';
} else if (json.uploader) {
document.getElementById('uploader-username').href = `/u/${json.uploader}`;
}
})
.catch(error => console.error('Error fetching paste info:', error));
}
document.getElementById("edit-button").addEventListener("click", function () {
if (editing) {
createInput('Are you sure you want to save this edit?');
document.getElementById('yes-button').addEventListener("click", finalizeEdit);
} else {
editing = true;
var editButton = document.getElementById('edit-button');
editButton.innerText = 'save';
var text = document.getElementById('text');
var innertext = text.innerText;
text.innerHTML = `<textarea class="textarea" id="edit-textarea" style="width: 100%; height: ${text.clientHeight}px;">${innertext}</textarea>`;
}
});
document.addEventListener("DOMContentLoaded", function () { document.addEventListener("DOMContentLoaded", function () {
fetchInfo();
authenticated();
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'); const textElement = document.getElementById('text');
creationdateElement.innerText = localizeDateTime(parseInt(creationdateText)); creationdateElement.innerText = localizeDateTime(parseInt(creationdateText));
textElement.innerText = "Loading..."; textElement.innerText = "Loading...";
fetch(`/raw/{pasteid}`) fetch(`/raw/{pasteid}`)
@@ -109,8 +183,106 @@
element.click(); element.click();
document.body.removeChild(element); document.body.removeChild(element);
}); });
{ deletescript } document.getElementById("delete-button").addEventListener("click", function () {
createInput('Are you sure you want to delete this paste?');
document.getElementById("yes-button").addEventListener("click", function () {
fetch(`/api/pastes/delete?id={pasteid}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
id: '{pasteid}'
})
})
.then(response => response.json())
.then(obj => {
const result = JSON.parse(obj);
if (result.message != null) {
createNotification(`Success: ${result.message}`);
setTimeout(() => {
const inputWrapper = document.getElementById('input-wrapper');
inputWrapper.style.display = 'none';
window.location.href = '/';
}, 2000);
} else {
const inputWrapper = document.getElementById('input-wrapper');
inputWrapper.style.display = 'none';
createNotification(`Error: ${result.error}`);
}
});
});
});
document.getElementById("no-button").addEventListener("click", function () {
const inputWrapper = document.getElementById('input-wrapper');
inputWrapper.style.display = 'none';
});
function createNotification(message) {
const notificationWrapper = document.getElementById('notifications');
const notificationDiv = document.createElement('div');
notificationDiv.classList.add('notification-div');
notificationDiv.id = 'notification';
const notificationText = document.createElement('h2');
notificationText.id = 'notification-text';
notificationText.innerText = message;
notificationDiv.appendChild(notificationText);
notificationWrapper.appendChild(notificationDiv);
notificationDiv.style.animation = 'none';
notificationDiv.style.display = 'none';
notificationDiv.style.display = 'flex';
notificationDiv.style.animation = 'hoverup 1s';
setTimeout(() => {
notificationDiv.style.animation = 'hoverdown 1s';
}, 4000);
setTimeout(() => {
notificationDiv.remove();
}, 4900);
}
function createInput(message) {
const inputWrapper = document.getElementById('input-wrapper');
const inputMessage = document.getElementById('input-message');
inputMessage.innerText = message;
inputWrapper.style.display = 'flex';
}
function finalizeEdit() {
var textarea = document.getElementById('edit-textarea');
var text = textarea.value;
fetch(`/api/pastes/edit`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
id: '{pasteid}',
text: text
})
})
.then(response => response.json())
.then(obj => {
const result = JSON.parse(obj);
if (result.message != null) {
const inputWrapper = document.getElementById('input-wrapper');
inputWrapper.style.display = 'none';
document.getElementById('edit-button').innerText = "edit";
createNotification(`Success: ${result.message}`);
document.getElementById('text').innerText = text;
document.getElementById('edit-textarea').remove();
editing = false;
} else {
const inputWrapper = document.getElementById('input-wrapper');
inputWrapper.style.display = 'none';
document.getElementById('edit-button').innerText = "edit";
createNotification(`Error: ${result.error}`);
}
});
}
</script> </script>
@@ -118,6 +290,43 @@
<style> <style>
@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+Mono:wght@100..900&display=swap'); @import url('https://fonts.googleapis.com/css2?family=Noto+Sans+Mono:wght@100..900&display=swap');
.textarea{
font-family: "Noto Sans Mono", "Consolas", "SF Mono", monospace;
font-weight: 500;
max-width: 100%;
min-width: 100%;
background-color: #1d1d1d;
color: white;
border: none;
}
.textarea:focus{
outline: none;
}
.input-wrapper{
z-index: 100;
display: none;
position: absolute;
flex-direction: column;
justify-content: center;
align-items: center;
width: 100%;
height: 100%;
color: white;
backdrop-filter: blur(2.5px);
}
.input-wrapper-container{
z-index: 101;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 50%;
border-radius: 5px;
padding: 20px;
background-color: #181818;
}
body { body {
font-family: "Noto Sans Mono", "Consolas", "SF Mono", monospace; font-family: "Noto Sans Mono", "Consolas", "SF Mono", monospace;
font-weight: bold; font-weight: bold;
@@ -210,12 +419,13 @@
font-weight: 600; font-weight: 600;
} }
.user-a { .user-a:any-link {
color: rgb(190, 190, 190); color: rgb(190, 190, 190);
text-decoration: none; text-decoration: none;
text-decoration: underline; text-decoration: underline;
} }
.nav-div { .nav-div {
top: 0; top: 0;
margin-top: 10px; margin-top: 10px;
@@ -233,6 +443,7 @@
height: fit-content; height: fit-content;
overflow-y: auto; overflow-y: auto;
border: #222222 2px solid; border: #222222 2px solid;
z-index: 999999;
} }
.nav-hamburger-menu { .nav-hamburger-menu {
@@ -314,4 +525,63 @@
} }
} }
@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 {
display: flex;
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: 102;
position: absolute;
}
.notifcations-wrapper{
z-index: 101;
}
</style> </style>
+209 -24
View File
@@ -12,10 +12,13 @@
<a href="/">home</a> <a href="/">home</a>
<a href="/pastes">recent pastes</a> <a href="/pastes">recent pastes</a>
<a href="/archive">archive</a> <a href="/archive">archive</a>
{html} <a href="login" id="login-signup-btn" style="display: none;" >login</a>
<a href="sign-up" id="login-signup-btn" style="display: none;">sign up</a>
<a href="dash" id="dash-btn" style="display: none;">dashboard</a>
</div> </div>
<div class="nav-hamburger-menu"> <div class="nav-hamburger-menu">
<svg xmlns="http://www.w3.org/2000/svg" width="56" height="56" fill="currentColor" class="bi bi-list" viewBox="0 0 16 16" id="hamburger-button" style="cursor: pointer;"> <svg xmlns="http://www.w3.org/2000/svg" width="56" height="56" fill="currentColor" class="bi bi-list"
viewBox="0 0 16 16" id="hamburger-button" style="cursor: pointer;">
<path fill-rule="evenodd" <path fill-rule="evenodd"
d="M2.5 12a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5m0-4a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5m0-4a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5" /> d="M2.5 12a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5m0-4a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5m0-4a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5" />
</svg> </svg>
@@ -23,13 +26,16 @@
<a href="/">home</a> <a href="/">home</a>
<a href="/pastes">recent pastes</a> <a href="/pastes">recent pastes</a>
<a href="/archive">archive</a> <a href="/archive">archive</a>
{html} <a href="login" id="login-signup-btn" style="display: none;" >login</a>
<a href="sign-up" id="login-signup-btn" style="display: none;">sign up</a>
<a href="dash" id="dash-btn" style="display: none;">dashboard</a>
</div> </div>
</div> </div>
<div class="container-wrapper"> <div class="container-wrapper">
<div class="paste-container"> <div class="paste-container">
<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"><a id="uploader-username" class="user-a"></a> <a id="creationdate"></a> <a id="paste-size"></a>
</h3>
<div class="paste-wrapper"> <div class="paste-wrapper">
<p id="text"></p> <p id="text"></p>
</div> </div>
@@ -39,13 +45,15 @@
</a> </a>
<button id="copy-button" class="button">copy</button> <button id="copy-button" class="button">copy</button>
<button id="download-button" class="button">download</button> <button id="download-button" class="button">download</button>
{deletebutton} <button id="delete-button" class="button" style="display: none;">delete</button>
<button id="edit-button" class="button" style="display: none;">edit</button>
</div> </div>
</div> </div>
<div class="passwordDiv"> <div class="passwordDiv">
<div class="inputDiv"> <div class="inputDiv">
<h1>This paste is password protected</h1> <h1>This paste is password protected</h1>
<input type="password" id="password" class="textinput" name="password" maxlength="500" placeholder="password"> <input type="password" id="password" class="textinput" name="password" maxlength="500"
placeholder="password">
<button id="submitPassword" class="button-input">Submit</button> <button id="submitPassword" class="button-input">Submit</button>
</div> </div>
</div> </div>
@@ -53,8 +61,77 @@
<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-wrapper" id="input-wrapper">
<div class="input-wrapper-container">
<h2 id="input-message"></h2>
<div>
<button id="yes-button" class="button">Yes</button>
<button id="no-button" class="button">No</button>
</div>
</div>
</div>
</body> </body>
<script> <script>
info = "";
editing = false;
function authenticated() {
fetch('/api/accounts/authenticated')
.then(response => response.json())
.then(data => {
if (data.message == "Authenticated") {
if (info.uploader == data.username || data.type == "Admin") {
document.getElementById('delete-button').style.display = 'block';
//document.getElementById('edit-button').style.display = 'block';
}
document.querySelectorAll("#login-signup-btn").forEach(element => {
element.style.display = 'none';
});
document.getElementById('dash-btn').style.display = 'block';
}else{
document.querySelectorAll("#login-signup-btn").forEach(element => {
element.style.display = 'block';
});
}
});
}
function fetchInfo() {
fetch('/api/pastes/info?id={pasteid}')
.then(response => response.json())
.then(data => {
const json = JSON.parse(data);
info = json;
document.getElementById('uploader-username').innerText = json.uploader;
document.getElementById('creationdate').innerText = localizeDateTime(json.date);
document.getElementById('paste-size').innerText = json.size;
document.getElementById('paste-size').title = `Compressed Size: ${json.compressedSize}`;
document.getElementById('paste-title').innerText = json.title;
document.getElementById('paste-title').title = json.title;
if (json.title == "") {
document.getElementById('paste-title').innerText = `Untitled ${json.uid}`;
document.title = `Untitled ${json.uid}`;
}
if (json.uploader.startsWith("Anonymous") && json.uploader.length == 46) {
document.getElementById('uploader-username').innerText = 'Anonymous';
} else {
document.getElementById('uploader-username').href = `/u/${json.uploader}`;
}
});
}
document.getElementById("edit-button").addEventListener("click", function () {
if (editing) {
createInput('Are you sure you want to save this edit?');
document.getElementById('yes-button').removeEventListener("click", deletePaste);
document.getElementById('yes-button').addEventListener("click", finalizeEdit);
document.getElementById('yes-button').removeEventListener("click", finalizeEdit);
} else {
editing = true;
var editButton = document.getElementById('edit-button');
editButton.innerText = 'save';
var text = document.getElementById('text');
var innertext = text.innerText;
text.innerHTML = `<textarea class="textarea" id="edit-textarea" style="width: 100%; height: ${text.clientHeight}px;">${innertext}</textarea>`;
}
});
document.getElementById("submitPassword").addEventListener("click", function () { document.getElementById("submitPassword").addEventListener("click", function () {
var password = document.getElementById("password").value; var password = document.getElementById("password").value;
fetch(`/api/pastes/password/{pasteid}`, { fetch(`/api/pastes/password/{pasteid}`, {
@@ -66,30 +143,32 @@
password: password password: password
}) })
}) })
.then(response => response.json()) .then(response => response.json())
.then(obj => { .then(obj => {
const result = JSON.parse(obj); const result = JSON.parse(obj);
if (result.content != null){ if (result.content != null) {
const textElement = document.getElementById('text'); const textElement = document.getElementById('text');
textElement.innerText = result.content; textElement.innerText = result.content;
document.querySelector(".passwordDiv").style.display = "none"; document.querySelector(".passwordDiv").style.display = "none";
const viewRawButton = document.getElementById('view-raw-a'); const viewRawButton = document.getElementById('view-raw-a');
viewRawButton.href = `/raw/{pasteid}?password=${password}`; viewRawButton.href = `/raw/{pasteid}?password=` + password;
} }
else { else {
notification(`Error: ${result.error}`); notification(`Error: ${result.error}`);
} }
}); });
}); });
function localizeDateTime(unixTimestamp) { function localizeDateTime(unixTimestamp) {
const date = new Date(unixTimestamp * 1000); const date = new Date(unixTimestamp * 1000);
return date.toLocaleString(); return date.toLocaleString();
} }
document.addEventListener("DOMContentLoaded", function() { document.addEventListener("DOMContentLoaded", function () {
fetchInfo();
authenticated();
const creationdateElement = document.getElementById('creationdate'); const creationdateElement = document.getElementById('creationdate');
const creationdateText = creationdateElement.innerText.trim(); const creationdateText = creationdateElement.innerText.trim();
creationdateElement.innerText = localizeDateTime(parseInt(creationdateText)); creationdateElement.innerText = localizeDateTime(parseInt(creationdateText));
var mobile = window.mobileCheck(); var mobile = window.mobileCheck();
if (mobile) { if (mobile) {
@@ -122,7 +201,68 @@
element.click(); element.click();
document.body.removeChild(element); document.body.removeChild(element);
}); });
{deletescript} document.getElementById("delete-button").addEventListener("click", function () {
createInput('Are you sure you want to delete this paste?');
document.getElementById('yes-button').removeEventListener("click", finalizeEdit);
document.getElementById('yes-button').addEventListener("click", deletePaste);
document.getElementById('yes-button').removeEventListener("click", deletePaste);
});
function deletePaste() {
fetch(`/api/pastes/delete?id={pasteid}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
id: '{pasteid}'
})
})
.then(response => response.json())
.then(obj => {
const result = JSON.parse(obj);
if (result.message != null) {
createNotification(`Success: ${result.message}`);
setTimeout(() => {
window.location.href = '/';
}, 2000);
} else {
createNotification(`Error: ${result.error}`);
}
});
}
function finalizeEdit() {
var textarea = document.getElementById('edit-textarea');
var text = textarea.value;
fetch(`/api/pastes/edit`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
id: '{pasteid}',
text: text
})
})
.then(response => response.json())
.then(obj => {
const result = JSON.parse(obj);
if (result.message != null) {
createNotification(`Success: ${result.message}`);
document.getElementById('text').innerText = text;
document.getElementById('edit-textarea').remove();
editing = false;
} else {
createNotification(`Error: ${result.error}`);
}
});
}
document.getElementById("no-button").addEventListener("click", function () {
const inputWrapper = document.getElementById('input-wrapper');
inputWrapper.style.display = 'none';
document.getElementById('yes-button').removeEventListener("click", finalizeEdit);
document.getElementById('yes-button').removeEventListener("click", deletePaste);
});
function notification(message) { function notification(message) {
const notification = document.getElementById('notification'); const notification = document.getElementById('notification');
const notificationText = document.getElementById('notification-text'); const notificationText = document.getElementById('notification-text');
@@ -140,13 +280,19 @@
}, 4900); }, 4900);
} }
function createInput(message) {
const inputWrapper = document.getElementById('input-wrapper');
const inputMessage = document.getElementById('input-message');
inputMessage.innerText = message;
inputWrapper.style.display = 'flex';
}
</script> </script>
</html> </html>
<style> <style>
@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+Mono:wght@100..900&display=swap'); @import url('https://fonts.googleapis.com/css2?family=Noto+Sans+Mono:wght@100..900&display=swap');
body { body {
font-family: "Noto Sans Mono", "Consolas", "SF Mono", monospace; font-family: "Noto Sans Mono", "Consolas", "SF Mono", monospace;
font-weight: bold; font-weight: bold;
@@ -157,6 +303,31 @@
background-color: #0d0d0d; background-color: #0d0d0d;
} }
.input-wrapper {
z-index: 100;
display: none;
position: absolute;
flex-direction: column;
justify-content: center;
align-items: center;
width: 100%;
height: 100%;
color: white;
backdrop-filter: blur(2.5px);
}
.input-wrapper-container {
z-index: 101;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 50%;
border-radius: 5px;
padding: 20px;
background-color: #181818;
}
.container-wrapper { .container-wrapper {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@@ -165,6 +336,7 @@
width: 100%; width: 100%;
height: 98.7vh; height: 98.7vh;
} }
.button-input { .button-input {
transition: 300ms; transition: 300ms;
background-color: #222222; background-color: #222222;
@@ -182,11 +354,13 @@
font-weight: 625; font-weight: 625;
box-sizing: content-box; box-sizing: content-box;
} }
.button-input:hover { .button-input:hover {
transition: 300ms; transition: 300ms;
background-color: #333333; background-color: #333333;
border: 2px solid #3a3a3a; border: 2px solid #3a3a3a;
} }
.passwordDiv { .passwordDiv {
z-index: 100; z-index: 100;
position: absolute; position: absolute;
@@ -199,6 +373,7 @@
justify-content: center; justify-content: center;
align-items: center; align-items: center;
} }
.inputDiv { .inputDiv {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@@ -207,6 +382,7 @@
width: fit-content; width: fit-content;
color: white; color: white;
} }
.textinput { .textinput {
width: 100%; width: 100%;
height: 50px; height: 50px;
@@ -219,6 +395,7 @@
font-weight: 625; font-weight: 625;
color: white; color: white;
} }
.textinput:focus { .textinput:focus {
outline: none; outline: none;
border: 2px solid #333333; border: 2px solid #333333;
@@ -321,6 +498,7 @@
height: fit-content; height: fit-content;
overflow-y: auto; overflow-y: auto;
border: #222222 2px solid; border: #222222 2px solid;
z-index: 999999;
} }
.nav-hamburger-menu { .nav-hamburger-menu {
@@ -383,6 +561,7 @@
background-color: #333333; background-color: #333333;
border: #3a3a3a 2px solid; border: #3a3a3a 2px solid;
} }
@media screen and (max-width: 800px) { @media screen and (max-width: 800px) {
.nav-div { .nav-div {
display: none; display: none;
@@ -401,6 +580,7 @@
} }
} }
@keyframes hoverup { @keyframes hoverup {
0% { 0% {
opacity: 0; opacity: 0;
@@ -436,6 +616,7 @@
} }
} }
.notification-div { .notification-div {
position: fixed; position: fixed;
display: none; display: none;
@@ -453,6 +634,10 @@
margin-bottom: 10px; margin-bottom: 10px;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
z-index: 102;
position: absolute;
}
.notifcations-wrapper{
z-index: 101; z-index: 101;
} }
</style> </style>
+23
View File
@@ -0,0 +1,23 @@
#!/bin/bash
############################################
#### Sharpbin Linux installer ####
############################################
##
## This is a semi completed script to install Sharpbin on Linux, however it does not set it as a system daemon/service, cause idk how to do that lol
##
mkdir sharpbin
cd sharpbin
curl -s "https://api.github.com/repos/whoswhip/Sharpbin/releases/latest" | jq -r '.assets[] | select(.name | test("sharpbin-linux-.*\\.tar$")) | .browser_download_url' | xargs -I {} curl -L -o sharpbin-linux.tar {}
tar -xvf sharpbin-linux.tar
chmod +x Sharpbin
echo "Enter your cloudflare sitekey: "
read sitekey
echo "Enter your cloudflare secretkey: "
read secretkey
echo "{ \"CF_TurnstileSiteKey\": \"$sitekey\", \"CF_TurnstileSecret\": \"$secretkey\" }" > config.json