Skip to content

Commit

Permalink
prevent logged in context from being used outside of the request it's…
Browse files Browse the repository at this point in the history
… related to. Fix issue of user context leaking from old requests.
  • Loading branch information
hahn-kev committed Jul 5, 2023
1 parent ac64855 commit 1733e73
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 13 deletions.
17 changes: 14 additions & 3 deletions backend/LexBoxApi/Auth/LoggedInContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace LexBoxApi.Auth;

public class LoggedInContext
public class LoggedInContext : IDisposable
{
private readonly Lazy<LexAuthUser> _user;

Expand All @@ -21,5 +21,16 @@ public LoggedInContext(IHttpContextAccessor httpContextAccessor)
/// <summary>
/// get the logged in user, will throw an exception if the user is not logged in
/// </summary>
public LexAuthUser User => _user.Value;
}
public LexAuthUser User =>
_disposed
? throw new ObjectDisposedException(nameof(LoggedInContext),
"this context has been disposed because the request that created it has finished")
: _user.Value;

private bool _disposed;

public void Dispose()
{
_disposed = true;
}
}
2 changes: 2 additions & 0 deletions backend/LexBoxApi/GraphQL/GraphQlSetupKernel.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using HotChocolate.Data.Projections.Expressions;
using HotChocolate.Diagnostics;
using LexBoxApi.Auth;
using LexBoxApi.Config;
using LexCore.ServiceInterfaces;
using LexData;
Expand All @@ -17,6 +18,7 @@ public static void AddLexGraphQL(this IServiceCollection services, IWebHostEnvir
.InitializeOnStartup()
.RegisterDbContext<LexBoxDbContext>()
.RegisterService<IHgService>()
.RegisterService<LoggedInContext>()
.AddSorting(descriptor =>
{
descriptor.AddDefaults();
Expand Down
14 changes: 4 additions & 10 deletions backend/LexBoxApi/GraphQL/LexQueries.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,12 @@ namespace LexBoxApi.GraphQL;
[QueryType]
public class LexQueries
{
private readonly LoggedInContext _loggedInContext;

public LexQueries(LoggedInContext loggedInContext)
{
_loggedInContext = loggedInContext;
}

[UseProjection]
[UseSorting]
public IQueryable<Project> MyProjects(LexBoxDbContext context)
public IQueryable<Project> MyProjects(LoggedInContext loggedInContext, LexBoxDbContext context)
{
var projectCodes = _loggedInContext.User.Projects.Select(p => p.Code);
var projectCodes = loggedInContext.User.Projects.Select(p => p.Code);
return context.Projects.Where(p => projectCodes.Contains(p.Code));
}

Expand Down Expand Up @@ -50,8 +44,8 @@ public IQueryable<User> Users(LexBoxDbContext context)
return context.Users;
}

public LexAuthUser Me()
public LexAuthUser Me(LoggedInContext loggedInContext)
{
return _loggedInContext.User;
return loggedInContext.User;
}
}

0 comments on commit 1733e73

Please sign in to comment.