in the middle of relearning msal

This commit is contained in:
2022-11-17 16:18:15 -06:00
parent 716470f24d
commit e3cf2f1059
14 changed files with 324 additions and 298 deletions

View File

@@ -1,9 +1,9 @@
@*<CascadingAuthenticationState>*@
<CascadingAuthenticationState>
<Router AppAssembly="@typeof(App).Assembly">
<Found Context="routeData">
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
@*<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
<Authorizing>
Authorizing!!
</Authorizing>
@@ -17,7 +17,7 @@
<p role="alert">You are not authorized to access this resource.</p>
}
</NotAuthorized>
</AuthorizeRouteView>*@
</AuthorizeRouteView>
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
</Found>
<NotFound>
@@ -28,4 +28,4 @@
</NotFound>
</Router>
@*</CascadingAuthenticationState>*@
</CascadingAuthenticationState>

View File

@@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Shogi.UI.Pages.Home.Api;
using Shogi.UI.Shared;
@@ -6,133 +7,132 @@ namespace Shogi.UI.Pages.Home.Account;
public class AccountManager
{
private readonly AccountState accountState;
private readonly IShogiApi shogiApi;
private readonly IConfiguration configuration;
private readonly ILocalStorage localStorage;
//private readonly AuthenticationStateProvider authState;
private readonly NavigationManager navigation;
private readonly ShogiSocket shogiSocket;
private readonly AccountState accountState;
private readonly IShogiApi shogiApi;
private readonly IConfiguration configuration;
private readonly ILocalStorage localStorage;
private readonly AuthenticationStateProvider authState;
private readonly NavigationManager navigation;
private readonly ShogiSocket shogiSocket;
public AccountManager(
AccountState accountState,
IShogiApi unauthenticatedClient,
IConfiguration configuration,
//AuthenticationStateProvider authState,
ILocalStorage localStorage,
NavigationManager navigation,
ShogiSocket shogiSocket)
{
this.accountState = accountState;
this.shogiApi = unauthenticatedClient;
this.configuration = configuration;
//this.authState = authState;
this.localStorage = localStorage;
this.navigation = navigation;
this.shogiSocket = shogiSocket;
}
public AccountManager(
AccountState accountState,
IShogiApi unauthenticatedClient,
IConfiguration configuration,
AuthenticationStateProvider authState,
ILocalStorage localStorage,
NavigationManager navigation,
ShogiSocket shogiSocket)
{
this.accountState = accountState;
this.shogiApi = unauthenticatedClient;
this.configuration = configuration;
this.authState = authState;
this.localStorage = localStorage;
this.navigation = navigation;
this.shogiSocket = shogiSocket;
}
private User? User { get => accountState.User; set => accountState.User = value; }
private User? User { get => accountState.User; set => accountState.User = value; }
public async Task LoginWithGuestAccount()
{
var response = await shogiApi.GetToken();
if (response != null)
{
User = new User
{
DisplayName = response.DisplayName,
Id = response.UserId,
OneTimeSocketToken = response.OneTimeToken,
WhichAccountPlatform = WhichAccountPlatform.Guest
};
await shogiSocket.OpenAsync(User.OneTimeSocketToken.ToString());
await localStorage.SetAccountPlatform(WhichAccountPlatform.Guest);
}
}
public async Task LoginWithGuestAccount()
{
var response = await shogiApi.GetToken();
if (response != null)
{
User = new User
{
DisplayName = response.DisplayName,
Id = response.UserId,
OneTimeSocketToken = response.OneTimeToken,
WhichAccountPlatform = WhichAccountPlatform.Guest
};
await shogiSocket.OpenAsync(User.OneTimeSocketToken.ToString());
await localStorage.SetAccountPlatform(WhichAccountPlatform.Guest);
}
}
public async Task LoginWithMicrosoftAccount()
{
throw new NotImplementedException();
//var state = await authState.GetAuthenticationStateAsync();
public async Task LoginWithMicrosoftAccount()
{
var state = await authState.GetAuthenticationStateAsync();
//if (state.User?.Identity?.Name == null || state.User?.Identity?.IsAuthenticated != true)
//{
// navigation.NavigateTo("authentication/login");
// return;
//}
if (state.User?.Identity?.Name == null || state.User?.Identity?.IsAuthenticated != true)
{
navigation.NavigateTo("authentication/login");
return;
}
//var id = state.User.Identity.Name;
//var socketToken = await shogiApi.GetToken();
//if (socketToken.HasValue)
//{
// User = new User
// {
// DisplayName = id,
// Id = id,
// OneTimeSocketToken = socketToken.Value
// };
var response = await shogiApi.GetToken();
if (response != null)
{
User = new User
{
DisplayName = response.DisplayName,
Id = response.UserId,
OneTimeSocketToken = response.OneTimeToken,
WhichAccountPlatform = WhichAccountPlatform.Microsoft,
};
// await ConnectToSocketAsync();
// await localStorage.SetAccountPlatform(WhichAccountPlatform.Microsoft);
// }
}
await shogiSocket.OpenAsync(User.OneTimeSocketToken.ToString());
await localStorage.SetAccountPlatform(WhichAccountPlatform.Microsoft);
}
}
/// <summary>
/// Try to log in with the account used from the previous browser session.
/// </summary>
/// <returns></returns>
public async Task<bool> TryLoginSilentAsync()
{
var platform = await localStorage.GetAccountPlatform();
if (platform == WhichAccountPlatform.Guest)
{
var response = await shogiApi.GetToken();
if (response != null)
{
User = new User
{
DisplayName = response.DisplayName,
Id = response.UserId,
OneTimeSocketToken = response.OneTimeToken,
WhichAccountPlatform = WhichAccountPlatform.Guest
};
}
}
else if (platform == WhichAccountPlatform.Microsoft)
{
Console.WriteLine("Login Microsoft");
throw new NotImplementedException();
//var state = await authState.GetAuthenticationStateAsync();
//if (state.User?.Identity?.Name != null)
//{
// var id = state.User.Identity;
// User = new User
// {
// DisplayName = id.Name,
// Id = id.Name
// };
// var token = await shogiApi.GetToken();
// if (token.HasValue)
// {
// User.OneTimeSocketToken = token.Value;
// }
//}
// TODO: If this fails then platform saved to localStorage should get cleared
}
/// <summary>
/// Try to log in with the account used from the previous browser session.
/// </summary>
/// <returns></returns>
public async Task<bool> TryLoginSilentAsync()
{
var platform = await localStorage.GetAccountPlatform();
if (platform == WhichAccountPlatform.Guest)
{
var response = await shogiApi.GetToken();
if (response != null)
{
User = new User
{
DisplayName = response.DisplayName,
Id = response.UserId,
OneTimeSocketToken = response.OneTimeToken,
WhichAccountPlatform = WhichAccountPlatform.Guest
};
}
}
else if (platform == WhichAccountPlatform.Microsoft)
{
Console.WriteLine("Login Microsoft");
throw new NotImplementedException();
//var state = await authState.GetAuthenticationStateAsync();
//if (state.User?.Identity?.Name != null)
//{
// var id = state.User.Identity;
// User = new User
// {
// DisplayName = id.Name,
// Id = id.Name
// };
// var token = await shogiApi.GetToken();
// if (token.HasValue)
// {
// User.OneTimeSocketToken = token.Value;
// }
//}
// TODO: If this fails then platform saved to localStorage should get cleared
}
if (User != null)
{
await shogiSocket.OpenAsync(User.OneTimeSocketToken.ToString());
return true;
}
if (User != null)
{
await shogiSocket.OpenAsync(User.OneTimeSocketToken.ToString());
return true;
}
return false;
}
return false;
}
public async Task LogoutAsync()
{
await Task.WhenAll(shogiApi.GuestLogout(), localStorage.DeleteAccountPlatform());
User = null;
}
public async Task LogoutAsync()
{
await Task.WhenAll(shogiApi.GuestLogout(), localStorage.DeleteAccountPlatform());
User = null;
}
}

