39 lines
1.0 KiB
C#
39 lines
1.0 KiB
C#
using MxGateway.Server.Security.Authentication;
|
|
|
|
namespace MxGateway.Server.Security.Authorization;
|
|
|
|
public sealed class GatewayRequestIdentityAccessor : IGatewayRequestIdentityAccessor
|
|
{
|
|
private readonly AsyncLocal<ApiKeyIdentity?> currentIdentity = new();
|
|
|
|
public ApiKeyIdentity? Current => currentIdentity.Value;
|
|
|
|
public IDisposable Push(ApiKeyIdentity identity)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(identity);
|
|
|
|
ApiKeyIdentity? previousIdentity = currentIdentity.Value;
|
|
currentIdentity.Value = identity;
|
|
|
|
return new IdentityScope(this, previousIdentity);
|
|
}
|
|
|
|
private sealed class IdentityScope(
|
|
GatewayRequestIdentityAccessor accessor,
|
|
ApiKeyIdentity? previousIdentity) : IDisposable
|
|
{
|
|
private bool disposed;
|
|
|
|
public void Dispose()
|
|
{
|
|
if (disposed)
|
|
{
|
|
return;
|
|
}
|
|
|
|
accessor.currentIdentity.Value = previousIdentity;
|
|
disposed = true;
|
|
}
|
|
}
|
|
}
|