47 lines
1.4 KiB
C#
47 lines
1.4 KiB
C#
using Gameboard.ShogiUI.Sockets.Repositories;
|
|
using Microsoft.AspNetCore.Authentication;
|
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
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;
|
|
|
|
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);
|
|
var success = await gameboardRepository.CreateUser(newUser);
|
|
if (success) user = newUser;
|
|
}
|
|
|
|
if (user != null)
|
|
{
|
|
return new ClaimsPrincipal(user.CreateClaimsIdentity());
|
|
}
|
|
}
|
|
return principal;
|
|
}
|
|
}
|
|
}
|