From ced67bfe4328f83b87fbed5ee0fdc0c7e15b63d8 Mon Sep 17 00:00:00 2001 From: ReiMerc Date: Tue, 19 Dec 2023 00:49:00 +0100 Subject: [PATCH] WIP list children --- backend/Controllers/UserController.cs | 14 ++++++++ backend/Middleware/ParentMiddleware.cs | 49 ++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 backend/Middleware/ParentMiddleware.cs diff --git a/backend/Controllers/UserController.cs b/backend/Controllers/UserController.cs index 55caee1..1f8cc19 100644 --- a/backend/Controllers/UserController.cs +++ b/backend/Controllers/UserController.cs @@ -125,4 +125,18 @@ public class UserController : ControllerBase return new JsonResult(data); } + + [HttpGet("Children")] + [MiddlewareFilter(typeof(ParentMiddlewareBuilder))] + public IActionResult ListChildren() + { + var users = ApplicationState.DbContext!.Users + .Where(user => !user.IsParent) + .Select(user => new { + username => user.Username, + dispenses = user.Dispenses, + }); + + return new JsonResult(users); + } } diff --git a/backend/Middleware/ParentMiddleware.cs b/backend/Middleware/ParentMiddleware.cs new file mode 100644 index 0000000..0f42a7c --- /dev/null +++ b/backend/Middleware/ParentMiddleware.cs @@ -0,0 +1,49 @@ +using backend.Application; + +namespace backend.Middleware; + +public class ParentMiddleware +{ + private readonly RequestDelegate _next; + + public ParentMiddleware(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; + } + + if (!user.IsParent) { + context.Response.Clear(); + context.Response.StatusCode = 403; + await context.Response.WriteAsync("You are not a parent"); + return; + } + + await _next(context); + } +} + +public class ParentMiddlewareBuilder +{ + public void Configure(IApplicationBuilder app) + { + app.UseMiddleware(); + } +} +