Skip to content

Commit f755a2b

Browse files
committed
Refactor user profile operations to UserProfileService
Centralized user profile related operations in `UserProfileService` by replacing `AuthenticationStateProvider` with `UserProfileService` in several files. Renamed `GetUserProfile()` to `GetUserProfileAsync()` to indicate its asynchronous nature. Moved `GetBuyerIdAsync()` and `GetUserNameAsync()` methods from `Extensions.cs` to `UserProfileService.cs`. Modified `UpdateProfile()` method in `UserProfileService.cs` to use `AccountController` for updating user profile. Added `GetUserAsync()` method and `UserProfile` class in `UserProfileService.cs`. Updated `BasketState.cs` to use `userProfileService.GetUserAsync()`. Added `Microsoft.AspNetCore.Authentication` namespace in `LogOutService.cs` and `System.Security.Claims`, `System.Text`, and `System.Text.Json` namespaces in `UserProfileService.cs`.
1 parent eeb6f6b commit f755a2b

File tree

6 files changed

+45
-29
lines changed

6 files changed

+45
-29
lines changed

WebApp/Components/Pages/User/OrdersRefreshOnStatusChange.razor

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
@inject AuthenticationStateProvider AuthenticationStateProvider
44
@inject OrderStatusNotificationService OrderStatusNotificationService
55
@inject NavigationManager Nav
6+
@inject UserProfileService ProfileService
67
@implements IDisposable
78
@code {
89
private IDisposable? orderStatusChangedSubscription;
@@ -11,7 +12,7 @@
1112
{
1213
if (firstRender)
1314
{
14-
var buyerId = await AuthenticationStateProvider.GetBuyerIdAsync();
15+
var buyerId = await ProfileService.GetBuyerIdAsync();
1516
if (!string.IsNullOrEmpty(buyerId))
1617
{
1718
orderStatusChangedSubscription = OrderStatusNotificationService.SubscribeToOrderStatusNotifications(

WebApp/Components/Pages/User/UserProfile.razor

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@
4747

4848
protected override async Task OnInitializedAsync()
4949
{
50-
userProfile = await ProfileService.GetUserProfile();
50+
userProfile = await ProfileService.GetUserProfileAsync();
5151
}
5252

5353
private async Task UpdateProfile()
@@ -62,7 +62,7 @@
6262
{
6363
updateMessage = "Profile updated successfully!";
6464
// Re-fetch the user profile to get the updated information
65-
userProfile = await ProfileService.GetUserProfile();
65+
userProfile = await ProfileService.GetUserProfileAsync();
6666
}
6767
}
6868
catch (Exception)

WebApp/Extensions/Extensions.cs

Lines changed: 0 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -103,18 +103,4 @@ private static void AddAIServices(this IHostApplicationBuilder builder)
103103
builder.Services.AddAzureOpenAIChatCompletion(deploymentName);
104104
}
105105
}
106-
107-
public static async Task<string?> GetBuyerIdAsync(this AuthenticationStateProvider authenticationStateProvider)
108-
{
109-
var authState = await authenticationStateProvider.GetAuthenticationStateAsync();
110-
var user = authState.User;
111-
return user.FindFirst("sub")?.Value;
112-
}
113-
114-
public static async Task<string?> GetUserNameAsync(this AuthenticationStateProvider authenticationStateProvider)
115-
{
116-
var authState = await authenticationStateProvider.GetAuthenticationStateAsync();
117-
var user = authState.User;
118-
return user.FindFirst("name")?.Value;
119-
}
120106
}

WebApp/Services/BasketState.cs

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,14 @@
11
namespace eShop.WebApp.Services;
2-
using System.Security.Claims;
2+
33
using Microsoft.AspNetCore.Components;
4-
using Microsoft.AspNetCore.Components.Authorization;
54
using eShop.WebAppComponents.Catalog;
65
using eShop.WebAppComponents.Services;
76

87
public class BasketState(
98
BasketService basketService,
109
CatalogService catalogService,
1110
OrderingService orderingService,
12-
AuthenticationStateProvider authenticationStateProvider)
11+
UserProfileService userProfileService)
1312
{
1413
private Task<IReadOnlyCollection<BasketItem>>? _cachedBasket;
1514
private HashSet<BasketStateChangedSubscription> _changeSubscriptions = new();
@@ -18,7 +17,7 @@ public Task DeleteBasketAsync()
1817
=> basketService.DeleteBasketAsync();
1918

2019
public async Task<IReadOnlyCollection<BasketItem>> GetBasketItemsAsync()
21-
=> (await GetUserAsync()).Identity?.IsAuthenticated == true
20+
=> (await userProfileService.GetUserAsync()).Identity?.IsAuthenticated == true
2221
? await FetchBasketItemsAsync()
2322
: [];
2423

@@ -81,8 +80,8 @@ public async Task CheckoutAsync(BasketCheckoutInfo checkoutInfo)
8180
checkoutInfo.RequestId = Guid.NewGuid();
8281
}
8382

