Add password reset functionality(WIP): implement PasswordReset class, database methods for password reset, and update routes for password reset handling. Enhance UI with new success message styles and update login page with reset password link.

This commit is contained in:
whoswhip
2025-06-29 10:29:37 -04:00
parent 73743399f1
commit 38411ca7c0
7 changed files with 320 additions and 44 deletions
+229 -32
View File
@@ -4,6 +4,7 @@ using System.Text;
using Bcrypt = BCrypt.Net.BCrypt;
using System.Security.Cryptography;
using UAParser;
using Microsoft.AspNetCore.RateLimiting;
namespace SharpbinV2.Server
{
@@ -49,11 +50,11 @@ namespace SharpbinV2.Server
builder.Configuration.AddEnvironmentVariables();
if (Environment.GetEnvironmentVariable("HTTPS") == "true")
{
builder.WebHost.UseUrls($"https://*:{Environment.GetEnvironmentVariable("HTTPS_Port") ?? "5820"}");
builder.WebHost.UseUrls($"https://*:{Environment.GetEnvironmentVariable("ASPNETCORE_HTTPS_PORTS") ?? "5820"}");
}
else
{
builder.WebHost.UseUrls($"http://*:{Environment.GetEnvironmentVariable("HTTP_Port") ?? "5810"}");
builder.WebHost.UseUrls($"http://*:{Environment.GetEnvironmentVariable("ASPNETCORE_HTTP_PORTS") ?? "5810"}");
}
MaxFileSize = Environment.GetEnvironmentVariable("MAX_FILE_SIZE") != null ? Convert.ToInt64(Environment.GetEnvironmentVariable("MAX_FILE_SIZE")) : MaxFileSize;
HMACSecret = Environment.GetEnvironmentVariable("HMAC_SECRET") ?? HMACSecret;
@@ -72,6 +73,41 @@ namespace SharpbinV2.Server
options.Limits.MaxRequestBodySize = null;
});
builder.Services.AddRateLimiter(options =>
{
options.AddTokenBucketLimiter("uploads", opt =>
{
opt.TokenLimit = 10;
opt.ReplenishmentPeriod = TimeSpan.FromMinutes(1);
opt.TokensPerPeriod = 2;
opt.AutoReplenishment = true;
});
options.AddTokenBucketLimiter("auth", opt =>
{
opt.TokenLimit = 15;
opt.ReplenishmentPeriod = TimeSpan.FromMinutes(5);
opt.TokensPerPeriod = 10;
opt.AutoReplenishment = true;
});
options.AddFixedWindowLimiter("general", opt =>
{
opt.PermitLimit = 200;
opt.Window = TimeSpan.FromMinutes(1);
});
options.OnRejected = async (context, token) =>
{
context.HttpContext.Response.StatusCode = 429;
await context.HttpContext.Response.WriteAsJsonAsync(new
{
success = false,
message = "Rate limit exceeded. Please try again later."
});
};
});
// Add services to the container.
builder.Services.AddCors();
builder.Services.AddResponseCaching();
@@ -92,7 +128,7 @@ namespace SharpbinV2.Server
app.UseRouting();
app.UseStaticFiles();
//app.UseRateLimiter();
app.UseRateLimiter();
app.UseCors(builder =>
{
@@ -109,7 +145,7 @@ namespace SharpbinV2.Server
context.Response.StatusCode = 200;
context.Response.Headers.Add("Content-Type", "text/html");
return context.Response.SendFileAsync("wwwroot/index.html");
});
}).RequireRateLimiting("general");
app.MapGet("/{pasteid}", async (HttpContext context, IWebHostEnvironment env) =>
{
var pasteid = context.Request.RouteValues["pasteid"].ToString() ?? null;
@@ -182,7 +218,7 @@ namespace SharpbinV2.Server
context.Response.StatusCode = 200;
context.Response.Headers.Add("Content-Type", "text/html");
await context.Response.SendFileAsync("wwwroot/paste.html");
});
}).RequireRateLimiting("general");
app.MapGet("/error", async (HttpContext context) =>
{
context.Response.StatusCode = 400;
@@ -220,7 +256,7 @@ namespace SharpbinV2.Server
{
await context.Response.SendFileAsync(paste.FilePath);
}
});
}).RequireRateLimiting("general");
app.MapGet("/paste.html", (HttpContext context) =>
{
context.Response.Redirect("/");
@@ -230,13 +266,13 @@ namespace SharpbinV2.Server
context.Response.StatusCode = 200;
context.Response.Headers.Add("Content-Type", "text/html");
await context.Response.SendFileAsync("wwwroot/archive.html");
});
}).RequireRateLimiting("general");
app.MapGet("/dash", async (HttpContext context) =>
{
context.Response.StatusCode = 200;
context.Response.Headers.Add("Content-Type", "text/html");
await context.Response.SendFileAsync("wwwroot/dash.html");
});
}).RequireRateLimiting("general");
app.MapGet("/dash.html", (HttpContext context) =>
{
context.Response.Redirect("/dash");
@@ -246,13 +282,13 @@ namespace SharpbinV2.Server
context.Response.StatusCode = 200;
context.Response.Headers.Add("Content-Type", "text/html");
await context.Response.SendFileAsync("wwwroot/login.html");
});
}).RequireRateLimiting("general");
app.MapGet("/register", async (HttpContext context) =>
{
context.Response.StatusCode = 200;
context.Response.Headers.Add("Content-Type", "text/html");
await context.Response.SendFileAsync("wwwroot/register.html");
});
}).RequireRateLimiting("general");
app.MapGet("/u/{username}", async (HttpContext context) =>
{
var username = context.Request.RouteValues["username"].ToString() ?? null;
@@ -270,9 +306,15 @@ namespace SharpbinV2.Server
context.Response.Headers.Add("Expires", "0");
context.Response.WriteAsync(html);
await context.Response.WriteAsync(html);
});
}).RequireRateLimiting("general");
app.MapGet("/reset-password", async (HttpContext context) =>
{
context.Response.StatusCode = 200;
context.Response.Headers.Add("Content-Type", "text/html");
await context.Response.SendFileAsync("wwwroot/reset-password.html");
}).RequireRateLimiting("general");
#endregion
@@ -369,7 +411,7 @@ namespace SharpbinV2.Server
await context.Response.WriteAsJsonAsync(new { success = true, message = "Account created." });
logger.LogInfo($"Account {username} has been created.");
return;
});
}).RequireRateLimiting("auth");
app.MapPost("/api/accounts/login", async (HttpContext context) =>
{
var requestdetails = GetRequestDetails(context);
@@ -466,7 +508,7 @@ namespace SharpbinV2.Server
await context.Response.WriteAsJsonAsync(new { success = true, message = "Logged in." });
logger.LogInfo($"User {user.UUID} logged in.");
return;
});
}).RequireRateLimiting("auth");
app.MapGet("/api/accounts/authorized", async (HttpContext context) =>
{
var requestdetails = GetRequestDetails(context);
@@ -565,7 +607,7 @@ namespace SharpbinV2.Server
context.Response.StatusCode = 200;
await context.Response.WriteAsJsonAsync(new { success = true, message = "Account deleted." });
});
}).RequireRateLimiting("auth");
app.MapPost("/api/accounts/logout", async (HttpContext context) =>
{
var requestdetails = GetRequestDetails(context);
@@ -605,7 +647,103 @@ namespace SharpbinV2.Server
context.Response.StatusCode = 200;
await context.Response.WriteAsJsonAsync(new { success = true, message = "Logged out." });
});
app.MapPost("/api/accounts/reset-password", async (HttpContext context) =>
{
var requestdetails = GetRequestDetails(context);
if (string.IsNullOrEmpty(requestdetails.Token))
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, message = "No token provided, not authorized." });
return;
}
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;
}
var json = TryParse(body);
if (json == null)
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid JSON." });
return;
}
if (!string.IsNullOrEmpty(json["token"]?.ToString()) && !string.IsNullOrEmpty(json["uuid"]?.ToString()) && !string.IsNullOrEmpty(json["url"]?.ToString()))
{
var password = json["password"]?.ToString();
var uuid = json["uuid"]?.ToString();
var token = json["token"]?.ToString();
var url = json["url"]?.ToString();
if (string.IsNullOrEmpty(uuid) || string.IsNullOrEmpty(token) || string.IsNullOrEmpty(url) || string.IsNullOrEmpty(password))
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, message = "Missing required fields." });
return;
}
var pwreset = await Database.GetPasswordReset(url, uuid, token);
if (pwreset == null)
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid token/url/uuid." });
return;
}
var user = await Database.UserFromUUID(uuid);
if (user == null)
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid user." });
return;
}
var passwordHashed = Bcrypt.HashPassword(password, Bcrypt.GenerateSalt(12));
if (!Database.ResetPassword(user.UUID ?? "", passwordHashed).Result)
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, message = "Failed to reset password." });
return;
}
else
{
context.Response.StatusCode = 200;
await context.Response.WriteAsJsonAsync(new { success = true, message = "Password reset." });
}
return;
}
else // normal password resets from the dashboard
{
var user = await Database.UserFromToken(requestdetails.Token);
if (user == null)
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid token." });
return;
}
var password = json["password"]?.ToString();
if (string.IsNullOrEmpty(password))
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, message = "Missing required fields." });
return;
}
var passwordHashed = Bcrypt.HashPassword(password, Bcrypt.GenerateSalt(12));
if (!Database.ResetPassword(user.UUID ?? "", passwordHashed).Result)
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, message = "Failed to reset password." });
return;
}
else
{
context.Response.StatusCode = 200;
await context.Response.WriteAsJsonAsync(new { success = true, message = "Password reset." });
}
}
}).RequireRateLimiting("auth");
app.MapPost("/api/pastes/create", async (HttpContext context) =>
{
@@ -654,7 +792,7 @@ namespace SharpbinV2.Server
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid syntax language." });
return;
}
}
bool shouldCompress = await Compression.ShouldCompress(body);
if (shouldCompress)
@@ -697,7 +835,7 @@ namespace SharpbinV2.Server
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;
@@ -765,7 +903,7 @@ namespace SharpbinV2.Server
}
}
}
});
}).RequireRateLimiting("general");
app.MapGet("/api/pastes/my", async (HttpContext context) =>
{
var requestdetails = GetRequestDetails(context);
@@ -877,9 +1015,9 @@ namespace SharpbinV2.Server
authorUsername = "Anonymous";
}
context.Response.StatusCode = 200;
await context.Response.WriteAsJsonAsync(new
{
success = true,
await context.Response.WriteAsJsonAsync(new
{
success = true,
paste = new
{
paste.UUID,
@@ -894,9 +1032,9 @@ namespace SharpbinV2.Server
paste.TrueSize,
paste.Views,
paste.Syntax
}
}
});
});
}).RequireRateLimiting("general");
app.MapGet("/api/pastes/{pasteid}", async (HttpContext context) =>
{
var pasteid = context.Request.RouteValues["pasteid"].ToString() ?? null;
@@ -919,7 +1057,7 @@ namespace SharpbinV2.Server
await context.Response.SendFileAsync(paste.FilePath);
}
return;
});
}).RequireRateLimiting("general");
app.MapGet("/api/pastes/{pasteid}/views", async (HttpContext context) =>
{
var requestdetails = GetRequestDetails(context);
@@ -993,13 +1131,13 @@ namespace SharpbinV2.Server
});
}
context.Response.StatusCode = 200;
await context.Response.WriteAsJsonAsync(new { success = true, views, viewcount });
await context.Response.WriteAsJsonAsync(new { success = true, views, viewcount });
}
}
}
});
}).RequireRateLimiting("general");
app.MapGet("/api/users/uuid/{uuid}", async (HttpContext context) =>
{
@@ -1017,7 +1155,7 @@ namespace SharpbinV2.Server
await context.Response.WriteAsJsonAsync(new { success = false, message = "User not found." });
return;
}
context.Response.StatusCode = 200;
await context.Response.WriteAsJsonAsync(new
{
@@ -1032,7 +1170,7 @@ namespace SharpbinV2.Server
user.LastLogin
}
});
});
}).RequireRateLimiting("general");
app.MapGet("/api/users/{username}", async (HttpContext context) =>
{
var username = context.Request.RouteValues["username"].ToString() ?? null;
@@ -1063,7 +1201,7 @@ namespace SharpbinV2.Server
user.LastLogin
}
});
});
}).RequireRateLimiting("general");
app.MapGet("/api/users/{uuid}/pastes", async (HttpContext context) =>
{
var uuid = context.Request.RouteValues["uuid"].ToString() ?? null;
@@ -1145,7 +1283,7 @@ namespace SharpbinV2.Server
}
}
});
}).RequireRateLimiting("general");
app.MapGet("/api/site/info", async (HttpContext context) =>
{
@@ -1155,6 +1293,65 @@ namespace SharpbinV2.Server
MaxFileSize
};
await context.Response.WriteAsJsonAsync(new { success = true, info });
}).RequireRateLimiting("general");
app.MapGet("/admin/{useruuid}/reset-password", async (HttpContext context) =>
{
var requestdetails = GetRequestDetails(context);
var user = await Database.UserFromToken(requestdetails.Token);
if (user == null)
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid token." });
return;
}
if (user.Type != 255)
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, message = "Not authorized." });
return;
}
var useruuid = context.Request.RouteValues["useruuid"].ToString() ?? null;
if (string.IsNullOrEmpty(useruuid))
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid UUID." });
return;
}
var targetuser = await Database.UserFromUUID(useruuid);
if (targetuser == null)
{
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { success = false, message = "User not found." });
return;
}
string uuid = Guid.NewGuid().ToString();
string url = GenerateRandomString(32);
string token = GenerateToken();
using (var connection = new SqliteConnection(MainDatabaseConnection))
{
await connection.OpenAsync();
var expiry = DateTimeOffset.UtcNow.AddHours(1).ToUnixTimeSeconds();
using (var command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO passwordresets (UUID, USERUUID, URL, Token,Created, Expirary) VALUES (@UUID, @USERUUID, @URL, @Token,@Created, @Expirary);";
command.Parameters.AddWithValue("@UUID", uuid);
command.Parameters.AddWithValue("@USERUUID", targetuser.UUID);
command.Parameters.AddWithValue("@URL", url);
command.Parameters.AddWithValue("@Token", token);
command.Parameters.AddWithValue("@Created", DateTimeOffset.UtcNow.ToUnixTimeSeconds());
command.Parameters.AddWithValue("@Expirary", expiry);
await command.ExecuteNonQueryAsync();
}
await connection.CloseAsync();
}
var resetlink = $"{context.Request.Scheme}://{context.Request.Host}/reset-password?uuid={uuid}&url={url}&token={token}";
context.Response.StatusCode = 200;
context.Response.Headers.Add("Content-Type", "application/json");
await context.Response.WriteAsJsonAsync(new { success = true, resetlink, uuid, url, token });
});
@@ -1347,7 +1544,7 @@ namespace SharpbinV2.Server
}
}
/// <summary>