|
1 | 1 | using FairPlayTube.ClientServices.KiotaClient;
|
| 2 | +using FairPlayTube.ClientServices.KiotaClient.Models; |
| 3 | +using FairPlayTube.MAUI.Helpers; |
2 | 4 | using Microsoft.AspNetCore.Components.Authorization;
|
3 | 5 | using System.Security.Claims;
|
4 | 6 |
|
5 | 7 | namespace FairPlayTube.MAUI.Authentication
|
6 | 8 | {
|
7 | 9 | public class CustomAuthenticationStateProvider(
|
8 |
| - [FromKeyedServices("AuthenticatedApiClient")] |
9 |
| - ApiClient authenticatedClient |
10 |
| - |
| 10 | + IServiceProvider serviceProvider, |
| 11 | + [FromKeyedServices("AnonymousApiClient")] |
| 12 | + ApiClient anonymousApiClient |
11 | 13 | ) : AuthenticationStateProvider
|
12 | 14 | {
|
13 |
| - public override async Task<AuthenticationState> GetAuthenticationStateAsync() |
| 15 | + private ClaimsPrincipal currentUser = new ClaimsPrincipal(new ClaimsIdentity()); |
| 16 | + |
| 17 | + public Task LoginAsync(LoginRequest loginRequest) |
14 | 18 | {
|
15 |
| - ClaimsIdentity identity = new(); |
16 |
| - if (UserContext.IsAuthenticated) { |
17 |
| - var response = await authenticatedClient.Identity.GetMyRoles.GetAsync(); |
18 |
| - foreach (var singleUserRole in response!) |
| 19 | + |
| 20 | + var loginTask = LogInAsyncCore(); |
| 21 | + NotifyAuthenticationStateChanged(loginTask); |
| 22 | + |
| 23 | + return loginTask; |
| 24 | + |
| 25 | + async Task<AuthenticationState> LogInAsyncCore() |
| 26 | + { |
| 27 | + var result = await anonymousApiClient!.Login.PostAsync(loginRequest); |
| 28 | + UserContext.AccessToken = result.AccessToken; |
| 29 | + UserContext.AccessTokenExpiresIn = result.ExpiresIn; |
| 30 | + UserContext.RefreshToken = result.RefreshToken; |
| 31 | + UserContext.TokenExpiraton = DateTimeOffset.UtcNow.AddMinutes(result!.ExpiresIn!.Value); |
| 32 | + using var scope = serviceProvider.CreateScope(); |
| 33 | + var authenticatedClient = scope.ServiceProvider |
| 34 | + .GetRequiredKeyedService<ApiClient>("AuthenticatedApiClient"); |
| 35 | + |
| 36 | + ClaimsIdentity identity = new(); |
| 37 | + if (UserContext.IsAuthenticated) |
19 | 38 | {
|
20 |
| - identity.AddClaim(new Claim(ClaimTypes.Role, singleUserRole)); |
| 39 | + var response = await authenticatedClient.Identity.GetMyRoles.GetAsync(); |
| 40 | + foreach (var singleUserRole in response!) |
| 41 | + { |
| 42 | + identity.AddClaim(new Claim(ClaimTypes.Role, singleUserRole)); |
| 43 | + } |
21 | 44 | }
|
| 45 | + this.currentUser = new ClaimsPrincipal(identity); |
| 46 | + var authenticationState = new AuthenticationState(this.currentUser); |
| 47 | + return authenticationState; |
22 | 48 | }
|
23 |
| - var user = new ClaimsPrincipal(identity); |
24 |
| - var result = new AuthenticationState(user); |
25 |
| - return result; |
26 | 49 | }
|
| 50 | + |
| 51 | + public override Task<AuthenticationState> GetAuthenticationStateAsync() => |
| 52 | + Task.FromResult(new AuthenticationState(currentUser)); |
27 | 53 | }
|
28 | 54 | }
|
0 commit comments