using System; using Luticate2.Auth.Controllers; using Luticate2.Auth.Dbo.Users; using Luticate2.Auth.Interfaces.Users; using Luticate2.Utils.Controllers; using Luticate2.Utils.Dbo.Result; using Luticate2.Utils.Utils; using Microsoft.AspNetCore.Mvc.Filters; namespace Luticate2.Auth.Middlewares { public class LuLoggedUserMiddleware : IActionFilter { public const string TokenCookieName = "luticate2-token"; private readonly ILuUsersBusiness _luUsersBusiness; public LuLoggedUserMiddleware(ILuUsersBusiness luUsersBusiness) { _luUsersBusiness = luUsersBusiness; } public void OnActionExecuting(ActionExecutingContext context) { var token = context.HttpContext.Request.Cookies[TokenCookieName]; var userId = Guid.Empty.ToDbo(); if (!string.IsNullOrWhiteSpace(token)) { var tokenRes = _luUsersBusiness.GetToken(token); if (tokenRes.Status == LuStatus.NotFound) { LuResult.Error(LuStatus.LoginError, $"token: {token}", "Invalid session").Throw(); } tokenRes.ThrowIfNotSuccess(); var tokenValid = _luUsersBusiness.IsTokenValid(tokenRes.Data); if (!tokenValid) { LuResult.Error(LuStatus.LoginError, $"token: {token}", "Invalid session").Throw(); } userId = tokenRes.Data.UserId; } var userRes = _luUsersBusiness.GetSingleById(userId).ThrowIfNotSuccess(); context.HttpContext.SetLuLoggedUser(userRes.Data); } public void OnActionExecuted(ActionExecutedContext context) { } } }