mirror of
https://github.com/whoswhip/Sharpbin.git
synced 2026-12-06 02:48:43 +00:00
Enhance user authentication and paste management
- Updated `AuthController.cs` to include token in `CreateSession` and improved validation for username and email. - Refactored paste creation logic from `Program.cs` to a new `PasteController.cs`. - Added email validation method in `HelperService.cs`. - Introduced `CompressionService.cs` for handling string compression and decompression. - Improved user experience with autocomplete and spellcheck in HTML forms. - Enhanced date display in `archive.js` and refactored date formatting in `dash.js`. - Updated API endpoints in `login.js` and `register.js` to reflect changes.
This commit is contained in:
@@ -63,7 +63,7 @@ namespace SharpbinV2.Server.Controllers
|
|||||||
|
|
||||||
string token = HelperService.GenerateToken();
|
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)
|
if (session.UUID == "0" || session == null)
|
||||||
return StatusCode(500, new { success = false, message = "Failed to create session" });
|
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" });
|
return BadRequest(new { success = false, message = "Username or Email is required" });
|
||||||
if (request.Password.Length is < 8 or > 128)
|
if (request.Password.Length is < 8 or > 128)
|
||||||
return BadRequest(new { success = false, message = "Password must be between 8 and 128 characters" });
|
return BadRequest(new { success = false, message = "Password must be between 8 and 128 characters" });
|
||||||
if (!string.IsNullOrWhiteSpace(request.Username) && request.Username.Length > 32)
|
if (request.Username.Length is < 3 or > 32)
|
||||||
return BadRequest(new { success = false, message = "Username must be 32 characters or less" });
|
return BadRequest(new { success = false, message = "Username must be between 3 and 32 characters" });
|
||||||
if (!string.IsNullOrWhiteSpace(request.Email) && request.Email.Length > 128)
|
if (request.Email.Length > 128)
|
||||||
return BadRequest(new { success = false, message = "Email must be 128 characters or less" });
|
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))
|
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" });
|
return BadRequest(new { success = false, message = "Please provide either a username or an email, not both" });
|
||||||
|
|
||||||
|
|
||||||
if (!string.IsNullOrWhiteSpace(requestDetails.Token))
|
if (!string.IsNullOrWhiteSpace(requestDetails.Token))
|
||||||
{
|
{
|
||||||
var _session = await _databaseService.UserFromToken(requestDetails.Token);
|
var _session = await _databaseService.UserFromToken(requestDetails.Token);
|
||||||
@@ -138,10 +141,10 @@ namespace SharpbinV2.Server.Controllers
|
|||||||
string uuid = Guid.NewGuid().ToString();
|
string uuid = Guid.NewGuid().ToString();
|
||||||
|
|
||||||
User? user = await _databaseService.CreateUser(request.Username, request.Email, hashedPassword, uuid);
|
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" });
|
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)
|
if (session.UUID == "0" || session == null)
|
||||||
return StatusCode(500, new { success = false, message = "Failed to create session" });
|
return StatusCode(500, new { success = false, message = "Failed to create session" });
|
||||||
@@ -190,12 +193,12 @@ namespace SharpbinV2.Server.Controllers
|
|||||||
var requestDetails = HelperService.GetRequestDetails(HttpContext);
|
var requestDetails = HelperService.GetRequestDetails(HttpContext);
|
||||||
if (string.IsNullOrWhiteSpace(requestDetails.Token))
|
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);
|
var user = await _databaseService.UserFromToken(requestDetails.Token);
|
||||||
if (user == null)
|
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);
|
var session = await _databaseService.GetSession(requestDetails.Token);
|
||||||
long currentTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
|
long currentTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
|
||||||
@@ -217,7 +220,8 @@ namespace SharpbinV2.Server.Controllers
|
|||||||
user.Username,
|
user.Username,
|
||||||
user.Email,
|
user.Email,
|
||||||
user.DisplayName,
|
user.DisplayName,
|
||||||
user.Created
|
user.Created,
|
||||||
|
user.LastLogin
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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<PasteController> _logger;
|
||||||
|
|
||||||
|
public PasteController(DatabaseService databaseService, ILogger<PasteController> logger)
|
||||||
|
{
|
||||||
|
_databaseService = databaseService;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost("create")]
|
||||||
|
[EnableRateLimiting("uploads")]
|
||||||
|
[Consumes("text/plain")]
|
||||||
|
public async Task<IActionResult> 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."});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -412,97 +412,6 @@ namespace SharpbinV2.Server
|
|||||||
}).RequireRateLimiting("auth");
|
}).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) =>
|
app.MapGet("/api/pastes/archive", async (HttpContext context) =>
|
||||||
{
|
{
|
||||||
var queries = context.Request.Query;
|
var queries = context.Request.Query;
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
|
||||||
|
|
||||||
|
using System.IO.Compression;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace SharpbinV2.Server.Services
|
||||||
|
{
|
||||||
|
public class CompressionService
|
||||||
|
{
|
||||||
|
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 async Task<bool> 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -339,7 +339,7 @@ namespace SharpbinV2.Server.Services
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
public async Task<Session?> CreateSession(User user, RequestDetails details)
|
public async Task<Session?> CreateSession(User user, RequestDetails details, string token)
|
||||||
{
|
{
|
||||||
if (user == null || details == null)
|
if (user == null || details == null)
|
||||||
return new Session { UUID = "0" };
|
return new Session { UUID = "0" };
|
||||||
@@ -347,7 +347,7 @@ namespace SharpbinV2.Server.Services
|
|||||||
{
|
{
|
||||||
UUID = Guid.NewGuid().ToString(),
|
UUID = Guid.NewGuid().ToString(),
|
||||||
UserUUID = user.UUID,
|
UserUUID = user.UUID,
|
||||||
Token = HelperService.GenerateToken(),
|
Token = token,
|
||||||
Created = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
|
Created = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
|
||||||
Expirary = DateTimeOffset.UtcNow.AddDays(14).ToUnixTimeSeconds(),
|
Expirary = DateTimeOffset.UtcNow.AddDays(14).ToUnixTimeSeconds(),
|
||||||
Ip = Bcrypt.HashPassword(details.Ip, Bcrypt.GenerateSalt(8)),
|
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.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("@UUID", user.UUID);
|
||||||
command.Parameters.AddWithValue("@Type", user.Type);
|
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("@Username", user.Username);
|
||||||
command.Parameters.AddWithValue("@DisplayName", user.DisplayName ?? (object)DBNull.Value);
|
command.Parameters.AddWithValue("@DisplayName", user.DisplayName ?? (object)DBNull.Value);
|
||||||
command.Parameters.AddWithValue("@Password", user.Password);
|
command.Parameters.AddWithValue("@Password", user.Password);
|
||||||
command.Parameters.AddWithValue("@Created", user.Created);
|
command.Parameters.AddWithValue("@Created", user.Created);
|
||||||
command.Parameters.AddWithValue("@LastLogin", user.LastLogin);
|
command.Parameters.AddWithValue("@LastLogin", user.LastLogin);
|
||||||
var result = await command.ExecuteScalarAsync();
|
await command.ExecuteNonQueryAsync();
|
||||||
user.UID = result != null ? Convert.ToInt32(result) : 0;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return user;
|
return user;
|
||||||
@@ -495,5 +494,40 @@ namespace SharpbinV2.Server.Services
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
public async Task<bool> 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
using Newtonsoft.Json.Linq;
|
using Newtonsoft.Json.Linq;
|
||||||
using SharpbinV2.Server.Models;
|
using SharpbinV2.Server.Models;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
using Bcrypt = BCrypt.Net.BCrypt;
|
using Bcrypt = BCrypt.Net.BCrypt;
|
||||||
|
|
||||||
namespace SharpbinV2.Server.Services
|
namespace SharpbinV2.Server.Services
|
||||||
@@ -81,5 +82,10 @@ namespace SharpbinV2.Server.Services
|
|||||||
}
|
}
|
||||||
return $"{len:0.##} {sizes[order]}";
|
return $"{len:0.##} {sizes[order]}";
|
||||||
}
|
}
|
||||||
|
public static bool IsValidEmail(string email)
|
||||||
|
{
|
||||||
|
return Regex.IsMatch(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$");
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -132,7 +132,6 @@ body {
|
|||||||
overflow: hidden !important;
|
overflow: hidden !important;
|
||||||
text-overflow: clip !important;
|
text-overflow: clip !important;
|
||||||
white-space: nowrap !important;
|
white-space: nowrap !important;
|
||||||
max-width: 80px;
|
|
||||||
text-align: left;
|
text-align: left;
|
||||||
margin-right: -70px !important;
|
margin-right: -70px !important;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,8 +18,8 @@
|
|||||||
<body>
|
<body>
|
||||||
<div class="main-container">
|
<div class="main-container">
|
||||||
<form class="create-form" id="create-form">
|
<form class="create-form" id="create-form">
|
||||||
<input type="text" name="title" id="title" placeholder="Title" maxlength="500">
|
<input type="text" name="title" id="title" placeholder="Title" maxlength="500" autocomplete="off" spellcheck="false">
|
||||||
<textarea name="content" id="content" placeholder="Content"></textarea>
|
<textarea name="content" id="content" placeholder="Content" autocomplete="off" spellcheck="false"></textarea>
|
||||||
<label id="syntax-label">Syntax Highlighting -</label>
|
<label id="syntax-label">Syntax Highlighting -</label>
|
||||||
<select name="syntax" id="syntax">
|
<select name="syntax" id="syntax">
|
||||||
<option value="none">None</option>
|
<option value="none">None</option>
|
||||||
@@ -52,7 +52,7 @@
|
|||||||
<option value="1">Unlisted</option>
|
<option value="1">Unlisted</option>
|
||||||
<option value="2">Private</option>
|
<option value="2">Private</option>
|
||||||
</select>
|
</select>
|
||||||
<input type="text" name="password" id="password" placeholder="Password" style="display: none;">
|
<input type="password" name="password" id="password" placeholder="Password" style="display: none;" autocomplete="off" spellcheck="false">
|
||||||
<button type="submit">Create Paste</button>
|
<button type="submit">Create Paste</button>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -49,7 +49,7 @@ async function renderArchive(page, limit) {
|
|||||||
<li>
|
<li>
|
||||||
<a href="/${paste.id}">
|
<a href="/${paste.id}">
|
||||||
<p id="archive-title" title="${paste.title}">${title}</p>
|
<p id="archive-title" title="${paste.title}">${title}</p>
|
||||||
<p id="archive-date">${formatDate(paste.created)}</p>
|
<p id="archive-date" title="${formatDate(paste.created)}">${formatDate(paste.created, true)}</p>
|
||||||
<p id="archive-syntax">${paste.syntax || 'Plain Text'}</p>
|
<p id="archive-syntax">${paste.syntax || 'Plain Text'}</p>
|
||||||
</a>
|
</a>
|
||||||
</li>
|
</li>
|
||||||
@@ -88,25 +88,34 @@ async function getPastes(page, limit) {
|
|||||||
return data;
|
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)) {
|
if (typeof unix !== 'number' || isNaN(unix)) {
|
||||||
return 'Invalid date';
|
return 'Invalid date';
|
||||||
}
|
}
|
||||||
const nowunix = Math.floor(Date.now() / 1000);
|
const date = new Date(unix * 1000);
|
||||||
const diff = nowunix - unix;
|
if (isNaN(date.getTime())) {
|
||||||
|
return 'Invalid date';
|
||||||
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`;
|
|
||||||
}
|
}
|
||||||
|
if (relative) {
|
||||||
|
return getRelativeTime(date);
|
||||||
|
}
|
||||||
|
return date.toLocaleDateString([], { year: 'numeric', month: '2-digit', day: '2-digit' });
|
||||||
}
|
}
|
||||||
|
|
||||||
function nextPage() {
|
function nextPage() {
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
|
|
||||||
let currentPage = 1;
|
let currentPage = 1;
|
||||||
let totalPages = 0;
|
let totalPages = 0;
|
||||||
let pastesPerPage = 10;
|
let pastesPerPage = 10;
|
||||||
@@ -6,30 +5,30 @@ let userPastes = [];
|
|||||||
|
|
||||||
|
|
||||||
document.addEventListener('DOMContentLoaded', function () {
|
document.addEventListener('DOMContentLoaded', function () {
|
||||||
fetchAccountInfo();
|
waitForAuthData().then(data => {
|
||||||
|
if (data.success === false) {
|
||||||
|
window.location.href = '/login';
|
||||||
|
} else {
|
||||||
|
updateAccountInfo(data.user);
|
||||||
fetchUserPastes();
|
fetchUserPastes();
|
||||||
|
}
|
||||||
|
}).catch(error => {
|
||||||
|
console.error('Error waiting for auth data:', error);
|
||||||
|
window.location.href = '/login';
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
function waitForAuthData() {
|
||||||
async function fetchAccountInfo() {
|
return new Promise(resolve => {
|
||||||
try {
|
const interval = setInterval(() => {
|
||||||
const response = await fetch('/api/auth/authorized');
|
if (authData) {
|
||||||
|
clearInterval(interval);
|
||||||
const accountData = await response.json();
|
resolve(authData);
|
||||||
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';
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}, 100);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
function updateAccountInfo(data) {
|
function updateAccountInfo(data) {
|
||||||
document.getElementById('account-username').textContent = `Username: ${data.username}`;
|
document.getElementById('account-username').textContent = `Username: ${data.username}`;
|
||||||
document.getElementById('account-email').textContent = `Email: ${data.email || 'Not provided'}`;
|
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())) {
|
if (isNaN(date.getTime())) {
|
||||||
return 'Never';
|
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() {
|
async function fetchUserPastes() {
|
||||||
try {
|
try {
|
||||||
const response = await fetch('/api/pastes/my?page=0&limit=15');
|
const response = await fetch('/api/pastes/my?page=0&limit=15');
|
||||||
@@ -154,7 +141,7 @@ function displayPastes() {
|
|||||||
const dateP = document.createElement('p');
|
const dateP = document.createElement('p');
|
||||||
dateP.id = 'paste-date';
|
dateP.id = 'paste-date';
|
||||||
const createdDate = new Date(paste.created * 1000);
|
const createdDate = new Date(paste.created * 1000);
|
||||||
dateP.textContent = `${formatDate(createdDate)} (${getRelativeTime(createdDate)})`;
|
dateP.textContent = `${formatDate(createdDate)}`;
|
||||||
|
|
||||||
|
|
||||||
const syntaxP = document.createElement('p');
|
const syntaxP = document.createElement('p');
|
||||||
|
|||||||
@@ -35,6 +35,9 @@ document.getElementById("create-form").addEventListener("submit", async function
|
|||||||
|
|
||||||
fetch(`/api/pastes/create?title=${title}&visibility=${visibility}&syntax=${syntax}`, {
|
fetch(`/api/pastes/create?title=${title}&visibility=${visibility}&syntax=${syntax}`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'text/plain'
|
||||||
|
},
|
||||||
body: content
|
body: content
|
||||||
})
|
})
|
||||||
.then(response => response.json())
|
.then(response => response.json())
|
||||||
|
|||||||
@@ -74,7 +74,7 @@ document.addEventListener('DOMContentLoaded', function () {
|
|||||||
|
|
||||||
async function checkAuthStatus() {
|
async function checkAuthStatus() {
|
||||||
try {
|
try {
|
||||||
const response = await fetch('/api/accounts/authorized');
|
const response = await fetch('/api/auth/authenticated');
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
|
|
||||||
if (data.success) {
|
if (data.success) {
|
||||||
|
|||||||
@@ -171,6 +171,8 @@ const navbarHTML = `
|
|||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
|
|
||||||
|
let authData = null;
|
||||||
|
|
||||||
document.addEventListener('DOMContentLoaded', async () => {
|
document.addEventListener('DOMContentLoaded', async () => {
|
||||||
document.body.insertAdjacentHTML('afterbegin', navbarHTML);
|
document.body.insertAdjacentHTML('afterbegin', navbarHTML);
|
||||||
var path = window.location.pathname;
|
var path = window.location.pathname;
|
||||||
@@ -178,8 +180,9 @@ document.addEventListener('DOMContentLoaded', async () => {
|
|||||||
|
|
||||||
let accountHref = '/login';
|
let accountHref = '/login';
|
||||||
try {
|
try {
|
||||||
const resp = await fetch('/api/accounts/authorized');
|
const resp = await fetch('/api/auth/authenticated');
|
||||||
const data = await resp.json();
|
const data = await resp.json();
|
||||||
|
authData = data;
|
||||||
if (data && data.success !== false) {
|
if (data && data.success !== false) {
|
||||||
accountHref = '/dash';
|
accountHref = '/dash';
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -96,7 +96,7 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
|
|
||||||
async function checkAuthStatus() {
|
async function checkAuthStatus() {
|
||||||
try {
|
try {
|
||||||
const response = await fetch('/api/accounts/authorized');
|
const response = await fetch('/api/auth/authenticated');
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
|
|
||||||
if (data.success) {
|
if (data.success) {
|
||||||
|
|||||||
@@ -22,11 +22,11 @@
|
|||||||
<form id="login-form" class="auth-form">
|
<form id="login-form" class="auth-form">
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label for="username">Username or Email</label>
|
<label for="username">Username or Email</label>
|
||||||
<input type="text" id="username" name="username" placeholder="Enter your username or email" required>
|
<input type="text" id="username" name="username" placeholder="Enter your username or email" required autocomplete="off" spellcheck="false">
|
||||||
</div>
|
</div>
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label for="password">Password</label>
|
<label for="password">Password</label>
|
||||||
<input type="password" id="password" name="password" placeholder="Enter your password" required>
|
<input type="password" id="password" name="password" placeholder="Enter your password" required autocomplete="off" spellcheck="false">
|
||||||
</div>
|
</div>
|
||||||
<button type="submit" class="auth-button">Login</button>
|
<button type="submit" class="auth-button">Login</button>
|
||||||
</form> <div class="auth-links">
|
</form> <div class="auth-links">
|
||||||
|
|||||||
@@ -22,19 +22,19 @@
|
|||||||
<form id="register-form" class="auth-form">
|
<form id="register-form" class="auth-form">
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label for="username">Username</label>
|
<label for="username">Username</label>
|
||||||
<input type="text" id="username" name="username" placeholder="Choose a username" required>
|
<input type="text" id="username" name="username" placeholder="Choose a username" required autocomplete="off" spellcheck="false">
|
||||||
</div>
|
</div>
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label for="email">Email (optional)</label>
|
<label for="email">Email (optional)</label>
|
||||||
<input type="email" id="email" name="email" placeholder="Enter your email">
|
<input type="email" id="email" name="email" placeholder="Enter your email" autocomplete="off" spellcheck="false">
|
||||||
</div>
|
</div>
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label for="password">Password</label>
|
<label for="password">Password</label>
|
||||||
<input type="password" id="password" name="password" placeholder="Create a password" required>
|
<input type="password" id="password" name="password" placeholder="Create a password" required autocomplete="off" spellcheck="false">
|
||||||
</div>
|
</div>
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label for="confirm-password">Confirm Password</label>
|
<label for="confirm-password">Confirm Password</label>
|
||||||
<input type="password" id="confirm-password" name="confirm-password" placeholder="Confirm your password" required>
|
<input type="password" id="confirm-password" name="confirm-password" placeholder="Confirm your password" required autocomplete="off" spellcheck="false">
|
||||||
</div>
|
</div>
|
||||||
<button type="submit" class="auth-button">Register</button>
|
<button type="submit" class="auth-button">Register</button>
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
Reference in New Issue
Block a user