create, read, playercount
This commit is contained in:
42
Shogi.Api/Extensions/ClaimsExtensions.cs
Normal file
42
Shogi.Api/Extensions/ClaimsExtensions.cs
Normal file
@@ -0,0 +1,42 @@
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace Shogi.Api.Extensions;
|
||||
|
||||
public static class ClaimsExtensions
|
||||
{
|
||||
private static readonly string MsalUsernameClaim = "preferred_username";
|
||||
|
||||
public static string? GetGuestUserId(this ClaimsPrincipal self)
|
||||
{
|
||||
return self.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value;
|
||||
}
|
||||
|
||||
public static string? DisplayName(this ClaimsPrincipal self)
|
||||
{
|
||||
return self.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value;
|
||||
}
|
||||
|
||||
public static bool IsMicrosoft(this ClaimsPrincipal self)
|
||||
{
|
||||
return self.HasClaim(c => c.Type == MsalUsernameClaim);
|
||||
}
|
||||
|
||||
public static string? GetMicrosoftUserId(this ClaimsPrincipal self)
|
||||
{
|
||||
return self.Claims.FirstOrDefault(c => c.Type == MsalUsernameClaim)?.Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the userId from claims after claims transformation has occurred.
|
||||
/// Throws if a shogi userid is not found.
|
||||
/// </summary>
|
||||
/// <exception cref="InvalidOperationException"></exception>
|
||||
public static string GetShogiUserId(this ClaimsPrincipal self)
|
||||
{
|
||||
var id = self.IsMicrosoft() ? self.GetMicrosoftUserId() : self.GetGuestUserId();
|
||||
|
||||
if (string.IsNullOrEmpty(id)) throw new InvalidOperationException("Shogi UserId not found in claims.");
|
||||
|
||||
return id;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user