diff options
Diffstat (limited to 'Services/UserService.cs')
| -rw-r--r-- | Services/UserService.cs | 86 |
1 files changed, 51 insertions, 35 deletions
diff --git a/Services/UserService.cs b/Services/UserService.cs index 1a2bd8f..39b1963 100644 --- a/Services/UserService.cs +++ b/Services/UserService.cs @@ -4,50 +4,30 @@ using Microsoft.EntityFrameworkCore; namespace HyperBooru.Services; public interface IUserService { - public bool ShowNsfw { get; set; } - - public event EventHandler<bool> ShowNsfwChanged; - - public User User { get; } + public UserSessionState UserSessionState { get; } } public class UserService : IUserService { - public bool ShowNsfw { - get => showNsfw; - set { - showNsfw = value; - ShowNsfwChanged?.Invoke(this, value); - } - } + public UserSessionState UserSessionState => + globalUserService.GetSessionState(httpContext.Session.Id); - public User User { - get { - if(user is not null) - return user; - using var db = dbFactory.CreateDbContext(); - int id = int.Parse(httpContextAccessor - .HttpContext!.User.Claims - .First(c => c.Type == "ObjectId") - .Value); - return user = db.Users.Find(id)!; - } - } - - public event EventHandler<bool> ShowNsfwChanged; - - private bool showNsfw = false; - - private User? user; - - private IDbContextFactory<HBContext> dbFactory; private IHttpContextAccessor httpContextAccessor; + private IGlobalUserService globalUserService; + + private HttpContext httpContext => + httpContextAccessor.HttpContext!; public UserService( - IDbContextFactory<HBContext> dbFactory, - IHttpContextAccessor httpContextAccessor) { + IHttpContextAccessor httpContextAccessor, + IGlobalUserService globalUserService) { - this.dbFactory = dbFactory; this.httpContextAccessor = httpContextAccessor; + this.globalUserService = globalUserService; + + // HTTP context session states are discarded if no values + // are set. Set a dummy value so that the session state + // will not be discarded later when we actually need it. + httpContext.Session.SetInt32("Persist", 1); } public static string HashPassword(string password) => @@ -59,3 +39,39 @@ public class UserService : IUserService { 100_000, 512 / 8)); } + +public interface IGlobalUserService { + public UserSessionState GetSessionState(string id); +} + +public class GlobalUserService : IGlobalUserService { + // TODO: prune this list periodically + private Dictionary<string, UserSessionState> sessionStates = new(); + + public UserSessionState GetSessionState(string id) { + sessionStates.TryGetValue(id, out var state); + + if(state is null) { + state = new(); + sessionStates[id] = state; + } + + return state; + } +} + +public record UserSessionState { + public event UserSessionStateChange OnStateChange; + + public bool ShowNsfw { + get => showNsfw; + set { + showNsfw = value; + OnStateChange.Invoke(this); + } + } + + private bool showNsfw = false; +} + +public delegate void UserSessionStateChange(UserSessionState sessionState); |
