checkpoint

This commit is contained in:
2026-10-28 14:22:27 +02:00
parent 33dad8ca5a
commit bd22fa86b7
11 changed files with 161 additions and 52 deletions
+41 -2
View File
@@ -1,4 +1,7 @@
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
@@ -12,6 +15,7 @@ namespace StatiKosev.Controllers;
public class PrivateMessageController(
MessageService messagesService,
IStringLocalizer<StringValues> strings,
IConfiguration config,
ILogger<PrivateMessageController> logger) : Controller
{
//form post from _MessageMe, redirects back to the page it came from
@@ -45,8 +49,43 @@ public class PrivateMessageController(
return LocalRedirect(back);
}
//JSON for the Inbox page (AJAX)
[HttpGet("")]
//password form on the /Inbox page; the admin has no account, only AdminPassword in appsettings.json
[HttpPost("login")]
[EnableRateLimiting("admin-login")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login([FromForm] string? password)
{
var adminPassword = config["AdminPassword"];
//empty AdminPassword = nobody gets in; hashing both sides gives a constant-time compare of equal-length values
var ok = !string.IsNullOrEmpty(adminPassword) && !string.IsNullOrEmpty(password) &&
CryptographicOperations.FixedTimeEquals(
SHA256.HashData(Encoding.UTF8.GetBytes(password)),
SHA256.HashData(Encoding.UTF8.GetBytes(adminPassword)));
if (!ok)
{
logger.LogWarning("Failed admin login from {Ip}", HttpContext.Connection.RemoteIpAddress);
TempData["Status"] = strings["AdminPasswordWrong"].Value;
TempData["StatusType"] = "error";
return LocalRedirect("/Inbox");
}
var admin = new ClaimsPrincipal(new ClaimsIdentity(
[new Claim(ClaimTypes.Name, "admin"), new Claim(ClaimTypes.Role, "Admin")], Program.AdminScheme));
await HttpContext.SignInAsync(Program.AdminScheme, admin);
return LocalRedirect("/Inbox");
}
[HttpPost("logout")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(Program.AdminScheme);
return LocalRedirect("/");
}
//JSON for the /Inbox page (AJAX)
[HttpGet("list")]
[Authorize(Policy = "AdminOnly")]
public async Task<IActionResult> Inbox(bool unreadOnly = false) =>
Ok(await messagesService.GetInboxAsync(unreadOnly));
+4 -15
View File
@@ -6,27 +6,16 @@ namespace StatiKosev.Data;
public static class DbSeeder
{
public const string UserRole = "User";
public const string AdminRole = "Admin";
//applies pending migrations, creates the roles and makes the configured AdminEmail account an admin
public static async Task SeedAsync(IServiceProvider services, string? adminEmail)
//applies pending migrations and creates the role every registered visitor gets
public static async Task SeedAsync(IServiceProvider services)
{
using var scope = services.CreateScope();
var sp = scope.ServiceProvider;
await sp.GetRequiredService<AppDbContext>().Database.MigrateAsync();
var roles = sp.GetRequiredService<RoleManager<IdentityRole>>();
foreach (var role in new[] { UserRole, AdminRole })
if (!await roles.RoleExistsAsync(role))
await roles.CreateAsync(new IdentityRole(role));
if (string.IsNullOrWhiteSpace(adminEmail)) return;
var users = sp.GetRequiredService<UserManager<IdentityUser>>();
var admin = await users.FindByEmailAsync(adminEmail);
if (admin is not null && !await users.IsInRoleAsync(admin, AdminRole))
await users.AddToRoleAsync(admin, AdminRole);
if (!await roles.RoleExistsAsync(UserRole))
await roles.CreateAsync(new IdentityRole(UserRole));
}
public static bool IsAdminEmail(string? email, string? adminEmail) =>
!string.IsNullOrWhiteSpace(adminEmail) && string.Equals(email, adminEmail, StringComparison.OrdinalIgnoreCase);
}
+13 -1
View File
@@ -91,7 +91,7 @@
<value>The message must be between 1 and 2000 characters.</value>
</data>
<data name="TooManyMessages" xml:space="preserve">
<value>Please wait a moment before sending another message.</value>
<value>Too many attempts. Please wait a moment and try again.</value>
</data>
<data name="Messages" xml:space="preserve">
<value>Messages</value>
@@ -138,4 +138,16 @@
<data name="RegisterFailed" xml:space="preserve">
<value>Registration failed. The email may already be taken, or the password is too weak.</value>
</data>
<data name="AdminPassword" xml:space="preserve">
<value>Admin password</value>
</data>
<data name="AdminLogin" xml:space="preserve">
<value>Enter</value>
</data>
<data name="AdminPasswordWrong" xml:space="preserve">
<value>Wrong password.</value>
</data>
<data name="AdminLogout" xml:space="preserve">
<value>Log out</value>
</data>
</root>
+13 -1
View File
@@ -91,7 +91,7 @@
<value>Съобщението трябва да е между 1 и 2000 символа.</value>
</data>
<data name="TooManyMessages" xml:space="preserve">
<value>Изчакайте малко, преди да изпратите следващо съобщение.</value>
<value>Твърде много опити. Изчакайте малко и опитайте отново.</value>
</data>
<data name="Messages" xml:space="preserve">
<value>Съобщения</value>
@@ -138,4 +138,16 @@
<data name="RegisterFailed" xml:space="preserve">
<value>Регистрацията не бе успешна. Имейлът може вече да е зает или паролата е твърде слаба.</value>
</data>
<data name="AdminPassword" xml:space="preserve">
<value>Администраторска парола</value>
</data>
<data name="AdminLogin" xml:space="preserve">
<value>Влез</value>
</data>
<data name="AdminPasswordWrong" xml:space="preserve">
<value>Грешна парола.</value>
</data>
<data name="AdminLogout" xml:space="preserve">
<value>Изход</value>
</data>
</root>
+38 -16
View File
@@ -5,26 +5,48 @@
ViewData["Title"] = StringValues["Messages"];
}
@section Head {
<link rel="stylesheet" href="~/styles/account.css" asp-append-version="true"/>
<link rel="stylesheet" href="~/styles/inbox.css" asp-append-version="true"/>
}
@* messages are loaded as JSON from PrivateMessageController by inbox.js *@
<section class="inbox"
data-api="/messages"
data-token="@Antiforgery.GetAndStoreTokens(HttpContext).RequestToken"
data-anonymous="@StringValues["Anonymous"]"
data-mark-read="@StringValues["MarkRead"]"
data-read="@StringValues["Read"]"
data-empty="@StringValues["NoMessages"]"
data-failed="@StringValues["LoadFailed"]">
<header class="inbox-header">
@if (!Model.IsAdmin)
{
@* no account: the admin password is checked by PrivateMessageController.Login *@
<form method="post" asp-controller="PrivateMessage" asp-action="Login" class="auth-card" data-once>
<h1>@StringValues["Messages"]</h1>
<label><input type="checkbox" class="inbox-unread-only"/> @StringValues["UnreadOnly"]</label>
</header>
<p class="inbox-status" role="status" aria-live="polite">@StringValues["Loading"]</p>
<ol class="inbox-list"></ol>
</section>
<label>@StringValues["AdminPassword"]
<input type="password" name="password" required autocomplete="current-password" autofocus/>
</label>
<button type="submit">@StringValues["AdminLogin"]</button>
</form>
}
else
{
@* messages are loaded as JSON from PrivateMessageController by inbox.js *@
<section class="inbox"
data-list="/messages/list"
data-base="/messages"
data-token="@Antiforgery.GetAndStoreTokens(HttpContext).RequestToken"
data-anonymous="@StringValues["Anonymous"]"
data-mark-read="@StringValues["MarkRead"]"
data-read="@StringValues["Read"]"
data-empty="@StringValues["NoMessages"]"
data-failed="@StringValues["LoadFailed"]">
<header class="inbox-header">
<h1>@StringValues["Messages"]</h1>
<label><input type="checkbox" class="inbox-unread-only"/> @StringValues["UnreadOnly"]</label>
<form method="post" asp-controller="PrivateMessage" asp-action="Logout" class="inbox-logout">
<button type="submit">@StringValues["AdminLogout"]</button>
</form>
</header>
<p class="inbox-status" role="status" aria-live="polite">@StringValues["Loading"]</p>
<ol class="inbox-list"></ol>
</section>
}
@section Scripts {
<script src="~/scripts/inbox.js" asp-append-version="true"></script>
@if (Model.IsAdmin)
{
<script src="~/scripts/inbox.js" asp-append-version="true"></script>
}
}
+6 -3
View File
@@ -1,12 +1,15 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace StatiKosev.Pages;
[Authorize(Policy = "AdminOnly")]
//open to everyone: shows the admin password form, or the inbox once the admin cookie is set
public class InboxModel : PageModel
{
public void OnGet()
public bool IsAdmin { get; private set; }
public async Task OnGetAsync()
{
IsAdmin = (await HttpContext.AuthenticateAsync(Program.AdminScheme)).Succeeded;
}
}
-4
View File
@@ -32,10 +32,6 @@
<nav class="main-nav" aria-label="@StringValues["Navigation"]">
<a asp-page="/Index" class="@Active("/")" aria-current="@Current("/")">@StringValues["Home"]</a>
<a asp-page="/Gallery" class="@Active("/Gallery")" aria-current="@Current("/Gallery")">@StringValues["Gallery"]</a>
@if (User.IsInRole("Admin"))
{
<a asp-page="/Inbox" class="@Active("/Inbox")" aria-current="@Current("/Inbox")">@StringValues["Messages"]</a>
}
</nav>
<div class="header-end">
@if (loggedIn)
+22 -5
View File
@@ -15,12 +15,13 @@ namespace StatiKosev;
public class Program
{
public const string AdminScheme = "Admin";
public static async Task Main(string[] arguments)
{
var builder = WebApplication.CreateBuilder(arguments);
var databaseConnectionString = builder.Configuration.GetConnectionString("DefaultConnection");
var messageRateLimitSeconds = builder.Configuration.GetValue("MessageRateLimitSeconds", 10);
var adminEmail = builder.Configuration["AdminEmail"]; // this account sees the Inbox
builder.Services.AddLocalization(o => o.ResourcesPath = "LanguagesValues");
builder.Services.AddRazorPages();
@@ -44,9 +45,18 @@ public class Program
o.LoginPath = "/Login";
o.AccessDeniedPath = "/";
});
//the admin has no account: the AdminPassword from appsettings.json, entered on /Inbox, signs this separate cookie in
builder.Services.AddAuthentication().AddCookie(AdminScheme, o =>
{
o.Cookie.Name = ".StatiKosev.Admin";
o.LoginPath = "/Inbox";
o.AccessDeniedPath = "/Inbox";
o.ExpireTimeSpan = TimeSpan.FromHours(8);
o.SlidingExpiration = true;
});
builder.Services.AddAuthorizationBuilder()
.AddPolicy("AdminOnly", p => p.RequireRole("Admin"));
.AddPolicy("AdminOnly", p => p.AddAuthenticationSchemes(AdminScheme).RequireRole("Admin"));
//rate limiting for messages
builder.Services.AddRateLimiter(o =>
{
@@ -65,6 +75,15 @@ public class Program
return ValueTask.CompletedTask;
};
//password guessing on /Inbox: 5 tries per 15 minutes per IP
o.AddPolicy("admin-login", ctx =>
RateLimitPartition.GetFixedWindowLimiter("ip:" + ctx.Connection.RemoteIpAddress, _ => new FixedWindowRateLimiterOptions
{
PermitLimit = 5,
Window = TimeSpan.FromMinutes(15),
QueueLimit = 0
}));
o.AddPolicy("contact", ctx => // ← the policy [EnableRateLimiting("contact")] uses
{
var userId = ctx.User.FindFirstValue(ClaimTypes.NameIdentifier);
@@ -87,7 +106,7 @@ public class Program
Console.WriteLine($"Database connection string: {databaseConnectionString}");
var app = builder.Build();
await DbSeeder.SeedAsync(app.Services, adminEmail);
await DbSeeder.SeedAsync(app.Services);
app.UseAntiforgery();
app.UseRateLimiter();
@@ -120,8 +139,6 @@ public class Program
if (!res.Succeeded)
return Results.LocalRedirect(LoginPage("register-failed", back));
await users.AddToRoleAsync(user, DbSeeder.UserRole);
if (DbSeeder.IsAdminEmail(email, adminEmail))
await users.AddToRoleAsync(user, DbSeeder.AdminRole);
await signIn.SignInAsync(user, isPersistent: true);
return Results.LocalRedirect(back);
});
+1 -1
View File
@@ -4,5 +4,5 @@
},
"Logging": { "LogLevel": { "Default": "Information" } },
"MessageRateLimitSeconds": 30,
"AdminEmail": ""
"AdminPassword": "GFiMdUgkpJJGlZlUxayDY842Yml89G6s"
}
+3 -3
View File
@@ -1,4 +1,4 @@
// Inbox: loads messages as JSON (GET /messages) and marks them read (POST /messages/{id}/read).
// Inbox: loads messages as JSON (GET /messages/list) and marks them read (POST /messages/{id}/read).
const inbox = document.querySelector('.inbox');
const list = inbox.querySelector('.inbox-list');
const status = inbox.querySelector('.inbox-status');
@@ -8,7 +8,7 @@ const dateFormat = new Intl.DateTimeFormat(document.documentElement.lang, { date
async function load() {
try {
const res = await fetch(`${t.api}?unreadOnly=${unreadOnly.checked}`, { headers: { Accept: 'application/json' } });
const res = await fetch(`${t.list}?unreadOnly=${unreadOnly.checked}`, { headers: { Accept: 'application/json' } });
if (!res.ok || res.redirected) throw new Error(res.status);
render(await res.json());
} catch {
@@ -65,7 +65,7 @@ function markReadButton(id, li) {
button.textContent = t.markRead;
button.addEventListener('click', async () => {
button.disabled = true;
const res = await fetch(`${t.api}/${id}/read`, {
const res = await fetch(`${t.base}/${id}/read`, {
method: 'POST',
headers: { RequestVerificationToken: t.token }
});
+19
View File
@@ -22,6 +22,25 @@
.inbox-header h1 { margin: 0; }
.inbox-logout { margin: 0 0 0 auto; }
.inbox-logout button {
padding: 0.45rem 0.9rem;
border: 1px solid var(--border);
border-radius: 999px;
background: transparent;
color: var(--muted);
font: 600 0.9rem/1.2 system-ui, sans-serif;
cursor: pointer;
}
.inbox-logout button:hover { color: var(--text); }
.inbox-logout button:focus-visible {
outline: 3px solid rgb(37 99 235 / 0.5);
outline-offset: 2px;
}
.inbox-header label {
display: inline-flex;
align-items: center;