using System; using Luticate2.Auth.Controllers; using Luticate2.Auth.Interfaces.Tokens; using Luticate2.Auth.Interfaces.Users; using Luticate2.Utils.Dbo.Result; using Luticate2.Utils.Utils; using Microsoft.AspNetCore.Mvc.Controllers; using Microsoft.AspNetCore.Mvc.Filters; namespace Luticate2.Auth.Middlewares { public class LuLoggedUserMiddleware : IActionFilter { private readonly ILuUsersBusiness _luUsersBusiness; private readonly ILuTokensBusiness _luTokensBusiness; public LuLoggedUserMiddleware(ILuUsersBusiness luUsersBusiness, ILuTokensBusiness luTokensBusiness) { _luUsersBusiness = luUsersBusiness; _luTokensBusiness = luTokensBusiness; } public void OnActionExecuting(ActionExecutingContext context) { var actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor; if (actionDescriptor == null) { LuResult.Error(LuStatus.InternalError, $"{nameof(LuLoggedUserMiddleware)}: actionDescriptor == null").Throw(); return; } var isLogin = false; var isLogout = false; if (actionDescriptor.ControllerTypeInfo.AsType() == typeof(LuUsersController)) { if (actionDescriptor.ActionName == nameof(LuUsersController.Login)) { isLogin = true; } else if (actionDescriptor.ActionName == nameof(LuUsersController.Logout)) { isLogout = true; } } var token = context.HttpContext.GetLuUserToken(); var userId = Guid.Empty.ToDbo(); if (token != null && !isLogout && !isLogin)//TODO { var tokenRes = _luTokensBusiness.GetToken(token); if (tokenRes.Status == LuStatus.NotFound) { LuResult.Error(LuStatus.LoginError, $"unknown token: {token}", "Invalid session").Throw(); } tokenRes.ThrowIfNotSuccess(); var tokenValid = _luTokensBusiness.IsTokenValid(tokenRes.Data); if (!tokenValid) { LuResult.Error(LuStatus.LoginError, $"invalid 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) { } } }