using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Jellyfin.Plugin.SSO_Auth.Api;
using StackExchange.Redis;
namespace Jellyfin.Plugin.SSO_Auth.State;
///
/// A Redis/Valkey backed . Every login-path operation addresses a single
/// key so the store works unchanged against a cluster-mode deployment, and expiry is a key TTL rather
/// than a sweep, so a state times out even if no further login ever happens.
///
public sealed class RedisSsoStateStore : ISsoStateStore
{
///
/// The prefix every OpenID state key is stored under.
///
public const string KeyPrefix = "jellyfin:sso:oid:state:";
private readonly IConnectionMultiplexer _redis;
private readonly IDatabase _database;
///
/// Initializes a new instance of the class.
///
/// The connection multiplexer shared with the server.
public RedisSsoStateStore(IConnectionMultiplexer redis)
{
ArgumentNullException.ThrowIfNull(redis);
_redis = redis;
_database = redis.GetDatabase();
}
///
public Task CreateAsync(TimedAuthorizeState state, TimeSpan expiry)
{
return WriteAsync(state, expiry);
}
///
public Task UpdateAsync(TimedAuthorizeState state, TimeSpan expiry)
{
return WriteAsync(state, expiry);
}
///
public async Task GetAsync(string state)
{
if (string.IsNullOrEmpty(state))
{
return null;
}
var payload = await _database.StringGetAsync(KeyFor(state)).ConfigureAwait(false);
return SsoStateSerializer.Deserialize(payload);
}
///
public async Task ConsumeAsync(string state)
{
if (string.IsNullOrEmpty(state))
{
return null;
}
var payload = await _database.StringGetDeleteAsync(KeyFor(state)).ConfigureAwait(false);
return SsoStateSerializer.Deserialize(payload);
}
///
public async Task> ListAsync()
{
var states = new List();
foreach (var endpoint in _redis.GetEndPoints())
{
var server = _redis.GetServer(endpoint);
if (!server.IsConnected || server.IsReplica)
{
continue;
}
await foreach (var key in server.KeysAsync(pattern: KeyPrefix + "*").ConfigureAwait(false))
{
var parsed = SsoStateSerializer.Deserialize(await _database.StringGetAsync(key).ConfigureAwait(false));
if (parsed is not null)
{
states.Add(parsed);
}
}
}
return states;
}
private static RedisKey KeyFor(string state)
{
return KeyPrefix + state;
}
private Task WriteAsync(TimedAuthorizeState state, TimeSpan expiry)
{
ArgumentNullException.ThrowIfNull(state);
return _database.StringSetAsync(
KeyFor(state.State.State),
SsoStateSerializer.Serialize(state),
expiry,
keepTtl: false,
when: When.Always,
flags: CommandFlags.None);
}
}