diff --git a/SharpbinV2.Server/Controllers/AuthController.cs b/SharpbinV2.Server/Controllers/AuthController.cs index aabfda1..3e9b672 100644 --- a/SharpbinV2.Server/Controllers/AuthController.cs +++ b/SharpbinV2.Server/Controllers/AuthController.cs @@ -63,7 +63,7 @@ namespace SharpbinV2.Server.Controllers string token = HelperService.GenerateToken(); - var session = await _databaseService.CreateSession(user, requestDetails) ?? new Session(); + var session = await _databaseService.CreateSession(user, requestDetails, token) ?? new Session(); if (session.UUID == "0" || session == null) return StatusCode(500, new { success = false, message = "Failed to create session" }); @@ -104,13 +104,16 @@ namespace SharpbinV2.Server.Controllers return BadRequest(new { success = false, message = "Username or Email is required" }); if (request.Password.Length is < 8 or > 128) return BadRequest(new { success = false, message = "Password must be between 8 and 128 characters" }); - if (!string.IsNullOrWhiteSpace(request.Username) && request.Username.Length > 32) - return BadRequest(new { success = false, message = "Username must be 32 characters or less" }); - if (!string.IsNullOrWhiteSpace(request.Email) && request.Email.Length > 128) + if (request.Username.Length is < 3 or > 32) + return BadRequest(new { success = false, message = "Username must be between 3 and 32 characters" }); + if (request.Email.Length > 128) return BadRequest(new { success = false, message = "Email must be 128 characters or less" }); + if (!string.IsNullOrWhiteSpace(request.Email) && !HelperService.IsValidEmail(request.Email)) + return BadRequest(new { success = false, message = "Invalid email" }); if (!string.IsNullOrWhiteSpace(request.Username) && !string.IsNullOrWhiteSpace(request.Email)) return BadRequest(new { success = false, message = "Please provide either a username or an email, not both" }); + if (!string.IsNullOrWhiteSpace(requestDetails.Token)) { var _session = await _databaseService.UserFromToken(requestDetails.Token); @@ -138,10 +141,10 @@ namespace SharpbinV2.Server.Controllers string uuid = Guid.NewGuid().ToString(); User? user = await _databaseService.CreateUser(request.Username, request.Email, hashedPassword, uuid); - if (user == null || user.UID == 0) + if (user == null) return StatusCode(500, new { success = false, message = "Failed to create user" }); - var session = await _databaseService.CreateSession(user, requestDetails) ?? new Session(); + var session = await _databaseService.CreateSession(user, requestDetails, token) ?? new Session(); if (session.UUID == "0" || session == null) return StatusCode(500, new { success = false, message = "Failed to create session" }); @@ -190,12 +193,12 @@ namespace SharpbinV2.Server.Controllers var requestDetails = HelperService.GetRequestDetails(HttpContext); if (string.IsNullOrWhiteSpace(requestDetails.Token)) { - return Unauthorized(new { success = false, message = "Not authenticated" }); + return Unauthorized(new { success = false, message = "Not authenticated, no token found" }); } var user = await _databaseService.UserFromToken(requestDetails.Token); if (user == null) { - return Unauthorized(new { success = false, message = "Not authenticated" }); + return Unauthorized(new { success = false, message = "Not authenticated, invalid token" }); } var session = await _databaseService.GetSession(requestDetails.Token); long currentTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); @@ -217,7 +220,8 @@ namespace SharpbinV2.Server.Controllers user.Username, user.Email, user.DisplayName, - user.Created + user.Created, + user.LastLogin } }); } diff --git a/SharpbinV2.Server/Controllers/PasteController.cs b/SharpbinV2.Server/Controllers/PasteController.cs new file mode 100644 index 0000000..2209ac7 --- /dev/null +++ b/SharpbinV2.Server/Controllers/PasteController.cs @@ -0,0 +1,108 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; +using SharpbinV2.Server.Services; +using SharpbinV2.Server.Models; +using System.Text; +using System.IO; + +namespace SharpbinV2.Server.Controllers +{ + [ApiController] + [Route("api/pastes")] + public class PasteController : Controller + { + private readonly DatabaseService _databaseService; + private readonly ILogger _logger; + + public PasteController(DatabaseService databaseService, ILogger logger) + { + _databaseService = databaseService; + _logger = logger; + } + + [HttpPost("create")] + [EnableRateLimiting("uploads")] + [Consumes("text/plain")] + public async Task CreatePaste() + { + try + { + string content = await new StreamReader(HttpContext.Request.Body, Encoding.UTF8).ReadToEndAsync(); + var requestDetails = HelperService.GetRequestDetails(HttpContext); + var queries = HttpContext.Request.Query; + + if (string.IsNullOrWhiteSpace(content)) + return BadRequest(new { success = false, message = "Content cannot be empty." }); + + if (content.Length > Program.MaxFileSize) + return BadRequest(new { success = false, message = $"Content exceeds maximum size of {Program.MaxFileSize} bytes." }); + + string title = queries.ContainsKey("title") ? queries["title"].ToString() : $"Untitled {await _databaseService.EnumeratePastes()}"; + string syntax = queries.ContainsKey("syntax") ? queries["syntax"].ToString() : "none"; + int visibility = queries.ContainsKey("visibility") ? int.Parse(queries["visibility"]) : 0; + + if (title.Length > 500) + return BadRequest(new { success = false, message = "Title cannot exceed 500 characters." }); + if (visibility < 0 || visibility > 2) + return BadRequest(new { success = false, message = "Invalid visibility option. Must be 0 (public), 1 (unlisted), or 2 (private)." }); + if (!Program.ValidSyntaxLanguages.Contains(syntax.ToLower())) + return BadRequest(new { success = false, message = "Invalid syntax language specified." }); + if (string.IsNullOrWhiteSpace(title)) + title = $"Untitled {await _databaseService.EnumeratePastes()}"; + + bool shouldCompress = await CompressionService.ShouldCompress(content); + byte[] compressedContent = shouldCompress + ? await CompressionService.CompressString(content) + : Encoding.UTF8.GetBytes(content); + User? user = await _databaseService.UserFromToken(requestDetails.Token ?? ""); + string pasteId = HelperService.GenerateRandomString(8); + + Paste paste = new Paste + { + Created = DateTimeOffset.UtcNow.ToUnixTimeSeconds(), + Size = compressedContent.Length, + TrueSize = content.Length, + UUID = Guid.NewGuid().ToString(), + ID = pasteId, + AuthorUUID = user?.UUID ?? "0", // 0 means the user is anonymous + FilePath = shouldCompress ? $"pastes/{pasteId}.txt.gz" : $"pastes/{pasteId}.txt", + Visibility = visibility, + Title = title, + Edited = 0, + Views = 0, + Syntax = syntax.ToLower() + }; + + await System.IO.File.WriteAllBytesAsync(paste.FilePath, compressedContent); + bool success = await _databaseService.CreatePaste(paste, _logger); + + if (!success) + return StatusCode(500, new { success, message = "An error occurred while creating the paste." }); + + _logger.LogInformation($"Paste created successfully: {pasteId}"); + + return Ok(new + { + success = true, + paste = new + { + paste.ID, + paste.UUID, + paste.Title, + paste.Syntax, + paste.Visibility, + paste.Created, + paste.Size, + paste.TrueSize, + paste.AuthorUUID + }, + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error creating paste"); + return StatusCode(500, new { error = "An error occurred while creating the paste."}); + } + } + } +} diff --git a/SharpbinV2.Server/Program.cs b/SharpbinV2.Server/Program.cs index e3d08dc..7e9ab83 100644 --- a/SharpbinV2.Server/Program.cs +++ b/SharpbinV2.Server/Program.cs @@ -412,97 +412,6 @@ namespace SharpbinV2.Server }).RequireRateLimiting("auth"); - app.MapPost("/api/pastes/create", async (HttpContext context) => - { - var body = await new StreamReader(context.Request.Body).ReadToEndAsync(); - if (body == null) - { - context.Response.StatusCode = 400; - await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid Body." }); - return; - } - if (body.Length > MaxFileSize) - { - context.Response.StatusCode = 400; - await context.Response.WriteAsJsonAsync(new { success = false, message = "File size too large." }); - return; - } - - var paste = new Paste(); - var requestdetails = GetRequestDetails(context); - var user = await Database.UserFromToken(requestdetails.Token); - var queries = context.Request.Query; - - if (queries.ContainsKey("title") && queries["title"].ToString().Length > 500) - { - context.Response.StatusCode = 400; - await context.Response.WriteAsJsonAsync(new { success = false, message = "Title too long." }); - return; - } - - - paste.Created = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); - paste.Size = body.Length; - paste.TrueSize = body.Length; - paste.UUID = Guid.NewGuid().ToString(); - paste.ID = GenerateRandomString(12); - paste.AuthorUUID = user?.UUID ?? "0"; // 0 means the user is anonymous - paste.FilePath = $"pastes/{paste.ID}.txt"; - paste.Visibility = queries.ContainsKey("visibility") ? Convert.ToInt32(queries["visibility"]) : 0; - paste.Title = queries.ContainsKey("title") && !string.IsNullOrEmpty(queries["title"].ToString()) ? queries["title"].ToString() : $"Untitled-{await Database.EnumeratePastes()}"; - paste.Edited = 0; - paste.Views = 0; - paste.Syntax = queries.ContainsKey("syntax") ? queries["syntax"].ToString() : null; - - if (!string.IsNullOrEmpty(paste.Syntax) && !ValidSyntaxLanguages.Contains(paste.Syntax.ToLower())) - { - context.Response.StatusCode = 400; - await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid syntax language." }); - return; - } - - bool shouldCompress = await Compression.ShouldCompress(body); - if (shouldCompress) - { - var compressed = await Compression.CompressString(body); - paste.Size = compressed.Length; - paste.TrueSize = body.Length; - paste.FilePath += ".gz"; - await File.WriteAllBytesAsync(paste.FilePath, compressed); - } - else - { - await File.WriteAllTextAsync(paste.FilePath, body); - } - - using (var connection = new SqliteConnection(MainDatabaseConnection)) - { - await connection.OpenAsync(); - using (var command = connection.CreateCommand()) - { - command.CommandText = "INSERT INTO pastes (UUID, ID, Visibility, Title, AuthorUUID, FilePath, Created, Edited, Size, TrueSize, Views, Syntax) VALUES (@UUID, @ID, @Visibility, @Title, @AuthorUUID, @FilePath, @Created, @Edited, @Size, @TrueSize, @Views, @Syntax);"; - command.Parameters.AddWithValue("@UUID", paste.UUID); - command.Parameters.AddWithValue("@ID", paste.ID); - command.Parameters.AddWithValue("@Visibility", paste.Visibility); - command.Parameters.AddWithValue("@Title", paste.Title); - command.Parameters.AddWithValue("@AuthorUUID", paste.AuthorUUID); - command.Parameters.AddWithValue("@FilePath", paste.FilePath); - command.Parameters.AddWithValue("@Created", paste.Created); - command.Parameters.AddWithValue("@Edited", paste.Edited); - command.Parameters.AddWithValue("@Size", paste.Size); - command.Parameters.AddWithValue("@TrueSize", paste.TrueSize); - command.Parameters.AddWithValue("@Views", paste.Views); - command.Parameters.AddWithValue("@Syntax", paste.Syntax); - await command.ExecuteNonQueryAsync(); - } - await connection.CloseAsync(); - } - paste.FilePath = null; - context.Response.StatusCode = 200; - await context.Response.WriteAsJsonAsync(new { success = true, message = "Paste created.", paste = paste }); - logger.LogInfo($"A Paste of {FormatBytes(paste.Size ?? 0)} was created by {paste.UUID}"); - return; - }).RequireRateLimiting("uploads"); app.MapGet("/api/pastes/archive", async (HttpContext context) => { var queries = context.Request.Query; diff --git a/SharpbinV2.Server/Services/CompressionService.cs b/SharpbinV2.Server/Services/CompressionService.cs new file mode 100644 index 0000000..12d1c7a --- /dev/null +++ b/SharpbinV2.Server/Services/CompressionService.cs @@ -0,0 +1,74 @@ + + +using System.IO.Compression; +using System.Text; + +namespace SharpbinV2.Server.Services +{ + public class CompressionService + { + public static async Task 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 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 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 async Task ShouldCompress(string text, int sizeThreshold = 512, double ratioThreshold = 0.8) + { + if (string.IsNullOrWhiteSpace(text)) + return false; + + byte[] inputBytes = Encoding.UTF8.GetBytes(text); + if (inputBytes.Length < sizeThreshold) + return false; + + byte[] compressedBytes = await CompressString(text).ConfigureAwait(false); + double compressionRatio = (double)compressedBytes.Length / inputBytes.Length; + + return compressionRatio < ratioThreshold; + } + public static bool IsCompressed(byte[] data) + { + return data.Length >= 2 && data[0] == 0x1F && data[1] == 0x8B; + } + } +} diff --git a/SharpbinV2.Server/Services/DatabaseService.cs b/SharpbinV2.Server/Services/DatabaseService.cs index 13b6e81..167ede0 100644 --- a/SharpbinV2.Server/Services/DatabaseService.cs +++ b/SharpbinV2.Server/Services/DatabaseService.cs @@ -339,7 +339,7 @@ namespace SharpbinV2.Server.Services } } } - public async Task CreateSession(User user, RequestDetails details) + public async Task CreateSession(User user, RequestDetails details, string token) { if (user == null || details == null) return new Session { UUID = "0" }; @@ -347,7 +347,7 @@ namespace SharpbinV2.Server.Services { UUID = Guid.NewGuid().ToString(), UserUUID = user.UUID, - Token = HelperService.GenerateToken(), + Token = token, Created = DateTimeOffset.UtcNow.ToUnixTimeSeconds(), Expirary = DateTimeOffset.UtcNow.AddDays(14).ToUnixTimeSeconds(), Ip = Bcrypt.HashPassword(details.Ip, Bcrypt.GenerateSalt(8)), @@ -447,14 +447,13 @@ namespace SharpbinV2.Server.Services command.CommandText = "INSERT INTO users (UUID, Type, Email, Username, DisplayName, Password, Created, LastLogin) VALUES (@UUID, @Type, @Email, @Username, @DisplayName, @Password, @Created, @LastLogin);"; command.Parameters.AddWithValue("@UUID", user.UUID); command.Parameters.AddWithValue("@Type", user.Type); - command.Parameters.AddWithValue("@Email", user.Email ?? (object)DBNull.Value); + command.Parameters.AddWithValue("@Email", string.IsNullOrWhiteSpace(user.Email) ? DBNull.Value : user.Email); command.Parameters.AddWithValue("@Username", user.Username); command.Parameters.AddWithValue("@DisplayName", user.DisplayName ?? (object)DBNull.Value); command.Parameters.AddWithValue("@Password", user.Password); command.Parameters.AddWithValue("@Created", user.Created); command.Parameters.AddWithValue("@LastLogin", user.LastLogin); - var result = await command.ExecuteScalarAsync(); - user.UID = result != null ? Convert.ToInt32(result) : 0; + await command.ExecuteNonQueryAsync(); } } return user; @@ -495,5 +494,40 @@ namespace SharpbinV2.Server.Services return true; } } + public async Task CreatePaste(Paste paste, ILogger logger) + { + try + { + if (paste == null || string.IsNullOrEmpty(paste.UUID) || string.IsNullOrEmpty(paste.ID) || paste.AuthorUUID == null) + return false; + using (var connection = new SqliteConnection(_connectionString)) + { + await connection.OpenAsync(); + using (var command = connection.CreateCommand()) + { + command.CommandText = "INSERT INTO pastes (UUID, ID, Visibility, Title, AuthorUUID, FilePath, Created, Edited, Size, TrueSize, Views, Syntax) VALUES (@UUID, @ID, @Visibility, @Title, @AuthorUUID, @FilePath, @Created, @Edited, @Size, @TrueSize, @Views, @Syntax);"; + command.Parameters.AddWithValue("@UUID", paste.UUID); + command.Parameters.AddWithValue("@ID", paste.ID); + command.Parameters.AddWithValue("@Visibility", paste.Visibility ?? 0); + command.Parameters.AddWithValue("@Title", paste.Title ?? (object)DBNull.Value); + command.Parameters.AddWithValue("@AuthorUUID", paste.AuthorUUID); + command.Parameters.AddWithValue("@FilePath", paste.FilePath ?? (object)DBNull.Value); + command.Parameters.AddWithValue("@Created", paste.Created ?? DateTimeOffset.UtcNow.ToUnixTimeSeconds()); + command.Parameters.AddWithValue("@Edited", paste.Edited ?? DateTimeOffset.UtcNow.ToUnixTimeSeconds()); + command.Parameters.AddWithValue("@Size", paste.Size ?? 0); + command.Parameters.AddWithValue("@TrueSize", paste.TrueSize ?? 0); + command.Parameters.AddWithValue("@Views", paste.Views ?? 0); + command.Parameters.AddWithValue("@Syntax", paste.Syntax ?? (object)DBNull.Value); + await command.ExecuteNonQueryAsync(); + return true; + } + } + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to create paste in database."); + return false; + } + } } } diff --git a/SharpbinV2.Server/Services/HelperService.cs b/SharpbinV2.Server/Services/HelperService.cs index 27c710f..15fdb12 100644 --- a/SharpbinV2.Server/Services/HelperService.cs +++ b/SharpbinV2.Server/Services/HelperService.cs @@ -1,6 +1,7 @@ using Newtonsoft.Json.Linq; using SharpbinV2.Server.Models; using System.Text; +using System.Text.RegularExpressions; using Bcrypt = BCrypt.Net.BCrypt; namespace SharpbinV2.Server.Services @@ -81,5 +82,10 @@ namespace SharpbinV2.Server.Services } return $"{len:0.##} {sizes[order]}"; } + public static bool IsValidEmail(string email) + { + return Regex.IsMatch(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$"); + } + } } diff --git a/SharpbinV2.Server/wwwroot/css/dash.css b/SharpbinV2.Server/wwwroot/css/dash.css index b49f34a..82c6e75 100644 --- a/SharpbinV2.Server/wwwroot/css/dash.css +++ b/SharpbinV2.Server/wwwroot/css/dash.css @@ -132,7 +132,6 @@ body { overflow: hidden !important; text-overflow: clip !important; white-space: nowrap !important; - max-width: 80px; text-align: left; margin-right: -70px !important; } diff --git a/SharpbinV2.Server/wwwroot/index.html b/SharpbinV2.Server/wwwroot/index.html index ea6ef30..4a79b14 100644 --- a/SharpbinV2.Server/wwwroot/index.html +++ b/SharpbinV2.Server/wwwroot/index.html @@ -18,8 +18,8 @@
- - + + - +
diff --git a/SharpbinV2.Server/wwwroot/js/archive.js b/SharpbinV2.Server/wwwroot/js/archive.js index 9b1e82c..c98136e 100644 --- a/SharpbinV2.Server/wwwroot/js/archive.js +++ b/SharpbinV2.Server/wwwroot/js/archive.js @@ -49,7 +49,7 @@ async function renderArchive(page, limit) {
  • ${title}

    -

    ${formatDate(paste.created)}

    +

    ${formatDate(paste.created, true)}

    ${paste.syntax || 'Plain Text'}

  • @@ -88,25 +88,34 @@ async function getPastes(page, limit) { return data; } -function formatDate(unix) { +function getRelativeTime(date) { + const now = new Date(); + const diff = now - date; + const seconds = Math.floor(diff / 1000); + const minutes = Math.floor(seconds / 60); + const hours = Math.floor(minutes / 60); + const days = Math.floor(hours / 24); + if (isNaN(date.getTime())) return ''; + if (seconds < 60) return 'just now'; + if (minutes < 60) return `${minutes} min ago`; + if (hours < 24) return `${hours} hr${hours > 1 ? 's' : ''} ago`; + if (days < 7) return `${days} day${days > 1 ? 's' : ''} ago`; + return date.toLocaleDateString(); +} + + +function formatDate(unix, relative = false) { if (typeof unix !== 'number' || isNaN(unix)) { return 'Invalid date'; } - const nowunix = Math.floor(Date.now() / 1000); - const diff = nowunix - unix; - - if (diff < 60) { - return `${diff} second${diff !== 1 ? 's' : ''} ago`; - } else if (diff < 3600) { - const minutes = Math.floor(diff / 60); - return `${minutes} minute${minutes !== 1 ? 's' : ''} ago`; - } else if (diff < 86400) { - const hours = Math.floor(diff / 3600); - return `${hours} hour${hours !== 1 ? 's' : ''} ago`; - } else { - const days = Math.floor(diff / 86400); - return `${days} day${days !== 1 ? 's' : ''} ago`; + const date = new Date(unix * 1000); + if (isNaN(date.getTime())) { + return 'Invalid date'; } + if (relative) { + return getRelativeTime(date); + } + return date.toLocaleDateString([], { year: 'numeric', month: '2-digit', day: '2-digit' }); } function nextPage() { diff --git a/SharpbinV2.Server/wwwroot/js/dash.js b/SharpbinV2.Server/wwwroot/js/dash.js index 8ad14a1..c477a72 100644 --- a/SharpbinV2.Server/wwwroot/js/dash.js +++ b/SharpbinV2.Server/wwwroot/js/dash.js @@ -1,4 +1,3 @@ - let currentPage = 1; let totalPages = 0; let pastesPerPage = 10; @@ -6,30 +5,30 @@ let userPastes = []; document.addEventListener('DOMContentLoaded', function () { - fetchAccountInfo(); - fetchUserPastes(); + waitForAuthData().then(data => { + if (data.success === false) { + window.location.href = '/login'; + } else { + updateAccountInfo(data.user); + fetchUserPastes(); + } + }).catch(error => { + console.error('Error waiting for auth data:', error); + window.location.href = '/login'; + }); }); - -async function fetchAccountInfo() { - try { - const response = await fetch('/api/auth/authorized'); - - const accountData = await response.json(); - if (accountData.success === false) { - window.location.href = '/login'; - } - updateAccountInfo(accountData.user); - } catch (error) { - console.error('Error fetching account information:', error); - - if (error.message.includes('401')) { - window.location.href = '/login.html'; - } - } +function waitForAuthData() { + return new Promise(resolve => { + const interval = setInterval(() => { + if (authData) { + clearInterval(interval); + resolve(authData); + } + }, 100); + }); } - function updateAccountInfo(data) { document.getElementById('account-username').textContent = `Username: ${data.username}`; document.getElementById('account-email').textContent = `Email: ${data.email || 'Not provided'}`; @@ -49,31 +48,19 @@ function updateAccountInfo(data) { } -function formatDate(date) { +function formatDate(date, minutes = false) { if (isNaN(date.getTime())) { return 'Never'; } - return date.toLocaleDateString() + ' ' + date.toLocaleTimeString(); + if (minutes) + { + return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], { minute: '2-digit', hour: '2-digit' }); + } else { + return date.toLocaleDateString([], { year: 'numeric', month: '2-digit', day: '2-digit' }); + } } - -function getRelativeTime(date) { - const now = new Date(); - const diff = now - date; - const seconds = Math.floor(diff / 1000); - const minutes = Math.floor(seconds / 60); - const hours = Math.floor(minutes / 60); - const days = Math.floor(hours / 24); - if (isNaN(date.getTime())) return ''; - if (seconds < 60) return 'just now'; - if (minutes < 60) return `${minutes} min ago`; - if (hours < 24) return `${hours} hr${hours > 1 ? 's' : ''} ago`; - if (days < 7) return `${days} day${days > 1 ? 's' : ''} ago`; - return date.toLocaleDateString(); -} - - async function fetchUserPastes() { try { const response = await fetch('/api/pastes/my?page=0&limit=15'); @@ -154,7 +141,7 @@ function displayPastes() { const dateP = document.createElement('p'); dateP.id = 'paste-date'; const createdDate = new Date(paste.created * 1000); - dateP.textContent = `${formatDate(createdDate)} (${getRelativeTime(createdDate)})`; + dateP.textContent = `${formatDate(createdDate)}`; const syntaxP = document.createElement('p'); @@ -268,4 +255,4 @@ function deleteAccount() { } catch { } window.location.href = '/register'; }; -} +} \ No newline at end of file diff --git a/SharpbinV2.Server/wwwroot/js/index.js b/SharpbinV2.Server/wwwroot/js/index.js index f7b7f3d..f9a1c3f 100644 --- a/SharpbinV2.Server/wwwroot/js/index.js +++ b/SharpbinV2.Server/wwwroot/js/index.js @@ -35,6 +35,9 @@ document.getElementById("create-form").addEventListener("submit", async function fetch(`/api/pastes/create?title=${title}&visibility=${visibility}&syntax=${syntax}`, { method: "POST", + headers: { + 'Content-Type': 'text/plain' + }, body: content }) .then(response => response.json()) diff --git a/SharpbinV2.Server/wwwroot/js/login.js b/SharpbinV2.Server/wwwroot/js/login.js index 6bf87a3..af25e4d 100644 --- a/SharpbinV2.Server/wwwroot/js/login.js +++ b/SharpbinV2.Server/wwwroot/js/login.js @@ -74,7 +74,7 @@ document.addEventListener('DOMContentLoaded', function () { async function checkAuthStatus() { try { - const response = await fetch('/api/accounts/authorized'); + const response = await fetch('/api/auth/authenticated'); const data = await response.json(); if (data.success) { diff --git a/SharpbinV2.Server/wwwroot/js/main.js b/SharpbinV2.Server/wwwroot/js/main.js index a4bb5f7..d3975ab 100644 --- a/SharpbinV2.Server/wwwroot/js/main.js +++ b/SharpbinV2.Server/wwwroot/js/main.js @@ -171,6 +171,8 @@ const navbarHTML = ` `; +let authData = null; + document.addEventListener('DOMContentLoaded', async () => { document.body.insertAdjacentHTML('afterbegin', navbarHTML); var path = window.location.pathname; @@ -178,8 +180,9 @@ document.addEventListener('DOMContentLoaded', async () => { let accountHref = '/login'; try { - const resp = await fetch('/api/accounts/authorized'); + const resp = await fetch('/api/auth/authenticated'); const data = await resp.json(); + authData = data; if (data && data.success !== false) { accountHref = '/dash'; } diff --git a/SharpbinV2.Server/wwwroot/js/register.js b/SharpbinV2.Server/wwwroot/js/register.js index 172076f..d9f6ebd 100644 --- a/SharpbinV2.Server/wwwroot/js/register.js +++ b/SharpbinV2.Server/wwwroot/js/register.js @@ -96,7 +96,7 @@ document.addEventListener('DOMContentLoaded', function() { async function checkAuthStatus() { try { - const response = await fetch('/api/accounts/authorized'); + const response = await fetch('/api/auth/authenticated'); const data = await response.json(); if (data.success) { diff --git a/SharpbinV2.Server/wwwroot/login.html b/SharpbinV2.Server/wwwroot/login.html index a9382e0..c20548c 100644 --- a/SharpbinV2.Server/wwwroot/login.html +++ b/SharpbinV2.Server/wwwroot/login.html @@ -22,11 +22,11 @@
    - +
    - +