diff --git a/Controllers/PrivateMessageController.cs b/Controllers/PrivateMessageController.cs index c1f77ec..1383e82 100644 --- a/Controllers/PrivateMessageController.cs +++ b/Controllers/PrivateMessageController.cs @@ -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 strings, + IConfiguration config, ILogger 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 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 Logout() + { + await HttpContext.SignOutAsync(Program.AdminScheme); + return LocalRedirect("/"); + } + + //JSON for the /Inbox page (AJAX) + [HttpGet("list")] [Authorize(Policy = "AdminOnly")] public async Task Inbox(bool unreadOnly = false) => Ok(await messagesService.GetInboxAsync(unreadOnly)); diff --git a/Data/DbSeeder.cs b/Data/DbSeeder.cs index a16bb86..41c270a 100644 --- a/Data/DbSeeder.cs +++ b/Data/DbSeeder.cs @@ -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().Database.MigrateAsync(); var roles = sp.GetRequiredService>(); - 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>(); - 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); } diff --git a/LanguagesValues/StringValues.en.resx b/LanguagesValues/StringValues.en.resx index a7263b7..299f07a 100644 --- a/LanguagesValues/StringValues.en.resx +++ b/LanguagesValues/StringValues.en.resx @@ -91,7 +91,7 @@ The message must be between 1 and 2000 characters. - Please wait a moment before sending another message. + Too many attempts. Please wait a moment and try again. Messages @@ -138,4 +138,16 @@ Registration failed. The email may already be taken, or the password is too weak. + + Admin password + + + Enter + + + Wrong password. + + + Log out + \ No newline at end of file diff --git a/LanguagesValues/StringValues.resx b/LanguagesValues/StringValues.resx index a0b6b49..9d39937 100644 --- a/LanguagesValues/StringValues.resx +++ b/LanguagesValues/StringValues.resx @@ -91,7 +91,7 @@ Съобщението трябва да е между 1 и 2000 символа. - Изчакайте малко, преди да изпратите следващо съобщение. + Твърде много опити. Изчакайте малко и опитайте отново. Съобщения @@ -138,4 +138,16 @@ Регистрацията не бе успешна. Имейлът може вече да е зает или паролата е твърде слаба. + + Администраторска парола + + + Влез + + + Грешна парола. + + + Изход + \ No newline at end of file diff --git a/Pages/Inbox.cshtml b/Pages/Inbox.cshtml index 67b8b9b..c6cb369 100644 --- a/Pages/Inbox.cshtml +++ b/Pages/Inbox.cshtml @@ -5,26 +5,48 @@ ViewData["Title"] = StringValues["Messages"]; } @section Head { + } -@* messages are loaded as JSON from PrivateMessageController by inbox.js *@ -
-
+@if (!Model.IsAdmin) +{ + @* no account: the admin password is checked by PrivateMessageController.Login *@ +

@StringValues["Messages"]

- -
-

@StringValues["Loading"]

-
    -
    + + + +} +else +{ + @* messages are loaded as JSON from PrivateMessageController by inbox.js *@ +
    +
    +

    @StringValues["Messages"]

    + +
    + +
    +
    +

    @StringValues["Loading"]

    +
      +
      +} @section Scripts { - + @if (Model.IsAdmin) + { + + } } diff --git a/Pages/Inbox.cshtml.cs b/Pages/Inbox.cshtml.cs index 26969ce..9bb9dd5 100644 --- a/Pages/Inbox.cshtml.cs +++ b/Pages/Inbox.cshtml.cs @@ -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; } } diff --git a/Pages/Shared/_Layout.cshtml b/Pages/Shared/_Layout.cshtml index ab85ff6..d9db94f 100644 --- a/Pages/Shared/_Layout.cshtml +++ b/Pages/Shared/_Layout.cshtml @@ -32,10 +32,6 @@
      @if (loggedIn) diff --git a/Program.cs b/Program.cs index c62d2f5..dc9bb07 100644 --- a/Program.cs +++ b/Program.cs @@ -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); }); @@ -166,4 +183,4 @@ public class Program app.Logger.LogInformation("Application started!"); app.Run(); } -} \ No newline at end of file +} diff --git a/appsettings.json b/appsettings.json index a41ab34..01b3884 100644 --- a/appsettings.json +++ b/appsettings.json @@ -4,5 +4,5 @@ }, "Logging": { "LogLevel": { "Default": "Information" } }, "MessageRateLimitSeconds": 30, - "AdminEmail": "" + "AdminPassword": "GFiMdUgkpJJGlZlUxayDY842Yml89G6s" } \ No newline at end of file diff --git a/wwwroot/scripts/inbox.js b/wwwroot/scripts/inbox.js index 8f3ac5e..84df90c 100644 --- a/wwwroot/scripts/inbox.js +++ b/wwwroot/scripts/inbox.js @@ -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 } }); diff --git a/wwwroot/styles/inbox.css b/wwwroot/styles/inbox.css index af79bf1..65df860 100644 --- a/wwwroot/styles/inbox.css +++ b/wwwroot/styles/inbox.css @@ -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;