IdentityService.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using System.Security.Claims;
  2. namespace Admin.NET.Core.Service.ApiJson
  3. {
  4. public class IdentityService : IIdentityService
  5. {
  6. private IHttpContextAccessor _context;
  7. private List<Role> _roles;
  8. public IdentityService(IHttpContextAccessor context, IOptions<ApiJsonOptions> roles)
  9. {
  10. _context = context ?? throw new ArgumentNullException(nameof(context));
  11. //roles = App.GetConfig<List<Role>>("ApiJson:RoleList");
  12. _roles = roles.Value.RoleList;
  13. }
  14. public string GetUserIdentity()
  15. {
  16. return _context.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
  17. }
  18. public string GetUserRoleName()
  19. {
  20. return _context.HttpContext.User.FindFirstValue(ClaimTypes.Role);
  21. }
  22. public Role GetRole()
  23. {
  24. var role = new Role();
  25. if (string.IsNullOrEmpty(GetUserRoleName()))//没登录默认取第一个
  26. {
  27. role = _roles.FirstOrDefault();
  28. }
  29. else
  30. {
  31. role = _roles.FirstOrDefault(it => it.Name.Equals(GetUserRoleName(), StringComparison.CurrentCultureIgnoreCase));
  32. }
  33. return role;
  34. }
  35. public (bool, string) GetSelectRole(string table)
  36. {
  37. var role = GetRole();
  38. if (role == null || role.Select == null || role.Select.Table == null)
  39. {
  40. return (false, $"appsettings.json权限配置不正确!");
  41. }
  42. string tablerole = role.Select.Table.FirstOrDefault(it => it == "*" || it.Equals(table, StringComparison.CurrentCultureIgnoreCase));
  43. if (string.IsNullOrEmpty(tablerole))
  44. {
  45. return (false, $"表名{table}没权限查询!");
  46. }
  47. int index = Array.IndexOf(role.Select.Table, tablerole);
  48. string selectrole = role.Select.Column[index];
  49. return (true, selectrole);
  50. }
  51. public bool ColIsRole(string col, string[] selectrole)
  52. {
  53. if (selectrole.Contains("*"))
  54. {
  55. return true;
  56. }
  57. else
  58. {
  59. if (col.Contains("(") && col.Contains(")"))
  60. {
  61. Regex reg = new Regex(@"\(([^)]*)\)");
  62. Match m = reg.Match(col);
  63. if (selectrole.Contains(m.Result("$1"), StringComparer.CurrentCultureIgnoreCase))
  64. {
  65. return true;
  66. }
  67. else
  68. {
  69. return false;
  70. }
  71. }
  72. else
  73. {
  74. if (selectrole.Contains(col, StringComparer.CurrentCultureIgnoreCase))
  75. {
  76. return true;
  77. }
  78. else
  79. {
  80. return false;
  81. }
  82. }
  83. }
  84. }
  85. }
  86. }