1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 |
- using System;
- using Luticate2.Auth.Business;
- 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.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 token = context.HttpContext.GetLuUserToken();
- var userId = Guid.Empty.ToDbo();
- if (token != null)
- {
- var tokenRes = _luTokensBusiness.GetToken(token);
- if (tokenRes.Status == LuStatus.NotFound)
- {
- LuResult<object>.Error(LuStatus.LoginError, $"unknown token: {token}", "Invalid session").Throw();
- }
- tokenRes.ThrowIfNotSuccess();
- var tokenValid = _luTokensBusiness.IsTokenValid(tokenRes.Data);
- if (!tokenValid)
- {
- LuResult<object>.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)
- {
- }
- }
- }
|