UserService.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. namespace wispro.sp.web.Services
  14. {
  15. public interface IUserService
  16. {
  17. CurrentUser CurrentUser { get; set; }
  18. Task<List<Staff>> GetAll();
  19. }
  20. public class UserService : IUserService
  21. {
  22. private readonly HttpClient _httpClient;
  23. private readonly JwtAuthenticationStateProvider _jwt;
  24. private readonly ILocalStorageService _localStorageService;
  25. private CurrentUser _CurrentUser= new CurrentUser() { Name = "" };
  26. public UserService(HttpClient httpClient, ILocalStorageService localStorageService, AuthenticationStateProvider jwt)
  27. {
  28. _httpClient = httpClient;
  29. _localStorageService = localStorageService;
  30. _jwt = (JwtAuthenticationStateProvider)jwt;
  31. }
  32. public CurrentUser CurrentUser
  33. {
  34. get
  35. {
  36. return _CurrentUser;
  37. }
  38. set
  39. {
  40. _CurrentUser = value;
  41. }
  42. }
  43. public async Task<CurrentUser> GetUser()
  44. {
  45. CurrentUser _user = new CurrentUser();
  46. var tokenInLocalStorage = await _localStorageService.GetItemAsStringAsync("authToken");
  47. var claims = JwtParser.ParseClaimsFromJwt(tokenInLocalStorage);
  48. foreach (Claim claim in claims)
  49. {
  50. if (claim.Type == ClaimTypes.Name )
  51. {
  52. _user.Name = claim.Value;
  53. break;
  54. }
  55. }
  56. return _user;
  57. }
  58. public async Task<List<Staff>> GetAll()
  59. {
  60. try
  61. {
  62. var _StaffGrade = await _httpClient.GetFromJsonAsync<List<Staff>>($"http://localhost:39476/api/Staff/GetAll");
  63. return _StaffGrade;
  64. }
  65. catch (Exception ex)
  66. {
  67. if (ex.Message.Contains("Unauthorized"))
  68. {
  69. _jwt.NotifyUserLogOut();
  70. }
  71. return null;
  72. }
  73. }
  74. }
  75. }