using backend.Application; namespace backend.Middleware; public class AuthenticationMiddleware { private readonly RequestDelegate _next; public AuthenticationMiddleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext context) { if (context.Request.Cookies["session"] == null) { context.Response.Clear(); context.Response.StatusCode = 401; await context.Response.WriteAsync("You are not logged in"); return; } var user = ApplicationState.DbContext!.Users.FirstOrDefault(user => user.SessionToken == context.Request.Cookies["session"]!.ToString()); if (user == null) { context.Response.Clear(); context.Response.StatusCode = 401; await context.Response.WriteAsync("Invalid session token"); return; } await _next(context); } } public class AuthenticationMiddlewareBuilder { public void Configure(IApplicationBuilder app) { app.UseMiddleware(); } }