You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

LuLoggedUserMiddleware.cs 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using System;
  2. using Luticate2.Auth.Business;
  3. using Luticate2.Auth.Controllers;
  4. using Luticate2.Auth.Interfaces.Tokens;
  5. using Luticate2.Auth.Interfaces.Users;
  6. using Luticate2.Utils.Dbo.Result;
  7. using Luticate2.Utils.Utils;
  8. using Microsoft.AspNetCore.Mvc.Filters;
  9. namespace Luticate2.Auth.Middlewares
  10. {
  11. public class LuLoggedUserMiddleware : IActionFilter
  12. {
  13. private readonly ILuUsersBusiness _luUsersBusiness;
  14. private readonly ILuTokensBusiness _luTokensBusiness;
  15. public LuLoggedUserMiddleware(ILuUsersBusiness luUsersBusiness, ILuTokensBusiness luTokensBusiness)
  16. {
  17. _luUsersBusiness = luUsersBusiness;
  18. _luTokensBusiness = luTokensBusiness;
  19. }
  20. public void OnActionExecuting(ActionExecutingContext context)
  21. {
  22. var token = context.HttpContext.GetLuUserToken();
  23. var userId = Guid.Empty.ToDbo();
  24. if (token != null)
  25. {
  26. var tokenRes = _luTokensBusiness.GetToken(token);
  27. if (tokenRes.Status == LuStatus.NotFound)
  28. {
  29. LuResult<object>.Error(LuStatus.LoginError, $"unknown token: {token}", "Invalid session").Throw();
  30. }
  31. tokenRes.ThrowIfNotSuccess();
  32. var tokenValid = _luTokensBusiness.IsTokenValid(tokenRes.Data);
  33. if (!tokenValid)
  34. {
  35. LuResult<object>.Error(LuStatus.LoginError, $"invalid token: {token}", "Invalid session").Throw();
  36. }
  37. userId = tokenRes.Data.UserId;
  38. }
  39. var userRes = _luUsersBusiness.GetSingleById(userId).ThrowIfNotSuccess();
  40. context.HttpContext.SetLuLoggedUser(userRes.Data);
  41. }
  42. public void OnActionExecuted(ActionExecutedContext context)
  43. {
  44. }
  45. }
  46. }