Files
StatiKosev/Program.cs
T

169 lines
7.7 KiB
C#
Raw Normal View History

using System.Security.Claims;
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Identity;
using Npgsql;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Console;
using StatiKosev.Data;
using StatiKosev.Logging;
namespace StatiKosev;
public class Program
{
2026-10-28 13:23:35 +02:00
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);
2026-10-28 13:23:35 +02:00
var adminEmail = builder.Configuration["AdminEmail"]; // this account sees the Inbox
builder.Services.AddLocalization(o => o.ResourcesPath = "LanguagesValues");
builder.Services.AddRazorPages();
2026-10-28 11:10:46 +02:00
builder.Services.AddControllers();
builder.Services.AddScoped<StatiKosev.Services.MessageService>();
builder.Services.AddNpgsqlDataSource(databaseConnectionString);
builder.Services.AddDbContext<AppDbContext>((sp, o) =>
o.UseNpgsql(sp.GetRequiredService<NpgsqlDataSource>())); // EF shares the same connection pool
//builder.Services.AddLogging();
builder.Services.AddDefaultIdentity<IdentityUser>(o =>
{
o.SignIn.RequireConfirmedAccount = false; // no email sending configured yet
o.User.RequireUniqueEmail = true;
o.Password.RequiredLength = 8;
o.Password.RequireNonAlphanumeric = false;
})
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<AppDbContext>();
2026-10-28 13:23:35 +02:00
builder.Services.ConfigureApplicationCookie(o =>
{
o.LoginPath = "/Login";
o.AccessDeniedPath = "/";
});
builder.Services.AddAuthorizationBuilder()
.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}");
var app = builder.Build();
2026-10-28 13:23:35 +02:00
await DbSeeder.SeedAsync(app.Services, adminEmail);
app.UseAntiforgery();
2026-10-28 11:10:46 +02:00
app.UseRateLimiter();
//accounts
//safety check if form sends us to the same domain
//if starting with / -> u, if null or else -> "/" redirects to Index
static string ForceLocalizeUrl(string? u) =>
!string.IsNullOrEmpty(u) && u.StartsWith('/') && !u.StartsWith("//") && !u.StartsWith("/\\") ? u : "/";
2026-10-28 13:23:35 +02:00
//failed login/register go back to the login page with the reason and the original returnUrl
static string LoginPage(string auth, string back) =>
QueryHelpers.AddQueryString("/Login", new Dictionary<string, string?> { ["auth"] = auth, ["returnUrl"] = back });
var account = app.MapGroup("/account");
account.MapPost("/login", async ([FromForm] string email, [FromForm] string password,
[FromForm] string? returnUrl, SignInManager<IdentityUser> signIn) =>
{
var r = await signIn.PasswordSignInAsync(email, password, isPersistent: true, lockoutOnFailure: true);
var back = ForceLocalizeUrl(returnUrl);
2026-10-28 13:23:35 +02:00
return Results.LocalRedirect(r.Succeeded ? back : LoginPage("login-failed", back));
});
account.MapPost("/register", async ([FromForm] string email, [FromForm] string password,
[FromForm] string? returnUrl, UserManager<IdentityUser> users, SignInManager<IdentityUser> signIn) =>
{
var back = ForceLocalizeUrl(returnUrl);
var user = new IdentityUser { UserName = email, Email = email };
var res = await users.CreateAsync(user, password);
if (!res.Succeeded)
2026-10-28 13:23:35 +02:00
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);
});
account.MapPost("/logout", async (SignInManager<IdentityUser> signIn) =>
{
await signIn.SignOutAsync();
return Results.LocalRedirect("/");
}).WithMetadata(new RequireAntiforgeryTokenAttribute());
//accounts end
app.UseRequestLocalization(o => o
.SetDefaultCulture("bg")
.AddSupportedCultures("bg", "en")
.AddSupportedUICultures("bg", "en"));
app.UseStaticFiles(); // CSS/JS/images from wwwroot
app.MapRazorPages();
2026-10-28 11:10:46 +02:00
app.MapControllers();
//get version of database the software is configured to work with (appsettings.json)
app.MapGet("/db_version", async (NpgsqlDataSource db) =>
{
await using var cmd = db.CreateCommand("SELECT version()");
var version = await cmd.ExecuteScalarAsync();
Console.WriteLine("db_version api called and returned==" + version);
return version;
});
app.MapGet("/set-language", (string culture, string? returnUrl, HttpContext ctx) =>
{
ctx.Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1), IsEssential = true });
return Results.LocalRedirect(string.IsNullOrEmpty(returnUrl) ? "/" : returnUrl);
});
app.MapStaticAssets();
app.MapGet("/_res", () => string.Join("\n",
typeof(StatiKosev.StringValues).Assembly.GetManifestResourceNames()));
app.Logger.LogInformation("Configured message rate limit secs==" + messageRateLimitSeconds);
app.Logger.LogInformation("Application started!");
app.Run();
}
}