using System;
using System.Linq;
using System.Security.Claims;
using Jellyfin.Api.Constants;
namespace Jellyfin.Api.Helpers
{
///
/// Claim Helpers.
///
public static class ClaimHelpers
{
///
/// Get user id from claims.
///
/// Current claims principal.
/// User id.
public static Guid? GetUserId(in ClaimsPrincipal user)
{
var value = GetClaimValue(user, InternalClaimTypes.UserId);
return string.IsNullOrEmpty(value)
? null
: (Guid?)Guid.Parse(value);
}
///
/// Get device id from claims.
///
/// Current claims principal.
/// Device id.
public static string? GetDeviceId(in ClaimsPrincipal user)
=> GetClaimValue(user, InternalClaimTypes.DeviceId);
///
/// Get device from claims.
///
/// Current claims principal.
/// Device.
public static string? GetDevice(in ClaimsPrincipal user)
=> GetClaimValue(user, InternalClaimTypes.Device);
///
/// Get client from claims.
///
/// Current claims principal.
/// Client.
public static string? GetClient(in ClaimsPrincipal user)
=> GetClaimValue(user, InternalClaimTypes.Client);
///
/// Get version from claims.
///
/// Current claims principal.
/// Version.
public static string? GetVersion(in ClaimsPrincipal user)
=> GetClaimValue(user, InternalClaimTypes.Version);
///
/// Get token from claims.
///
/// Current claims principal.
/// Token.
public static string? GetToken(in ClaimsPrincipal user)
=> GetClaimValue(user, InternalClaimTypes.Token);
private static string? GetClaimValue(in ClaimsPrincipal user, string name)
{
return user?.Identities
.SelectMany(c => c.Claims)
.Where(claim => claim.Type.Equals(name, StringComparison.OrdinalIgnoreCase))
.Select(claim => claim.Value)
.FirstOrDefault();
}
}
}