84-
var buyerId = await authenticationStateProvider.GetBuyerIdAsync() ?? throw new InvalidOperationException("User does not have a buyer ID");
85-
var userName = await authenticationStateProvider.GetUserNameAsync() ?? throw new InvalidOperationException("User does not have a user name");
83+
var buyerId = await userProfileService.GetBuyerIdAsync() ?? throw new InvalidOperationException("User does not have a buyer ID");
84+
var userName = await userProfileService.GetUserNameAsync() ?? throw new InvalidOperationException("User does not have a user name");
8685

8786
// Get details for the items in the basket
8887
var orderItems = await FetchBasketItemsAsync();
@@ -110,9 +109,6 @@ public async Task CheckoutAsync(BasketCheckoutInfo checkoutInfo)
110109
private Task NotifyChangeSubscribersAsync()
111110
=> Task.WhenAll(_changeSubscriptions.Select(s => s.NotifyAsync()));
112111

113-
private async Task<ClaimsPrincipal> GetUserAsync()
114-
=> (await authenticationStateProvider.GetAuthenticationStateAsync()).User;
115-
116112
private Task<IReadOnlyCollection<BasketItem>> FetchBasketItemsAsync()
117113
{
118114
return _cachedBasket ??= FetchCoreAsync();

WebApp/Services/LogOutService.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
namespace eShop.WebApp.Services;
2+
23
using Microsoft.AspNetCore.Authentication;
34
using Microsoft.AspNetCore.Authentication.Cookies;
45
using Microsoft.AspNetCore.Authentication.OpenIdConnect;

WebApp/Services/UserProfileService.cs

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
namespace eShop.WebApp.Services;
22

3+
using System.Security.Claims;
4+
using System.Text;
5+
using System.Text.Json;
36
using Microsoft.AspNetCore.Components;
47
using Microsoft.AspNetCore.Components.Authorization;
58

@@ -9,9 +12,10 @@ public class UserProfileService(HttpClient httpClient, AuthenticationStateProvid
912
[CascadingParameter]
1013
public HttpContext HttpContext { get; set; } = default!;
1114

12-
public async Task<UserProfile> GetUserProfile()
15+
public async Task<UserProfile> GetUserProfileAsync()
1316
{
1417
var authState = await authenticationStateProvider.GetAuthenticationStateAsync();
18+
authState.User.Claims.ToList().ForEach(claim => Console.WriteLine($"{claim.Type}: {claim.Value}"));
1519
var user = authState.User;
1620

1721
return new UserProfile
@@ -25,14 +29,42 @@ public async Task<UserProfile> GetUserProfile()
2529

2630
private static string? ReadClaim(string type, System.Security.Claims.ClaimsPrincipal? user) => user.FindFirst(x => x.Type == type)?.Value;
2731

28-
public Task<HttpResponseMessage> UpdateProfile(UserProfile userProfile)
32+
/*public Task<HttpResponseMessage> UpdateProfile(UserProfile userProfile)
2933
{
30-
/*await httpClient.PutAsJsonAsync(userProfileApiUrl, userProfile);*/
34+
*//*await httpClient.PutAsJsonAsync(userProfileApiUrl, userProfile);*//*
3135
httpClient.ToString();
3236
Console.WriteLine(userProfileApiUrl + userProfile);
3337
return Task.FromResult(new HttpResponseMessage(System.Net.HttpStatusCode.OK));
38+
}*/
39+
40+
// Use the AccountController to update the user profile
41+
public Task<HttpResponseMessage> UpdateProfile(UserProfile userProfile)
42+
{
43+
var request = new HttpRequestMessage(HttpMethod.Put, userProfileApiUrl)
44+
{
45+
Content = new StringContent(JsonSerializer.Serialize(userProfile), Encoding.UTF8, "application/json")
46+
};
47+
48+
return httpClient.SendAsync(request);
49+
}
50+
51+
public async Task<string?> GetBuyerIdAsync()
52+
{
53+
var authState = await authenticationStateProvider.GetAuthenticationStateAsync();
54+
var user = authState.User;
55+
return user.FindFirst("sub")?.Value;
3456
}
3557

58+
public async Task<string?> GetUserNameAsync()
59+
{
60+
var authState = await authenticationStateProvider.GetAuthenticationStateAsync();
61+
var user = authState.User;
62+
return user.FindFirst("name")?.Value;
63+
}
64+
65+
public async Task<ClaimsPrincipal> GetUserAsync()
66+
=> (await authenticationStateProvider.GetAuthenticationStateAsync()).User;
67+
3668
public class UserProfile
3769
{
3870
public string? Name { get; set; }

0 commit comments

Comments
 (0)