SessionAudit

This commit is contained in:
dingo
2025-11-10 14:43:19 -05:00
parent 53a8ebb1d6
commit 9c75aaafc9
5 changed files with 91 additions and 6 deletions
+10
View File
@@ -0,0 +1,10 @@
using System.Threading;
using System.Threading.Tasks;
namespace Server.Services.Auth;
public interface ISessionAudit
{
/// <summary>Marks the session as ended (or deletes it) for this account+token.</summary>
Task EndAsync(ulong accountId, string token, string reason, CancellationToken ct = default);
}
+64
View File
@@ -0,0 +1,64 @@
using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Server.Data;
namespace Server.Services.Auth;
public sealed class SessionAudit : ISessionAudit
{
private readonly GameDbContext _db;
private readonly ILogger<SessionAudit> _log;
public SessionAudit(GameDbContext db, ILogger<SessionAudit> log)
{
_db = db; _log = log;
}
public async Task EndAsync(ulong accountId, string token, string reason, CancellationToken ct = default)
{
var tokenHash = Sha256Hex(token);
// Try to mark RevokedAt if the column exists; otherwise delete the row.
try
{
var session = await _db.Set<Session>()
.Where(s => s.AccountId == accountId && s.TokenHash == tokenHash)
.OrderByDescending(s => s.Id)
.FirstOrDefaultAsync(ct);
if (session is null) return;
// If you have a RevokedAt column, prefer marking it:
var revokedAtProp = _db.Entry(session).Property<DateTime?>("RevokedAt");
if (revokedAtProp != null)
{
revokedAtProp.CurrentValue = DateTime.UtcNow;
await _db.SaveChangesAsync(ct);
}
else
{
_db.Remove(session);
await _db.SaveChangesAsync(ct);
}
_log.LogInformation("Session ended for account {AccountId} (reason={Reason})", accountId, reason);
}
catch (Exception ex)
{
_log.LogWarning(ex, "Failed to end SQL session for account {AccountId}", accountId);
}
}
private static string Sha256Hex(string s)
{
using var sha = SHA256.Create();
var bytes = sha.ComputeHash(Encoding.UTF8.GetBytes(s));
return Convert.ToHexString(bytes).ToLowerInvariant();
}
}