2026-10-27 15:31:45 +02:00
|
|
|
using System.Security.Claims;
|
|
|
|
|
using System.Threading.RateLimiting;
|
|
|
|
|
using Microsoft.AspNetCore.Antiforgery;
|
2026-10-27 10:15:05 +02:00
|
|
|
using Microsoft.AspNetCore.Identity;
|
|
|
|
|
using Npgsql;
|
|
|
|
|
using Microsoft.AspNetCore.Localization;
|
|
|
|
|
using Microsoft.AspNetCore.Mvc;
|
|
|
|
|
using Microsoft.AspNetCore.WebUtilities;
|
|
|
|
|
using Microsoft.EntityFrameworkCore;
|
2026-10-27 15:31:45 +02:00
|
|
|
using Microsoft.Extensions.Logging.Console;
|
2026-10-27 10:15:05 +02:00
|
|
|
using StatiKosev.Data;
|
2026-10-27 15:31:45 +02:00
|
|
|
using StatiKosev.Logging;
|
2026-10-27 10:15:05 +02:00
|
|
|
|
|
|
|
|
namespace StatiKosev;
|
|
|
|
|
|
|
|
|
|
public class Program
|
|
|
|
|
{
|
|
|
|
|
public static void Main(string[] arguments)
|
|
|
|
|
{
|
|
|
|
|
var builder = WebApplication.CreateBuilder(arguments);
|
|
|
|
|
var databaseConnectionString = builder.Configuration.GetConnectionString("DefaultConnection");
|
2026-10-27 15:31:45 +02:00
|
|
|
var messageRateLimitSeconds = builder.Configuration.GetValue("MessageRateLimitSeconds", 10);
|
|
|
|
|
|
2026-10-27 10:15:05 +02:00
|
|
|
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>();
|
2026-10-27 10:15:05 +02:00
|
|
|
builder.Services.AddNpgsqlDataSource(databaseConnectionString);
|
|
|
|
|
builder.Services.AddDbContext<AppDbContext>((sp, o) =>
|
|
|
|
|
o.UseNpgsql(sp.GetRequiredService<NpgsqlDataSource>())); // EF shares the same connection pool
|
2026-10-27 15:31:45 +02:00
|
|
|
//builder.Services.AddLogging();
|
2026-10-27 10:15:05 +02:00
|
|
|
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>();
|
|
|
|
|
|
|
|
|
|
builder.Services.AddAuthorizationBuilder()
|
|
|
|
|
.AddPolicy("AdminOnly", p => p.RequireRole("Admin"));
|
2026-10-27 15:31:45 +02:00
|
|
|
//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;
|
|
|
|
|
};
|
2026-10-27 10:15:05 +02:00
|
|
|
|
2026-10-27 15:31:45 +02:00
|
|
|
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>();
|
|
|
|
|
|
2026-10-27 10:15:05 +02:00
|
|
|
Console.WriteLine($"Database connection string: {databaseConnectionString}");
|
|
|
|
|
|
|
|
|
|
var app = builder.Build();
|
|
|
|
|
app.UseAntiforgery();
|
2026-10-28 11:10:46 +02:00
|
|
|
app.UseRateLimiter();
|
2026-10-27 10:15:05 +02:00
|
|
|
|
|
|
|
|
//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 : "/";
|
|
|
|
|
|
|
|
|
|
Console.WriteLine("Local==" + ForceLocalizeUrl(app.Environment.ApplicationName));
|
|
|
|
|
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);
|
|
|
|
|
return Results.LocalRedirect(r.Succeeded ? back : QueryHelpers.AddQueryString(back, "auth", "login-failed"));
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
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)
|
|
|
|
|
return Results.LocalRedirect(QueryHelpers.AddQueryString(back, "auth", "register-failed"));
|
|
|
|
|
await users.AddToRoleAsync(user, "User");
|
|
|
|
|
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();
|
2026-10-27 10:15:05 +02:00
|
|
|
//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()));
|
2026-10-27 15:31:45 +02:00
|
|
|
app.Logger.LogInformation("Configured message rate limit secs==" + messageRateLimitSeconds);
|
|
|
|
|
app.Logger.LogInformation("Application started!");
|
2026-10-27 10:15:05 +02:00
|
|
|
app.Run();
|
|
|
|
|
}
|
|
|
|
|
}
|