adding messages rate limit, form, controller

This commit is contained in:
2026-10-27 15:31:45 +02:00
parent 35aed79337
commit c5c9d74937
15 changed files with 306 additions and 36 deletions
+35
View File
@@ -0,0 +1,35 @@
using StatiKosev.Services;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using StatiKosev.Data;
using StatiKosev.Logging;
namespace StatiKosev.Controllers;
[Route("messages")]
public class PrivateMessageController(MessageService messagesService, ILogger<PrivateMessageController> logger) : ControllerBase
{
[HttpPost("send")]
[EnableRateLimiting("contact")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Send(SendPrivateMessageRequest req, CancellationToken ct)
{
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
var userAgent = Request.Headers["User-Agent"].ToString();
if (userId == null)
await messagesService.SendAnonymousAsync(req.Body, userAgent);
else
{
var senderUsername = User.FindFirstValue(userId);
if (senderUsername is null)
{
logger.LogWarning("User {UserId} has no name claim", userId);
return Unauthorized();
}
await messagesService.SendAsUserAsync(req.Body, userId, senderUsername, userAgent);
}
return Accepted();
}
}
+1 -1
View File
@@ -7,5 +7,5 @@ namespace StatiKosev.Data;
public class AppDbContext(DbContextOptions<AppDbContext> options) public class AppDbContext(DbContextOptions<AppDbContext> options)
: IdentityDbContext<IdentityUser>(options) : IdentityDbContext<IdentityUser>(options)
{ {
public DbSet<GuestMessage> GuestMessages => Set<GuestMessage>(); public DbSet<PrivateMessage> PrivateMessages => Set<PrivateMessage>();
} }
-14
View File
@@ -1,14 +0,0 @@
using System.ComponentModel.DataAnnotations;
namespace StatiKosev.Data;
public class GuestMessage
{
public int Id { get; set; }
[MaxLength(2000)] public required string Body { get; set; }
public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow;
public bool IsRead { get; set; }
}
public record SendGuestMessageRequest(
[Required, StringLength(2000, MinimumLength = 1)] string Body);
+34
View File
@@ -0,0 +1,34 @@
using System.ComponentModel.DataAnnotations;
using System.Security.Claims;
namespace StatiKosev.Data;
public class PrivateMessage
{
public int Id { get; set; }
bool Anonymous { get; set; }
public string? SenderId { get; set; }
string SenderUsername { get; set; }
[MaxLength(3000)] public string Body { get; set; }
public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow;
public bool IsRead { get; set; }
public PrivateMessage(string body, string userAgent)
{
CreatedAt = DateTime.UtcNow;
SenderUsername = userAgent + "___" + CreatedAt.ToString("dd-MM-yyyy___HH:mm:ss");
Anonymous = true;
SenderId = null;
Body = body;
}
public PrivateMessage(string body, string senderId, string senderUsername, string userAgent)
{
CreatedAt = DateTime.UtcNow;
SenderId = senderId;
SenderUsername = senderUsername;
Anonymous = false;
Body = body;
}
}
public record SendPrivateMessageRequest(
[Required, StringLength(2000, MinimumLength = 1)] string Body, bool Anonymous);
-15
View File
@@ -1,15 +0,0 @@
using System.ComponentModel.DataAnnotations;
namespace StatiKosev.Data;
public class UserMessage
{
public int Id { get; set; }
[MaxLength(2000)] public required string Body { get; set; }
public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow;
public bool IsRead { get; set; }
}
public record SendUserMessageRequest(
[Required, StringLength(2000, MinimumLength = 1)] string Body, string Username);
+3
View File
@@ -18,4 +18,7 @@
<data name="Title" xml:space="preserve"> <data name="Title" xml:space="preserve">
<value>Stati Kosev</value> <value>Stati Kosev</value>
</data> </data>
<data name="SendMeAMessage" xml:space="preserve">
<value>Send me a DM.</value>
</data>
</root> </root>
+24
View File
@@ -21,4 +21,28 @@
<data name="Gallery" xml:space="preserve"> <data name="Gallery" xml:space="preserve">
<value>Галерия</value> <value>Галерия</value>
</data> </data>
<data name="SendMeAMessage" xml:space="preserve">
<value>Пишете ми.</value>
</data>
<data name="MessageForm" xml:space="preserve">
<value>Форма за съобщение</value>
</data>
<data name="SendingAs" xml:space="preserve">
<value>Изпрати като </value>
</data>
<data name="SendingAnon" xml:space="preserve">
<value>Изпратете анонимно</value>
</data>
<data name="YouAreNotLoggedIn" xml:space="preserve">
<value>Не Сте се логнали</value>
</data>
<data name="CancelMessaging" xml:space="preserve">
<value>Откажи съобщението</value>
</data>
<data name="SendMessage" xml:space="preserve">
<value>Изпрати</value>
</data>
<data name="CancelSend" xml:space="preserve">
<value>Откажи изпращането</value>
</data>
</root> </root>
+28
View File
@@ -0,0 +1,28 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Logging.Console;
namespace StatiKosev.Logging;
public sealed class Logger() : ConsoleFormatter("color")
{
public override void Write<TState>(in LogEntry<TState> entry,
IExternalScopeProvider? scopeProvider, TextWriter writer)
{
var message = entry.Formatter(entry.State, entry.Exception);
if (message is null) return;
var color = entry.LogLevel switch
{
LogLevel.Information => "\e[32m", // green
LogLevel.Warning => "\e[33m", // yellow
LogLevel.Error or LogLevel.Critical => "\e[31m", // red
LogLevel.Debug or LogLevel.Trace => "\e[90m", // gray
_ => ""
};
var reset = color.Length > 0 ? "\e[0m" : "";
writer.WriteLine($"{color}{DateTime.Now:HH:mm:ss} {entry.LogLevel,-11} {entry.Category}: {message}{reset}");
if (entry.Exception is not null)
writer.WriteLine($"{color}{entry.Exception}{reset}");
}
}
+11 -1
View File
@@ -10,5 +10,15 @@
<div> <div>
<img src="~/images/profile.jpg" alt="@StringValues["PhotoAlt"]" width="600" asp-append-version="true" /> <img src="~/images/profile.jpg" alt="@StringValues["PhotoAlt"]" width="600" asp-append-version="true" />
</div> </div>
<div id="description"></div> <div id="description">@StringValues["Description"]</div>
<div id="message-me-div">
<button id="message-me-btn" type="button" popovertarget="message-me" popover popovertargetaction="show">@StringValues["SendMeAMessage"]
</button>
<div id="message-me" popover>
<partial name="Shared/_MessageMe" />
</div>
<button id="cancel-message-btn" type="button" popovertarget="message-me" popover popovertargetaction="hide">@StringValues["CancelMessaging"]
</button>
</div>
</div> </div>
+2 -1
View File
@@ -7,6 +7,7 @@
<html lang="@System.Globalization.CultureInfo.CurrentUICulture.TwoLetterISOLanguageName"> <html lang="@System.Globalization.CultureInfo.CurrentUICulture.TwoLetterISOLanguageName">
<head> <head>
<link rel="stylesheet" href="~/styles/site.css" asp-append-version="true"/>
<nav class="main-nav" aria-label="@StringValues["Navigation"]"> <nav class="main-nav" aria-label="@StringValues["Navigation"]">
<a asp-page="/Index" class="@Active("/")">@StringValues["Home"]</a> <a asp-page="/Index" class="@Active("/")">@StringValues["Home"]</a>
<a asp-page="/Gallery" class="@Active("/Gallery")">@StringValues["Gallery"]</a> <a asp-page="/Gallery" class="@Active("/Gallery")">@StringValues["Gallery"]</a>
@@ -15,7 +16,7 @@
<meta charset="utf-8"/> <meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/> <meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>@StringValues["Title"]</title> <title>@StringValues["Title"]</title>
<link rel="stylesheet" href="~/styles/site.css" asp-append-version="true"/>
<a href="/set-language?culture=bg&returnUrl=@Context.Request.Path">Български</a> <a href="/set-language?culture=bg&returnUrl=@Context.Request.Path">Български</a>
<a href="/set-language?culture=en&returnUrl=@Context.Request.Path">English</a> <a href="/set-language?culture=en&returnUrl=@Context.Request.Path">English</a>
+27
View File
@@ -0,0 +1,27 @@
@* HTML partial Pages/Shared/_MessageMe.cshtml *@
@{
var loggedIn = User.Identity?.IsAuthenticated == true;
}
<form id="message-me-form">
@Html.AntiForgeryToken()
<h2>@StringValues["MessageForm"]</h2>
@if (loggedIn)
{
<p>@StringValues["SendingAs"] <strong>@User.Identity!.Name</strong></p>
<label><input type="checkbox" name="anonymous" />@StringValues["SendingAnon"]</label>
}
else
{
<p>@StringValues["YouAreNotLoggedIn"]</p>
}
<textarea name="body" required maxlength="2000" rows="6" placeholder="Your message…"></textarea>
<p class="message-me-status" role="status" aria-live="polite"></p>
<div class="message-me-actions">
<button type="button" class="message-me-cancel" id="message-me-close">@StringValues["CancelSend"]</button>
<button type="submit" class="message-me-btn">@StringValues["SendMessage"]</button>
</div>
</form>
+46 -2
View File
@@ -1,11 +1,15 @@
using Microsoft.AspNetCore.Antiforgery; using System.Security.Claims;
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity;
using Npgsql; using Npgsql;
using Microsoft.AspNetCore.Localization; using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.WebUtilities; using Microsoft.AspNetCore.WebUtilities;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Console;
using StatiKosev.Data; using StatiKosev.Data;
using StatiKosev.Logging;
namespace StatiKosev; namespace StatiKosev;
@@ -15,12 +19,14 @@ public class Program
{ {
var builder = WebApplication.CreateBuilder(arguments); var builder = WebApplication.CreateBuilder(arguments);
var databaseConnectionString = builder.Configuration.GetConnectionString("DefaultConnection"); var databaseConnectionString = builder.Configuration.GetConnectionString("DefaultConnection");
var messageRateLimitSeconds = builder.Configuration.GetValue("MessageRateLimitSeconds", 10);
builder.Services.AddLocalization(o => o.ResourcesPath = "LanguagesValues"); builder.Services.AddLocalization(o => o.ResourcesPath = "LanguagesValues");
builder.Services.AddRazorPages(); builder.Services.AddRazorPages();
builder.Services.AddNpgsqlDataSource(databaseConnectionString); builder.Services.AddNpgsqlDataSource(databaseConnectionString);
builder.Services.AddDbContext<AppDbContext>((sp, o) => builder.Services.AddDbContext<AppDbContext>((sp, o) =>
o.UseNpgsql(sp.GetRequiredService<NpgsqlDataSource>())); // EF shares the same connection pool o.UseNpgsql(sp.GetRequiredService<NpgsqlDataSource>())); // EF shares the same connection pool
//builder.Services.AddLogging();
builder.Services.AddDefaultIdentity<IdentityUser>(o => builder.Services.AddDefaultIdentity<IdentityUser>(o =>
{ {
o.SignIn.RequireConfirmedAccount = false; // no email sending configured yet o.SignIn.RequireConfirmedAccount = false; // no email sending configured yet
@@ -33,6 +39,42 @@ public class Program
builder.Services.AddAuthorizationBuilder() builder.Services.AddAuthorizationBuilder()
.AddPolicy("AdminOnly", p => p.RequireRole("Admin")); .AddPolicy("AdminOnly", p => p.RequireRole("Admin"));
//rate limiting for messages
builder.Services.AddRateLimiter(o =>
{
o.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
o.OnRejected = (ctx, _) =>
{
var http = ctx.HttpContext;
if (http.Request.HasFormContentType)
{
var referer = http.Request.Headers.Referer.ToString();
var path = Uri.TryCreate(referer, UriKind.Absolute, out var uri)
&& uri.Host == http.Request.Host.Host ? uri.AbsolutePath : "/";
http.Response.Redirect(path + "?wait=1");
}
return ValueTask.CompletedTask;
};
o.AddPolicy("contact", ctx => // ← the policy [EnableRateLimiting("contact")] uses
{
var userId = ctx.User.FindFirstValue(ClaimTypes.NameIdentifier);
var key = userId is not null ? "user:" + userId : "ip:" + ctx.Connection.RemoteIpAddress;
return RateLimitPartition.GetFixedWindowLimiter(key, _ => new FixedWindowRateLimiterOptions
{
PermitLimit = 1,
Window = TimeSpan.FromSeconds(messageRateLimitSeconds),
QueueLimit = 0
});
});
});
builder.Logging.ClearProviders();
builder.Logging.AddConsole(o => o.FormatterName = "color")
.AddConsoleFormatter<Logger, ConsoleFormatterOptions>();
Console.WriteLine($"Database connection string: {databaseConnectionString}"); Console.WriteLine($"Database connection string: {databaseConnectionString}");
@@ -104,6 +146,8 @@ public class Program
app.MapStaticAssets(); app.MapStaticAssets();
app.MapGet("/_res", () => string.Join("\n", app.MapGet("/_res", () => string.Join("\n",
typeof(StatiKosev.StringValues).Assembly.GetManifestResourceNames())); typeof(StatiKosev.StringValues).Assembly.GetManifestResourceNames()));
app.Logger.LogInformation("Configured message rate limit secs==" + messageRateLimitSeconds);
app.Logger.LogInformation("Application started!");
app.Run(); app.Run();
} }
} }
+34
View File
@@ -0,0 +1,34 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.EntityFrameworkCore;
using StatiKosev.Data;
namespace StatiKosev.Services;
public class MessageService(AppDbContext db)
{
public async Task SendAnonymousAsync(string body, string userAgent)
{
db.PrivateMessages.Add(new PrivateMessage(body, userAgent));
await db.SaveChangesAsync();
}
public async Task SendAsUserAsync(string body, string userId, string senderUsername, string userAgent)
{
db.PrivateMessages.Add(new PrivateMessage(body, userId, senderUsername, userAgent));
await db.SaveChangesAsync();
}
public Task<List<PrivateMessage>> GetInboxAsync(bool unreadOnly = false) =>
db.PrivateMessages
.Where(m => !unreadOnly || !m.IsRead)
.OrderByDescending(m => m.CreatedAt)
.AsNoTracking()
.ToListAsync();
public Task<int> MarkReadAsync(int id) =>
db.PrivateMessages.Where(m => m.Id == id)
.ExecuteUpdateAsync(s => s.SetProperty(m => m.IsRead, true));
}
+2 -1
View File
@@ -2,5 +2,6 @@
"ConnectionStrings": { "ConnectionStrings": {
"DefaultConnection": "Host=192.168.1.1;Database=dotnet_portfolio;Username=dotnet_portfolio_usr;Password=z50QhAN3v8P7Eqmj0ptPppr3jtC4WkwA" "DefaultConnection": "Host=192.168.1.1;Database=dotnet_portfolio;Username=dotnet_portfolio_usr;Password=z50QhAN3v8P7Eqmj0ptPppr3jtC4WkwA"
}, },
"Logging": { "LogLevel": { "Default": "Information" } } "Logging": { "LogLevel": { "Default": "Information" } },
"MessageRateLimitSeconds": 30
} }
+58
View File
@@ -1,3 +1,61 @@
html, body{ html, body{
background-color: lightgreen; background-color: lightgreen;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 100vh;
}
#message-me-btn {
--btn-bg: #2563eb;
--btn-bg-hover: #1d4ed8;
--btn-text: #fff;
display: inline-flex;
align-items: center;
gap: 0.5rem;
padding: 0.7rem 1.4rem;
border: none;
border-radius: 999px;
background: var(--btn-bg);
color: var(--btn-text);
font: 600 1rem/1.2 system-ui, sans-serif;
cursor: pointer;
box-shadow: 0 2px 8px rgb(37 99 235 / 0.35);
transition: background-color 0.2s ease, transform 0.15s ease, box-shadow 0.2s ease;
}
#message-me-btn:hover {
background: var(--btn-bg-hover);
transform: translateY(-1px);
box-shadow: 0 4px 14px rgb(37 99 235 / 0.45);
}
#message-me-btn:active {
transform: translateY(0) scale(0.98);
}
#message-me-btn:focus-visible {
outline: 3px solid rgb(37 99 235 / 0.5);
outline-offset: 3px;
}
#message-me-btn:disabled {
background: #94a3b8;
box-shadow: none;
transform: none;
cursor: not-allowed;
}
@media (prefers-color-scheme: dark) {
#message-me-btn {
--btn-bg: #3b82f6;
--btn-bg-hover: #60a5fa;
--btn-text: #0b1220;
}
}
@media (prefers-reduced-motion: reduce) {
#message-me-btn { transition: none; }
} }