pcut_uwp/PCUT/Http.Core/Contexts/UserContext.cs

87 lines
2.4 KiB
C#
Raw Permalink Normal View History

2024-08-21 16:02:56 +00:00
using Microsoft.IdentityModel.JsonWebTokens;
using PCUT.Entities;
using System;
namespace Http.Core.Contexts
{
public class UserContext : IDisposable
{
private UserContext() { }
private static readonly object _instanceLock = new object();
private static UserContext _instance;
public static UserContext Instance
{
get
{
if (_instance == null)
{
lock (_instanceLock)
{
if (_instance == null)
_instance = new UserContext();
}
}
return _instance;
}
}
2024-10-31 03:45:59 +00:00
public bool DebugFeaturesEnabled { get; set; } = false;
2024-08-21 16:02:56 +00:00
public UserProfile Profile { get; private set; }
public string AccessToken { get; private set; }
public string RefreshToken { get; private set; }
2024-10-31 03:45:59 +00:00
public DateTime? ExpiredTime { get; private set; }
2024-08-21 16:02:56 +00:00
public string DeviceId { get; private set; }
2024-10-30 10:00:07 +00:00
public string AppVersion { get; private set; }
2024-08-21 16:02:56 +00:00
public bool IsPermittedEdit => Profile.Role == "admin" || (Profile.IsPermittedEdit ?? false);
public void SetDeviceId(string deviceId)
{
if (DeviceId == null)
{
DeviceId = deviceId;
}
}
2024-10-30 10:00:07 +00:00
public void SetAppVersion(string appVersion)
{
if (AppVersion == null)
{
AppVersion = appVersion;
}
}
2024-08-21 16:02:56 +00:00
private readonly object _updateLock = new object();
internal void SetValue(string accessToken, string refreshToken, string userName = null)
{
lock(_updateLock)
{
AccessToken = accessToken;
RefreshToken = refreshToken;
try
{
var token = new JsonWebToken(AccessToken);
ExpiredTime = token.ValidTo != DateTime.MinValue ? token.ValidTo : (DateTime?)null;
}
catch { }
}
}
internal void SetProfile(UserProfile profile)
{
Profile = profile;
}
public void Dispose()
{
AccessToken = null;
RefreshToken = null;
DeviceId = null;
ExpiredTime = null;
Profile = null;
_instance = null;
}
}
}