using System;
using System.Linq;
using System.Security.Claims;
using Jellyfin.Api.Constants;
namespace Jellyfin.Api.Extensions;
///
/// Extensions for .
///
public static class ClaimsPrincipalExtensions
{
///
/// Get user id from claims.
///
/// Current claims principal.
/// User id.
public static Guid GetUserId(this ClaimsPrincipal user)
{
var value = GetClaimValue(user, InternalClaimTypes.UserId);
return string.IsNullOrEmpty(value)
? default
: Guid.Parse(value);
}
///
/// Get device id from claims.
///
/// Current claims principal.
/// Device id.
public static string? GetDeviceId(this ClaimsPrincipal user)
=> GetClaimValue(user, InternalClaimTypes.DeviceId);
///
/// Get device from claims.
///
/// Current claims principal.
/// Device.
public static string? GetDevice(this ClaimsPrincipal user)
=> GetClaimValue(user, InternalClaimTypes.Device);
///
/// Get client from claims.
///
/// Current claims principal.
/// Client.
public static string? GetClient(this ClaimsPrincipal user)
=> GetClaimValue(user, InternalClaimTypes.Client);
///
/// Get version from claims.
///
/// Current claims principal.
/// Version.
public static string? GetVersion(this ClaimsPrincipal user)
=> GetClaimValue(user, InternalClaimTypes.Version);
///
/// Get token from claims.
///
/// Current claims principal.
/// Token.
public static string? GetToken(this ClaimsPrincipal user)
=> GetClaimValue(user, InternalClaimTypes.Token);
///
/// Gets a flag specifying whether the request is using an api key.
///
/// Current claims principal.
/// The flag specifying whether the request is using an api key.
public static bool GetIsApiKey(this ClaimsPrincipal user)
{
var claimValue = GetClaimValue(user, InternalClaimTypes.IsApiKey);
return !string.IsNullOrEmpty(claimValue)
&& bool.TryParse(claimValue, out var parsedClaimValue)
&& parsedClaimValue;
}
private static string? GetClaimValue(in ClaimsPrincipal user, string name)
=> user.Claims.FirstOrDefault(claim => claim.Type.Equals(name, StringComparison.OrdinalIgnoreCase))?.Value;
}