View File

@@ -1,24 +1,23 @@
using Shogi.UI.Shared;
namespace Shogi.UI.Pages.Home.Account
namespace Shogi.UI.Pages.Home.Account;
public static class LocalStorageExtensions
{
public static class LocalStorageExtensions
private const string AccountPlatform = "AccountPlatform";
public static Task<WhichAccountPlatform?> GetAccountPlatform(this ILocalStorage self)
{
private const string AccountPlatform = "AccountPlatform";
return self.Get<WhichAccountPlatform>(AccountPlatform).AsTask();
}
public static Task<WhichAccountPlatform?> GetAccountPlatform(this ILocalStorage self)
{
return self.Get<WhichAccountPlatform>(AccountPlatform).AsTask();
}
public static Task SetAccountPlatform(this ILocalStorage self, WhichAccountPlatform platform)
{
return self.Set(AccountPlatform, platform.ToString()).AsTask();
}
public static Task SetAccountPlatform(this ILocalStorage self, WhichAccountPlatform platform)
{
return self.Set(AccountPlatform, platform.ToString()).AsTask();
}
public static Task DeleteAccountPlatform(this ILocalStorage self)
{
return self.Delete(AccountPlatform).AsTask();
}
public static Task DeleteAccountPlatform(this ILocalStorage self)
{
return self.Delete(AccountPlatform).AsTask();
}
}

