Files
zszq-trs/YLErpDAL/Helpers/UserManager.cs
T
2024-05-09 14:06:26 +08:00

138 lines
3.8 KiB
C#

using System.Security.Claims;
using System.Security.Principal;
namespace YLErp.Helpers
{
public static class UserManager
{
private const string USER_ID = "userId";
private const string USER_NAME = "account";
private const string USER_TOKEN = "uuid";
private const string USER_LOGINTIME = "USER_LOGINTIME";
public static int GetUserId(this ClaimsPrincipal user)
{
return GetInt32(user, USER_ID, 0);
}
public static string GetUserIdStr(this ClaimsPrincipal user)
{
return GetData(user, USER_ID);
}
public static string GetUserName(this ClaimsPrincipal user)
{
return GetData(user, USER_NAME);
}
public static string GetUserToken(this ClaimsPrincipal user)
{
return GetData(user, USER_TOKEN);
}
public static DateTime GetUserLoginTime(this ClaimsPrincipal user)
{
var uxSeconds = GetInt64(user, USER_LOGINTIME, 0);
return DateTimeOffset.FromUnixTimeSeconds(uxSeconds).LocalDateTime;
}
/// <summary>
/// 保存用户数据到Cookie
/// </summary>
public static ClaimsIdentity CreateIdentity(string userid, string userName, string userToken)
{
var claims = new Claim[] {
new Claim(USER_ID, userid),
new Claim(USER_NAME, userName),
new Claim(USER_TOKEN, userToken),
new Claim(USER_LOGINTIME, DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString())
};
return new ClaimsIdentity(claims, "yc_identity");
}
#region-----帮助方法-----
private static string GetData(IPrincipal user, string key)
{
if (user == null)
{
return null;
}
return ((ClaimsIdentity)user.Identity).FindFirst(key)?.Value;
}
private static int GetInt32(ClaimsPrincipal user, string type, int defValue = 0)
{
if (string.IsNullOrEmpty(type))
{
throw new ArgumentNullException(nameof(type));
}
if (user == null)
{
return defValue;
}
var claim = ((ClaimsIdentity)user.Identity).FindFirst(type);
if (claim == null)
{
return defValue;
}
return int.TryParse(claim.Value, out var number) ? number : 0;
}
private static long GetInt64(ClaimsPrincipal user, string type, long defValue = 0)
{
if (string.IsNullOrEmpty(type))
{
throw new ArgumentNullException(nameof(type));
}
if (user == null)
{
return defValue;
}
var claim = ((ClaimsIdentity)user.Identity).FindFirst(type);
if (claim == null)
{
return defValue;
}
return long.TryParse(claim.Value, out var number) ? number : 0;
}
private static void SetData(ClaimsPrincipal user, string type, string value)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
if (string.IsNullOrEmpty(type))
{
throw new ArgumentNullException(nameof(type));
}
var identity = (ClaimsIdentity)user.Identity;
var claim = identity.FindFirst(type);
if (claim != null)
{
identity.TryRemoveClaim(claim);
}
if (value != null)
{
identity.AddClaim(new Claim(type, value ?? string.Empty));
}
}
#endregion
}
}