This commit is contained in:
2022-06-22 18:29:19 -05:00
parent 770344422d
commit 02e64daec5
9 changed files with 101 additions and 105 deletions

View File

@@ -176,7 +176,7 @@ namespace Gameboard.ShogiUI.Sockets.Controllers
}
[HttpGet]
public async Task<GetSessionsResponse> GetSessions()
public async Task<ActionResult<GetSessionsResponse>> GetSessions()
{
var user = await ReadUserOrThrow();
var sessions = await gameboardRepository.ReadSessionMetadatas();
@@ -190,11 +190,11 @@ namespace Gameboard.ShogiUI.Sockets.Controllers
.Select(s => mapper.Map(s))
.ToList();
return new GetSessionsResponse
return Ok(new GetSessionsResponse
{
PlayerHasJoinedSessions = sessionsJoinedByUser,
AllOtherSessions = sessionsNotJoinedByUser
};
});
}
[HttpPut("{gameName}")]

View File

@@ -1,28 +1,29 @@
using System.Linq;
using System.Security.Claims;
using System.Security.Claims;
namespace Gameboard.ShogiUI.Sockets.Extensions
{
public static class Extensions
{
public static string? UserId(this ClaimsPrincipal self)
{
return self.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value;
}
public static class Extensions
{
private static readonly string MsalUsernameClaim = "preferred_username";
public static string? DisplayName(this ClaimsPrincipal self)
{
return self.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value;
}
public static string? UserId(this ClaimsPrincipal self)
{
return self.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value;
}
public static bool IsGuest(this ClaimsPrincipal self)
{
return self.HasClaim(c => c.Type == ClaimTypes.Role && c.Value == "Guest");
}
public static string? DisplayName(this ClaimsPrincipal self)
{
return self.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value;
}
public static string ToCamelCase(this string self)
{
return char.ToLowerInvariant(self[0]) + self[1..];
}
}
public static bool IsMicrosoft(this ClaimsPrincipal self)
{
return self.HasClaim(c => c.Type == MsalUsernameClaim);
}
public static string ChangeFirstCharacterToLowerCase(this string self)
{
return char.ToLowerInvariant(self[0]) + self[1..];
}
}
}

View File

@@ -31,9 +31,9 @@ namespace Gameboard.ShogiUI.Sockets.Managers
throw new InvalidOperationException("Cannot create user from given claims.");
}
var user = principal.IsGuest()
? User.CreateGuestUser(id)
: User.CreateMsalUser(id);
var user = principal.IsMicrosoft()
? User.CreateMsalUser(id)
: User.CreateGuestUser(id);
await repository.CreateUser(user);
return user;

View File

@@ -1,8 +1,6 @@
using Gameboard.ShogiUI.Sockets.Repositories.CouchModels;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Security.Claims;
@@ -62,7 +60,6 @@ namespace Gameboard.ShogiUI.Sockets.Models
new Claim(ClaimTypes.NameIdentifier, Id),
new Claim(ClaimTypes.Name, DisplayName),
new Claim(ClaimTypes.Role, "Guest"),
new Claim(ClaimTypes.Role, "Shogi") // The Shogi role grants access to api controllers.
};
return new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
}
@@ -72,7 +69,6 @@ namespace Gameboard.ShogiUI.Sockets.Models
{
new Claim(ClaimTypes.NameIdentifier, Id),
new Claim(ClaimTypes.Name, DisplayName),
new Claim(ClaimTypes.Role, "Shogi") // The Shogi role grants access to api controllers.
};
return new ClaimsIdentity(claims, JwtBearerDefaults.AuthenticationScheme);
}

View File

