using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using IdentityModel;
using IdentityServer4;
using Kyoo.Abstractions.Models;
namespace Kyoo.Authentication
{
///
/// Extension methods.
///
public static class Extensions
{
///
/// Get claims of an user.
///
/// The user concerned
/// The list of claims the user has
public static ICollection GetClaims(this User user)
{
return new[]
{
new Claim(JwtClaimTypes.Subject, user.ID.ToString()),
new Claim(JwtClaimTypes.Name, user.Username),
new Claim(JwtClaimTypes.Picture, $"api/account/picture/{user.Slug}")
};
}
///
/// Convert a user to an .
///
/// The user to convert
/// The corresponding identity server user.
public static IdentityServerUser ToIdentityUser(this User user)
{
return new(user.ID.ToString())
{
DisplayName = user.Username,
AdditionalClaims = new[] { new Claim("permissions", string.Join(',', user.Permissions)) }
};
}
///
/// Get the permissions of an user.
///
/// The user
/// The list of permissions
public static ICollection GetPermissions(this ClaimsPrincipal user)
{
return user.Claims.FirstOrDefault(x => x.Type == "permissions")?.Value.Split(',');
}
}
}