View File

@@ -1,7 +1,6 @@
namespace Shogi.UI.Pages.Home.Account
namespace Shogi.UI.Pages.Home.Account;
public class LoginEventArgs : EventArgs
{
public class LoginEventArgs : EventArgs
{
public User? User { get; set; }
}
public User? User { get; set; }
}

View File

@@ -10,6 +10,6 @@ public interface IShogiApi
Task<ReadSessionsPlayerCountResponse?> GetSessionsPlayerCount();
Task<CreateTokenResponse?> GetToken();
Task GuestLogout();
Task PostMove(string sessionName, MovePieceCommand move);
Task Move(string sessionName, MovePieceCommand move);
Task<HttpStatusCode> PostSession(string name, bool isPrivate);
}

View File

@@ -7,74 +7,74 @@ using System.Text.Json;
namespace Shogi.UI.Pages.Home.Api
{
public class ShogiApi : IShogiApi
{
public const string GuestClientName = "Guest";
public const string MsalClientName = "Msal";
public const string AnonymouseClientName = "Anonymous";
public class ShogiApi : IShogiApi
{
public const string GuestClientName = "Guest";
public const string MsalClientName = "Msal";
public const string AnonymouseClientName = "Anonymous";
private readonly JsonSerializerOptions serializerOptions;
private readonly IHttpClientFactory clientFactory;
private readonly AccountState accountState;
private readonly JsonSerializerOptions serializerOptions;
private readonly IHttpClientFactory clientFactory;
private readonly AccountState accountState;
public ShogiApi(IHttpClientFactory clientFactory, AccountState accountState)
{
serializerOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web);
this.clientFactory = clientFactory;
this.accountState = accountState;
}
public ShogiApi(IHttpClientFactory clientFactory, AccountState accountState)
{
serializerOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web);
this.clientFactory = clientFactory;
this.accountState = accountState;
}
private HttpClient HttpClient => accountState.User?.WhichAccountPlatform switch
{
WhichAccountPlatform.Guest => clientFactory.CreateClient(GuestClientName),
WhichAccountPlatform.Microsoft => clientFactory.CreateClient(MsalClientName),
_ => clientFactory.CreateClient(AnonymouseClientName)
};
private HttpClient HttpClient => accountState.User?.WhichAccountPlatform switch
{
WhichAccountPlatform.Guest => clientFactory.CreateClient(GuestClientName),
WhichAccountPlatform.Microsoft => clientFactory.CreateClient(MsalClientName),
_ => clientFactory.CreateClient(AnonymouseClientName)
};
public async Task GuestLogout()
{
var response = await HttpClient.PutAsync(new Uri("User/GuestLogout", UriKind.Relative), null);
response.EnsureSuccessStatusCode();
}
public async Task GuestLogout()
{
var response = await HttpClient.PutAsync(new Uri("User/GuestLogout", UriKind.Relative), null);
response.EnsureSuccessStatusCode();
}
public async Task<Session?> GetSession(string name)
{
var response = await HttpClient.GetAsync(new Uri($"Sessions/{name}", UriKind.Relative));
if (response.IsSuccessStatusCode)
{
return (await response.Content.ReadFromJsonAsync<ReadSessionResponse>(serializerOptions))?.Session;
}
return null;
}
public async Task<Session?> GetSession(string name)
{
var response = await HttpClient.GetAsync(new Uri($"Sessions/{name}", UriKind.Relative));
if (response.IsSuccessStatusCode)
{
return (await response.Content.ReadFromJsonAsync<ReadSessionResponse>(serializerOptions))?.Session;
}
return null;
}
public async Task<ReadSessionsPlayerCountResponse?> GetSessionsPlayerCount()
{
var response = await HttpClient.GetAsync(new Uri("Sessions/PlayerCount", UriKind.Relative));
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadFromJsonAsync<ReadSessionsPlayerCountResponse>(serializerOptions);
}
return null;
}
public async Task<ReadSessionsPlayerCountResponse?> GetSessionsPlayerCount()
{
var response = await HttpClient.GetAsync(new Uri("Sessions/PlayerCount", UriKind.Relative));
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadFromJsonAsync<ReadSessionsPlayerCountResponse>(serializerOptions);
}
return null;
}
public async Task<CreateTokenResponse?> GetToken()
{
var response = await HttpClient.GetFromJsonAsync<CreateTokenResponse>(new Uri("User/Token", UriKind.Relative), serializerOptions);
return response;
}
public async Task<CreateTokenResponse?> GetToken()
{
var response = await HttpClient.GetFromJsonAsync<CreateTokenResponse>(new Uri("User/Token", UriKind.Relative), serializerOptions);
return response;
}
public async Task PostMove(string sessionName, MovePieceCommand command)
{
await this.HttpClient.PostAsJsonAsync($"Sessions{sessionName}/Move", command);
}
public async Task Move(string sessionName, MovePieceCommand command)
{
await this.HttpClient.PatchAsync($"Sessions/{sessionName}/Move", JsonContent.Create(command));
}
public async Task<HttpStatusCode> PostSession(string name, bool isPrivate)
{
var response = await HttpClient.PostAsJsonAsync(new Uri("Sessions", UriKind.Relative), new CreateSessionCommand
{
Name = name,
});
return response.StatusCode;
}
}
public async Task<HttpStatusCode> PostSession(string name, bool isPrivate)
{
var response = await HttpClient.PostAsJsonAsync(new Uri("Sessions", UriKind.Relative), new CreateSessionCommand
{
Name = name,
});
return response.StatusCode;
}
}
}

