first commit
This commit is contained in:
commit
b31e9a7261
38 files changed
+3822
No files matched your search
@@ -0,0 +1,48 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace Gateway.Api.Services;
|
||||
|
||||
public sealed class SessionService
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, DateTimeOffset> _sessions = new(StringComparer.Ordinal);
|
||||
|
||||
public string Create()
|
||||
{
|
||||
PruneExpired();
|
||||
var token = Convert.ToHexString(RandomNumberGenerator.GetBytes(32));
|
||||
_sessions[token] = DateTimeOffset.UtcNow.AddHours(12);
|
||||
return token;
|
||||
}
|
||||
|
||||
public bool IsValid(string? authorizationHeader)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(authorizationHeader) || !authorizationHeader.StartsWith("Bearer ", StringComparison.Ordinal))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var token = authorizationHeader[7..];
|
||||
return _sessions.TryGetValue(token, out var expiresAt) && expiresAt > DateTimeOffset.UtcNow;
|
||||
}
|
||||
|
||||
public void Remove(string? authorizationHeader)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(authorizationHeader) && authorizationHeader.StartsWith("Bearer ", StringComparison.Ordinal))
|
||||
{
|
||||
_sessions.TryRemove(authorizationHeader[7..], out _);
|
||||
}
|
||||
}
|
||||
|
||||
private void PruneExpired()
|
||||
{
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
foreach (var (token, expiresAt) in _sessions)
|
||||
{
|
||||
if (expiresAt <= now)
|
||||
{
|
||||
_sessions.TryRemove(token, out _);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user