UserService.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. using Blazored.LocalStorage;
  2. using Microsoft.AspNetCore.Components.Authorization;
  3. using System.Net.Http;
  4. using System.Net.Http.Json;
  5. using System.Threading.Tasks;
  6. using wispro.sp.web.Auth;
  7. using wispro.sp.web.Models;
  8. using wispro.sp.web.Utils;
  9. using System.Security.Claims;
  10. using System.Collections.Generic;
  11. using wispro.sp.entity;
  12. using System;
  13. using wispro.sp.share.webViewObject;
  14. using System.Text.Json;
  15. namespace wispro.sp.web.Services
  16. {
  17. public interface IUserService
  18. {
  19. //CurrentUser CurrentUser { get; set; }
  20. Task<List<Staff>> GetAll();
  21. Task<CurrentUser> GetUser();
  22. }
  23. public class UserService : IUserService
  24. {
  25. private readonly IHttpService _httpClient;
  26. private readonly JwtAuthenticationStateProvider _jwt;
  27. private readonly ILocalStorageService _localStorageService;
  28. //private CurrentUser _CurrentUser= new CurrentUser() { Name = "" };
  29. public UserService(IHttpService httpClient, ILocalStorageService localStorageService, AuthenticationStateProvider jwt)
  30. {
  31. _httpClient = httpClient;
  32. _localStorageService = localStorageService;
  33. _jwt = (JwtAuthenticationStateProvider)jwt;
  34. }
  35. //public CurrentUser CurrentUser
  36. //{
  37. // get
  38. // {
  39. // return _CurrentUser;
  40. // }
  41. // set
  42. // {
  43. // _CurrentUser = value;
  44. // }
  45. //}
  46. public async Task<CurrentUser> GetUser()
  47. {
  48. CurrentUser _user = new CurrentUser();
  49. var tokenInLocalStorage = await _localStorageService.GetItemAsync<userToken>("authToken");
  50. if (tokenInLocalStorage == null)
  51. {
  52. _jwt.NotifyUserLogOut();
  53. return null;
  54. }
  55. var claims = JwtParser.ParseClaimsFromJwt(tokenInLocalStorage.Token);
  56. foreach (Claim claim in claims)
  57. {
  58. if (claim.Type == ClaimTypes.Name )
  59. {
  60. _user.Name = claim.Value;
  61. break;
  62. }
  63. }
  64. _user.Userid = tokenInLocalStorage.UserId;
  65. return _user;
  66. }
  67. public async Task<List<Staff>> GetAll()
  68. {
  69. try
  70. {
  71. var _StaffGrade = await _httpClient.Get<List<Staff>>($"Staff/GetAll");
  72. return _StaffGrade;
  73. }
  74. catch (Exception ex)
  75. {
  76. if (ex.Message.Contains("Unauthorized"))
  77. {
  78. _jwt.NotifyUserLogOut();
  79. }
  80. return null;
  81. }
  82. }
  83. }
  84. }