using System.Collections.Generic; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using MiniWiki.Data.Sessions; namespace MiniWiki.Web.Auth; public class SessionValidationMiddleware(RequestDelegate next) { public async Task InvokeAsync(HttpContext context, ISessionsRepository sessionsRepository) { var sessionId = context.Request.Cookies["mw_session"]; if (!string.IsNullOrEmpty(sessionId)) { var session = await sessionsRepository.GetAsync(sessionId); if (session is not null) { List claims = [ new(ClaimTypes.NameIdentifier, session.UserId), new(ClaimTypes.Email, session.Email), new("SessionId", session.Id), new("DisplayName", session.DisplayName ?? session.Email), new("is_admin", session.IsAdmin.ToString()) ]; var identity = new ClaimsIdentity(claims, "DatabaseSession"); context.User = new ClaimsPrincipal(identity); } } await next(context); } }