Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

LuLoggedUserMiddleware.cs 2.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System;
  2. using Luticate2.Auth.Controllers;
  3. using Luticate2.Auth.Interfaces.Tokens;
  4. using Luticate2.Auth.Interfaces.Users;
  5. using Luticate2.Utils.Dbo.Result;
  6. using Luticate2.Utils.Utils;
  7. using Microsoft.AspNetCore.Mvc.Controllers;
  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 actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
  23. if (actionDescriptor == null)
  24. {
  25. LuResult<bool>.Error(LuStatus.InternalError,
  26. $"{nameof(LuLoggedUserMiddleware)}: actionDescriptor == null").Throw();
  27. return;
  28. }
  29. var isLogin = false;
  30. var isLogout = false;
  31. if (actionDescriptor.ControllerTypeInfo.AsType() == typeof(LuUsersController))
  32. {
  33. if (actionDescriptor.ActionName == nameof(LuUsersController.Login))
  34. {
  35. isLogin = true;
  36. }
  37. else if (actionDescriptor.ActionName == nameof(LuUsersController.Logout))
  38. {
  39. isLogout = true;
  40. }
  41. }
  42. var token = context.HttpContext.GetLuUserToken();
  43. var userId = Guid.Empty.ToDbo();
  44. if (token != null && !isLogout && !isLogin)//TODO
  45. {
  46. var tokenRes = _luTokensBusiness.GetToken(token);
  47. if (tokenRes.Status == LuStatus.NotFound)
  48. {
  49. LuResult<object>.Error(LuStatus.LoginError, $"unknown token: {token}", "Invalid session").Throw();
  50. }
  51. tokenRes.ThrowIfNotSuccess();
  52. var tokenValid = _luTokensBusiness.IsTokenValid(tokenRes.Data);
  53. if (!tokenValid)
  54. {
  55. LuResult<object>.Error(LuStatus.LoginError, $"invalid token: {token}", "Invalid session").Throw();
  56. }
  57. userId = tokenRes.Data.UserId;
  58. }
  59. var userRes = _luUsersBusiness.GetSingleById(userId).ThrowIfNotSuccess();
  60. context.HttpContext.SetLuLoggedUser(userRes.Data);
  61. }
  62. public void OnActionExecuted(ActionExecutedContext context)
  63. {
  64. }
  65. }
  66. }