aboutsummaryrefslogtreecommitdiff
path: root/Libs/VNLib.Plugins.Essentials.Sessions.OAuth/O2SessionProviderEntry.cs
diff options
context:
space:
mode:
Diffstat (limited to 'Libs/VNLib.Plugins.Essentials.Sessions.OAuth/O2SessionProviderEntry.cs')
-rw-r--r--Libs/VNLib.Plugins.Essentials.Sessions.OAuth/O2SessionProviderEntry.cs94
1 files changed, 28 insertions, 66 deletions
diff --git a/Libs/VNLib.Plugins.Essentials.Sessions.OAuth/O2SessionProviderEntry.cs b/Libs/VNLib.Plugins.Essentials.Sessions.OAuth/O2SessionProviderEntry.cs
index f4462a4..7e72714 100644
--- a/Libs/VNLib.Plugins.Essentials.Sessions.OAuth/O2SessionProviderEntry.cs
+++ b/Libs/VNLib.Plugins.Essentials.Sessions.OAuth/O2SessionProviderEntry.cs
@@ -27,12 +27,14 @@ using System.Text.Json;
using VNLib.Net.Http;
using VNLib.Utils.Logging;
using VNLib.Utils.Extensions;
-using VNLib.Data.Caching.Extensions;
+using VNLib.Data.Caching;
+using VNLib.Plugins.Sessions.Cache.Client;
using VNLib.Plugins.Essentials.Oauth.Tokens;
using VNLib.Plugins.Essentials.Oauth.Applications;
using VNLib.Plugins.Essentials.Sessions.OAuth;
using VNLib.Plugins.Essentials.Sessions.Runtime;
using VNLib.Plugins.Essentials.Sessions.OAuth.Endpoints;
+using VNLib.Plugins.Extensions.VNCache;
using VNLib.Plugins.Extensions.Loading;
using VNLib.Plugins.Extensions.Loading.Routing;
using VNLib.Plugins.Extensions.Loading.Sql;
@@ -44,7 +46,6 @@ namespace VNLib.Plugins.Essentials.Sessions.Oauth
public sealed class O2SessionProviderEntry : IRuntimeSessionProvider
{
- const string VNCACHE_CONFIG_KEY = "vncache";
const string OAUTH2_CONFIG_KEY = "oauth2";
private OAuth2SessionProvider? _sessions;
@@ -63,14 +64,11 @@ namespace VNLib.Plugins.Essentials.Sessions.Oauth
void IRuntimeSessionProvider.Load(PluginBase plugin, ILogProvider localized)
{
- //Try get vncache config element
- IReadOnlyDictionary<string, JsonElement> cacheConfig = plugin.GetConfig(VNCACHE_CONFIG_KEY);
-
- IReadOnlyDictionary<string, JsonElement> oauth2Config = plugin.GetConfig(OAUTH2_CONFIG_KEY);
+ IReadOnlyDictionary<string, JsonElement> oauth2Config = plugin.GetConfigForType<OAuth2SessionProvider>();
//Optional application jwt token
Task<JsonDocument?> jwtTokenSecret = plugin.TryGetSecretAsync("application_token_key")
- .ContinueWith(static t => t.Result == null ? null : t.Result.GetJsonDocument(), TaskScheduler.Default);
+ .ContinueWith(static t => t.Result?.GetJsonDocument(), TaskScheduler.Default);
//Access token endpoint is optional
if (oauth2Config.TryGetValue("token_path", out JsonElement el))
@@ -89,74 +87,38 @@ namespace VNLib.Plugins.Essentials.Sessions.Oauth
plugin.Route<RevocationEndpoint>();
}
- //Run
- _ = plugin.DeferTask(() => CacheWokerDoWorkAsync(plugin, localized, cacheConfig, oauth2Config), 100);
-
- }
+ int cacheLimit = oauth2Config["cache_size"].GetInt32();
+ int maxTokensPerApp = oauth2Config["max_tokens_per_app"].GetInt32();
+ int sessionIdSize = (int)oauth2Config["access_token_size"].GetUInt32();
+ TimeSpan tokenValidFor = oauth2Config["token_valid_for_sec"].GetTimeSpan(TimeParseType.Seconds);
+ TimeSpan cleanupInterval = oauth2Config["gc_interval_sec"].GetTimeSpan(TimeParseType.Seconds);
+ string sessionIdPrefix = oauth2Config["cache_prefix"].GetString() ?? throw new KeyNotFoundException($"Missing required key 'cache_prefix' in '{OAUTH2_CONFIG_KEY}' config");
- private async Task<IOAuth2TokenResult?> CreateTokenDelegateAsync(HttpEntity entity, UserApplication app, CancellationToken cancellation)
- {
- return await _sessions!.CreateAccessTokenAsync(entity, app, cancellation).ConfigureAwait(false);
- }
+ //init the id provider
+ OAuth2SessionIdProvider idProv = new(sessionIdPrefix, maxTokensPerApp, sessionIdSize, tokenValidFor);
- /*
- * Starts and monitors the VNCache connection
- */
+ //Get shared global-cache
+ IGlobalCacheProvider globalCache = plugin.GetGlobalCache();
- private async Task CacheWokerDoWorkAsync(PluginBase plugin, ILogProvider localized,
- IReadOnlyDictionary<string, JsonElement> cacheConfig,
- IReadOnlyDictionary<string, JsonElement> oauth2Config)
- {
- //Init cache client
- using VnCacheClient cache = new(plugin.IsDebug() ? localized : null, Utils.Memory.Memory.Shared);
-
- try
- {
- int cacheLimit = oauth2Config["cache_size"].GetInt32();
- int maxTokensPerApp = oauth2Config["max_tokens_per_app"].GetInt32();
- int sessionIdSize = (int)oauth2Config["access_token_size"].GetUInt32();
- TimeSpan tokenValidFor = oauth2Config["token_valid_for_sec"].GetTimeSpan(TimeParseType.Seconds);
- TimeSpan cleanupInterval = oauth2Config["gc_interval_sec"].GetTimeSpan(TimeParseType.Seconds);
- string sessionIdPrefix = oauth2Config["cache_prefix"].GetString() ?? throw new KeyNotFoundException($"Missing required key 'cache_prefix' in '{OAUTH2_CONFIG_KEY}' config");
-
- //init the id provider
- OAuth2SessionIdProvider idProv = new(sessionIdPrefix, maxTokensPerApp, sessionIdSize, tokenValidFor);
-
- //Try loading config
- await cache.LoadConfigAsync(plugin, cacheConfig);
+ //Create cache store from global cache
+ GlobalCacheStore cacheStore = new(globalCache);
- //Init session provider now that client is loaded
- _sessions = new(cache.Resource!, cacheLimit, 100, idProv, plugin.GetContextOptions());
+ //Init session provider now that client is loaded
+ _sessions = new(cacheStore, cacheLimit, 100, idProv, plugin.GetContextOptions());
- //Schedule cleanup interval with the plugin scheduler
- plugin.ScheduleInterval(_sessions, cleanupInterval);
+ //Schedule cleanup interval with the plugin scheduler
+ plugin.ScheduleInterval(_sessions, cleanupInterval);
- localized.Information("Session provider loaded");
+ //Wait and cleanup expired sessions
+ _ = plugin.DeferTask(() => _sessions.CleanupExpiredSessionsAsync(localized, plugin.UnloadToken), 1000);
- //Run and wait for exit
- await cache.RunAsync(localized, plugin.UnloadToken);
+ localized.Information("Session provider loaded");
- }
- catch (OperationCanceledException)
- {}
- catch (KeyNotFoundException e)
- {
- localized.Error("Missing required configuration variable for VnCache client: {0}", e.Message);
- }
- catch(FBMServerNegiationException fne)
- {
- localized.Error("Failed to negotiate connection with cache server {reason}", fne.Message);
- }
- catch (Exception ex)
- {
- localized.Error(ex, "Cache client error occured in session provider");
- }
- finally
- {
- _sessions = null;
- }
+ }
- localized.Information("Cache client exited");
+ private async Task<IOAuth2TokenResult?> CreateTokenDelegateAsync(HttpEntity entity, UserApplication app, CancellationToken cancellation)
+ {
+ return await _sessions!.CreateAccessTokenAsync(entity, app, cancellation).ConfigureAwait(false);
}
}
} \ No newline at end of file