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.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using System;
  2. using Luticate2.Auth.Controllers;
  3. using Luticate2.Auth.Dbo.Users;
  4. using Luticate2.Auth.Interfaces.Users;
  5. using Luticate2.Utils.Controllers;
  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. public const string TokenCookieName = "luticate2-token";
  14. private readonly ILuUsersBusiness _luUsersBusiness;
  15. public LuLoggedUserMiddleware(ILuUsersBusiness luUsersBusiness)
  16. {
  17. _luUsersBusiness = luUsersBusiness;
  18. }
  19. public void OnActionExecuting(ActionExecutingContext context)
  20. {
  21. var token = context.HttpContext.Request.Cookies[TokenCookieName];
  22. var userId = Guid.Empty.ToDbo();
  23. if (!string.IsNullOrWhiteSpace(token))
  24. {
  25. var tokenRes = _luUsersBusiness.GetToken(token);
  26. if (tokenRes.Status == LuStatus.NotFound)
  27. {
  28. LuResult<object>.Error(LuStatus.LoginError, $"token: {token}", "Invalid session").Throw();
  29. }
  30. tokenRes.ThrowIfNotSuccess();
  31. var tokenValidityRes = _luUsersBusiness.IsTokenValid(tokenRes.Data).ThrowIfNotSuccess();
  32. if (!tokenValidityRes.Data)
  33. {
  34. LuResult<object>.Error(LuStatus.LoginError, $"token: {token}", "Invalid session").Throw();
  35. }
  36. userId = tokenRes.Data.UserId;
  37. }
  38. var userRes = _luUsersBusiness.GetSingleById(userId).ThrowIfNotSuccess();
  39. context.HttpContext.SetLuLoggedUser(userRes.Data);
  40. }
  41. public void OnActionExecuted(ActionExecutedContext context)
  42. {
  43. }
  44. }
  45. }