Skip to content

Commit

Permalink
Merge pull request #3982 from sbwalker/dev
Browse files Browse the repository at this point in the history
improve caching for sites with many registered users
  • Loading branch information
sbwalker authored Mar 12, 2024
2 parents 1d9f970 + 0c8dc63 commit 09ad560
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 5 deletions.
13 changes: 13 additions & 0 deletions Oqtane.Server/Extensions/ClaimsPrincipalExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Linq;
using System.Security.Claims;
using Oqtane.Shared;

namespace Oqtane.Extensions
{
Expand Down Expand Up @@ -70,5 +71,17 @@ public static int SiteId(this ClaimsPrincipal claimsPrincipal)
}
return -1;
}

public static bool IsOnlyInRole(this ClaimsPrincipal claimsPrincipal, string role)
{
var identity = claimsPrincipal.Identities.FirstOrDefault(item => item.AuthenticationType == Constants.AuthenticationScheme);
if (identity != null)
{
// check if user has role claim specified and no other role claims
return identity.Claims.Any(item => item.Type == ClaimTypes.Role && item.Value == role) &&
!identity.Claims.Any(item => item.Type == ClaimTypes.Role && item.Value != role);
}
return false;
}
}
}
23 changes: 18 additions & 5 deletions Oqtane.Server/Services/SiteService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,19 +64,32 @@ public async Task<Site> GetSiteAsync(int siteId)
{
if (!_accessor.HttpContext.User.Identity.IsAuthenticated)
{
// unauthenticated
return await _cache.GetOrCreateAsync($"site:{_accessor.HttpContext.GetAlias().SiteKey}", async entry =>
{
entry.SlidingExpiration = TimeSpan.FromMinutes(30);
return await GetSite(siteId);
}, true);
}
else // authenticated - cached per user
else // authenticated
{
return await _cache.GetOrCreateAsync($"site:{_accessor.HttpContext.GetAlias().SiteKey}:{_accessor.HttpContext.User.UserId}", async entry =>
// is only in registered users role - cache by role
if (_accessor.HttpContext.User.IsOnlyInRole(RoleNames.Registered))
{
entry.SlidingExpiration = TimeSpan.FromMinutes(30);
return await GetSite(siteId);
}, true);
return await _cache.GetOrCreateAsync($"site:{_accessor.HttpContext.GetAlias().SiteKey}:{RoleNames.Registered}", async entry =>
{
entry.SlidingExpiration = TimeSpan.FromMinutes(30);
return await GetSite(siteId);
}, true);
}
else // cache by user
{
return await _cache.GetOrCreateAsync($"site:{_accessor.HttpContext.GetAlias().SiteKey}:{_accessor.HttpContext.User.UserId}", async entry =>
{
entry.SlidingExpiration = TimeSpan.FromMinutes(30);
return await GetSite(siteId);
}, true);
}
}
}

Expand Down

0 comments on commit 09ad560

Please sign in to comment.