@@ -169,7 +169,7 @@ namespace Gameboard.ShogiUI.Sockets
services.AddSingleton<IValidator<JoinGameRequest>, JoinGameRequestValidator>();
services.AddSingleton<ISocketService, SocketService>();
services.AddTransient<IGameboardRepository, GameboardRepository>();
services.AddSingleton<IClaimsTransformation, ShogiUserClaimsTransformer>();
services.AddTransient<IClaimsTransformation, ShogiUserClaimsTransformer>();
services.AddHttpClient("couchdb", c =>
{
var base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes("admin:admin"));

View File

@@ -1,43 +1,44 @@
using Gameboard.ShogiUI.Sockets.Repositories;
using Gameboard.ShogiUI.Sockets.Extensions;
using Gameboard.ShogiUI.Sockets.Repositories;
using Microsoft.AspNetCore.Authentication;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
namespace Gameboard.ShogiUI.Sockets
{
/// <summary>
/// Standardizes the claims from third party issuers. Also registers new msal users in the database.
/// </summary>
public class ShogiUserClaimsTransformer : IClaimsTransformation
{
private static readonly string MsalUsernameClaim = "preferred_username";
private readonly IGameboardRepository gameboardRepository;
/// <summary>
/// Standardizes the claims from third party issuers. Also registers new msal users in the database.
/// </summary>
public class ShogiUserClaimsTransformer : IClaimsTransformation
{
private readonly IGameboardRepository gameboardRepository;
public ShogiUserClaimsTransformer(IGameboardRepository gameboardRepository)
{
this.gameboardRepository = gameboardRepository;
}
public ShogiUserClaimsTransformer(IGameboardRepository gameboardRepository)
{
this.gameboardRepository = gameboardRepository;
}
public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
var nameClaim = principal.Claims.FirstOrDefault(c => c.Type == MsalUsernameClaim);
if (nameClaim != default)
{
var user = await gameboardRepository.ReadUser(nameClaim.Value);
if (user == null)
{
var newUser = Models.User.CreateMsalUser(nameClaim.Value);
await gameboardRepository.CreateUser(newUser);
user = newUser;
}
public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
var id = principal.UserId();
if (!string.IsNullOrWhiteSpace(id))
{
var user = await gameboardRepository.ReadUser(id);
if (user == null)
{
var newUser = principal.IsMicrosoft()
? Models.User.CreateMsalUser(id)
: Models.User.CreateGuestUser(id);
if (user != null)
{
return new ClaimsPrincipal(user.CreateClaimsIdentity());
}
}
return principal;
}
}
await gameboardRepository.CreateUser(newUser);
user = newUser;
}
if (user != null)
{
return new ClaimsPrincipal(user.CreateClaimsIdentity());
}
}
return principal;
}
}
}

View File

@@ -1,43 +1,44 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<UserSecretsId>96d6281d-a75b-4181-b535-ea34b26dc8a2</UserSecretsId>
</PropertyGroup>
<IsPackable>false</IsPackable>
<UserSecretsId>96d6281d-a75b-4181-b535-ea34b26dc8a2</UserSecretsId>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<None Remove="appsettings.json" />
</ItemGroup>
<ItemGroup>
<None Remove="appsettings.json" />
</ItemGroup>
<ItemGroup>
<Content Include="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<Content Include="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<PackageReference Include="FluentAssertions" Version="6.7.0" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="6.0.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="6.0.1" />
<PackageReference Include="Microsoft.Identity.Client" Version="4.44.0" />
<PackageReference Include="Microsoft.Net.Http.Headers" Version="2.2.8" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.2.0" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="3.1.2">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<PackageReference Include="FluentAssertions" Version="6.7.0" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="6.0.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="6.0.1" />
<PackageReference Include="Microsoft.Identity.Client" Version="4.44.0" />
<PackageReference Include="Microsoft.Net.Http.Headers" Version="2.2.8" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.2.0" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="3.1.2">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
</Project>

View File

@@ -44,9 +44,6 @@ namespace Shogi.AcceptanceTests.TestSetup
authResult.AccessToken.Should().NotBeNullOrEmpty();
Service.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
var response = await Service.GetAsync("Socket/Token");
response.IsSuccessStatusCode.Should().BeTrue(because: "AAT client should create an account for tests.");
}
protected virtual void Dispose(bool disposing)

View File

@@ -9,7 +9,7 @@
<ItemGroup>
<PackageReference Include="FluentAssertions" Version="6.2.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.1.0-preview-20211130-02" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.2.0" />
<PackageReference Include="xunit" Version="2.4.2-pre.12" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>