LoginContext.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System.Security.Claims;
  2. using GxPress.Common.Tools;
  3. using GxPress.EnumConst;
  4. using Microsoft.AspNetCore.Http;
  5. namespace GxPress.Auth
  6. {
  7. /// <summary>
  8. /// 登录用户上下文
  9. /// </summary>
  10. public class LoginContext : ILoginContext
  11. {
  12. private readonly IHttpContextAccessor _contextAccessor;
  13. public LoginContext(IHttpContextAccessor contextAccessor)
  14. {
  15. _contextAccessor = contextAccessor;
  16. }
  17. /// <summary>
  18. /// 账户id
  19. /// </summary>
  20. public int AccountId
  21. {
  22. get
  23. {
  24. var value = _contextAccessor?.HttpContext?.User?.FindFirst(ClaimTypes.NameIdentifier);
  25. if (int.TryParse(value?.Value, out var accountId))
  26. {
  27. return accountId;
  28. }
  29. return -1;
  30. }
  31. }
  32. public int DepartmentId
  33. {
  34. get
  35. {
  36. var value = _contextAccessor?.HttpContext?.User?.FindFirst(ClaimTypes.GroupSid);
  37. if (int.TryParse(value?.Value, out var departmentId))
  38. {
  39. return departmentId;
  40. }
  41. return -1;
  42. }
  43. }
  44. /// <summary>
  45. /// 账号类型
  46. /// </summary>
  47. public AccountTypeConst AccountType
  48. {
  49. get
  50. {
  51. var ty = _contextAccessor?.HttpContext?.User?.FindFirst(ClaimTypes.Role);
  52. return StringUtils.ToEnum(ty?.Value, AccountTypeConst.UnKnown);
  53. }
  54. }
  55. /// <summary>
  56. /// 获取当前用户IP
  57. /// </summary>
  58. public string Ip => _contextAccessor?.HttpContext?.Connection == null
  59. ? string.Empty
  60. : _contextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
  61. public string Name
  62. {
  63. get
  64. {
  65. var value = _contextAccessor?.HttpContext?.User?.FindFirst(ClaimTypes.Actor);
  66. return value.Value;
  67. }
  68. }
  69. //TODO 其他用户相关信息获取?
  70. }
  71. }