Files
systemrevivalserver/Services/Auth/SessionAudit.cs
T

65 lines
2.0 KiB
C#

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 DataServer.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();
}
}