View File

@@ -15,10 +15,10 @@
var position = $"{file}{rank}";
var piece = session?.BoardState.Board[position];
<div class="tile"
data-position="@(position)"
data-selected="@(piece != null && selectedPosition == position)"
style="grid-area: @(position)"
@onclick="() => OnClickTile(piece, position)">
data-position="@(position)"
data-selected="@(piece != null && selectedPosition == position)"
style="grid-area: @(position)"
@onclick="() => OnClickTile(piece, position)">
<GamePiece Piece="piece" Perspective="Perspective" />
</div>
}
@@ -46,7 +46,7 @@
<span>I</span>
</div>
<!-- Promote prompt -->
<div class="promote-prompt">
<div class="promote-prompt" data-visible="@PromotePrompt.IsVisible">
<p>Do you wish to promote?</p>
<div>
<button type="button">Yes</button>
@@ -114,6 +114,7 @@
: this.session.BoardState.Player2Hand;
}
}
bool IsMyTurn => session?.BoardState.WhoseTurn == Perspective;
string? selectedPosition;
WhichPiece? selectedPiece;
@@ -138,21 +139,24 @@
}
return false;
}
async void OnClickTile(Piece? piece, string position)
{
if (SessionName == null) return;
if (SessionName == null || !IsMyTurn) return;
if (selectedPosition == null)
if (selectedPosition == null || piece?.Owner == Perspective)
{
// Select a position.
selectedPosition = position;
return;
}
else if (selectedPosition == position)
if (selectedPosition == position)
{
// Deselect the selected position.
selectedPosition = null;
return;
}
else if (piece != null)
if (piece == null)
{
if (ShouldPromptForPromotion(position) || ShouldPromptForPromotion(selectedPosition))
{
@@ -164,7 +168,7 @@
}
else
{
await ShogiApi.PostMove(SessionName, new MovePieceCommand
await ShogiApi.Move(SessionName, new MovePieceCommand
{
From = selectedPosition,
IsPromotion = false,
@@ -173,6 +177,7 @@
}
}
}
void OnClickHand(Piece piece)
{
selectedPiece = piece.WhichPiece;

View File

@@ -15,6 +15,7 @@
}
.board {
position: relative;
display: grid;
grid-template-areas:
"rank A9 B9 C9 D9 E9 F9 G9 H9 I9"
@@ -59,9 +60,10 @@
overflow: hidden; /* Because SVGs are shaped weird */
transition: filter linear 0.25s;
}
.tile[data-selected] {
filter: invert(0.8);
}
.tile[data-selected] {
filter: invert(0.8);
}
.ruler {
color: beige;
@@ -91,3 +93,20 @@
display: flex;
flex-wrap: wrap;
}
.promote-prompt {
display: none;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
border: 2px solid #444;
background-color: #eaeaea;
padding: 1rem;
box-shadow: 1px 1px 1px #444;
text-align: center;
}
.promote-prompt[data-visible="true"] {
display: block;
}

View File

@@ -42,7 +42,7 @@ public class PromotePrompt
if (command != null && sessionName != null)
{
command.IsPromotion = false;
return shogiApi.PostMove(sessionName, command);
return shogiApi.Move(sessionName, command);
}
return Task.CompletedTask;
}
@@ -51,7 +51,7 @@ public class PromotePrompt
if (command != null && sessionName != null)
{
command.IsPromotion = true;
return shogiApi.PostMove(sessionName, command);
return shogiApi.Move(sessionName, command);
}
return Task.CompletedTask;
}

View File

@@ -9,6 +9,6 @@
protected override void OnInitialized()
{
//ModalService.ShowLoginModal();
//Navigation.NavigateTo($"authentication/login?returnUrl={Uri.EscapeDataString(Navigation.Uri)}");
Navigation.NavigateTo($"authentication/login?returnUrl={Uri.EscapeDataString(Navigation.Uri)}");
}
}