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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. throw new LuResultException(LuResult<object>.Error(LuStatus.LoginError, $"{token}", "Invalid session"));
  29. }
  30. if (!tokenRes)
  31. {
  32. throw new LuResultException(tokenRes.To<object>());
  33. }
  34. userId = tokenRes.Data.UserId;
  35. }
  36. var userRes = _luUsersBusiness.GetSingleById(userId);
  37. if (!userRes)
  38. {
  39. throw new LuResultException(userRes.To<object>());
  40. }
  41. context.HttpContext.SetLuLoggedUser(userRes.Data);
  42. }
  43. public void OnActionExecuted(ActionExecutedContext context)
  44. {
  45. }
  46. }
  47. }