using System;
using System.Security.Claims;
using Dpz.Core.EnumLibrary;
namespace Dpz.Core.Public.ViewModel
{
public static class ViewModelHelper
{
/// <summary>
/// 根据Identity反射获取当前用户信息
/// 未授权用户返回 null
/// </summary>
/// <param name="principal"></param>
/// <returns></returns>
public static VmUserInfo UserInfo(this ClaimsPrincipal principal)
{
if (principal.Identity.IsAuthenticated)
{
var userInfo = new VmUserInfo();
foreach (var claims in principal.Claims)
{
var property = typeof(VmUserInfo).GetProperty(claims.Type);
if (property == null) continue;
if (property.PropertyType == typeof(DateTime?))
{
property.SetValue(userInfo, DateTime.Parse(claims.Value));
}
else if (property.PropertyType == typeof(Sex))
{
var sex = Enum.Parse(typeof(Sex), claims.Value);
property.SetValue(userInfo, sex);
}
else if (property.PropertyType == typeof(bool?))
{
bool.TryParse(claims.Value, out var result);
property.SetValue(userInfo, result);
}
else if (property.PropertyType == typeof(Permissions?))
{
if (Enum.TryParse(claims.Value, out Permissions permissions))
{
property.SetValue(userInfo, permissions);
}
}
else
{
typeof(VmUserInfo).GetProperty(claims.Type)?.SetValue(userInfo, claims.Value);
}
}
return userInfo;
}
return null;
}
}
}