UserService.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. namespace wispro.sp.web.Services
  11. {
  12. public interface IUserService
  13. {
  14. CurrentUser CurrentUser { get; set; }
  15. }
  16. public class UserService : IUserService
  17. {
  18. private readonly HttpClient _httpClient;
  19. private readonly ILocalStorageService _localStorageService;
  20. private CurrentUser _CurrentUser= new CurrentUser() { Name = "" };
  21. public UserService(HttpClient httpClient, ILocalStorageService localStorageService)
  22. {
  23. _httpClient = httpClient;
  24. _localStorageService = localStorageService;
  25. }
  26. public CurrentUser CurrentUser
  27. {
  28. get
  29. {
  30. return _CurrentUser;
  31. }
  32. set
  33. {
  34. _CurrentUser = value;
  35. }
  36. }
  37. public async Task<CurrentUser> GetUser()
  38. {
  39. CurrentUser _user = new CurrentUser();
  40. var tokenInLocalStorage = await _localStorageService.GetItemAsStringAsync("authToken");
  41. var claims = JwtParser.ParseClaimsFromJwt(tokenInLocalStorage);
  42. foreach (Claim claim in claims)
  43. {
  44. if (claim.Type == ClaimTypes.Name )
  45. {
  46. _user.Name = claim.Value;
  47. break;
  48. }
  49. }
  50. return _user;
  51. }
  52. }
  53. }