Split Common from Messages
This commit is contained in:
42
src/Web/Common/Shared.cs
Normal file
42
src/Web/Common/Shared.cs
Normal file
@@ -0,0 +1,42 @@
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace Hutopy.Web.Common;
|
||||
|
||||
public class Shared(string claimName) : Exception;
|
||||
|
||||
public static class ClaimsPrincipalExtensions
|
||||
{
|
||||
public static Guid GetUserId(this ClaimsPrincipal claims)
|
||||
{
|
||||
return (Guid)claims.GetFirstValue<Guid>(ClaimTypes.NameIdentifier);
|
||||
}
|
||||
|
||||
public static string GetFirstName(this ClaimsPrincipal claims)
|
||||
{
|
||||
return (string)claims.GetFirstValue<string>(ClaimTypes.GivenName);
|
||||
}
|
||||
|
||||
public static string GetLastName(this ClaimsPrincipal claims)
|
||||
{
|
||||
return (string)claims.GetFirstValue<string>(ClaimTypes.Surname);
|
||||
}
|
||||
|
||||
public static string GetEmail(this ClaimsPrincipal claims)
|
||||
{
|
||||
return (string)claims.GetFirstValue<string>(ClaimTypes.Email);
|
||||
}
|
||||
|
||||
public static object GetFirstValue<TValue>(this ClaimsPrincipal claims, string key)
|
||||
{
|
||||
var claim = claims.FindFirst(key);
|
||||
|
||||
if (claim is null) throw new Shared(key);
|
||||
|
||||
if (typeof(TValue) == typeof(Guid))
|
||||
{
|
||||
return Guid.Parse(claim.Value);
|
||||
}
|
||||
|
||||
return Convert.ChangeType(claim.Value, typeof(TValue));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user