refactor: purge expired sessions on startup

This commit is contained in:
Oliver Booth 2024-02-25 14:12:28 +00:00
parent 0837092d5f
commit e21dfd17ff
Signed by: oliverbooth
GPG Key ID: E60B570D1B7557B5
1 changed files with 9 additions and 1 deletions

View File

@ -9,7 +9,7 @@ using ISession = OliverBooth.Data.Web.ISession;
namespace OliverBooth.Services;
internal sealed class SessionService : ISessionService
internal sealed class SessionService : BackgroundService, ISessionService
{
private readonly ILogger<SessionService> _logger;
private readonly IUserService _userService;
@ -171,4 +171,12 @@ internal sealed class SessionService : ISessionService
return true;
}
/// <inheritdoc />
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await using WebContext context = await _webContextFactory.CreateDbContextAsync(stoppingToken);
context.Sessions.RemoveRange(context.Sessions.Where(s => s.Expires <= DateTimeOffset.UtcNow));
await context.SaveChangesAsync(stoppingToken);
}
}