Skip to content

Commit

Permalink
Add logging and seperate out magic number for ClearOldPasswordREsets …
Browse files Browse the repository at this point in the history
…CRON job
  • Loading branch information
hhvrc committed Dec 4, 2024
1 parent 9c55623 commit b85c8b6
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 10 deletions.
2 changes: 2 additions & 0 deletions Common/Constants/Constants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

public static class Duration
{
public static readonly TimeSpan AuditRetentionTime = TimeSpan.FromDays(90);

public static readonly TimeSpan PasswordResetRequestLifetime = TimeSpan.FromHours(1);

public static readonly TimeSpan NameChangeCooldown = TimeSpan.FromDays(7);
Expand Down
23 changes: 13 additions & 10 deletions Cron/Jobs/ClearOldPasswordResetsJob.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,32 +7,35 @@
namespace OpenShock.Cron.Jobs;

/// <summary>
/// Deletes old password requests if they have expired their lifetime and havent been used
/// Deletes old password requests if they have expired their lifetime and haven't been used
/// </summary>
[CronJob("0 0 * * *")] // Every day at midnight (https://crontab.guru/)
public sealed class ClearOldPasswordResetsJob
{
private readonly OpenShockContext _db;
private readonly ILogger<ClearOldPasswordResetsJob> _logger;

/// <summary>
/// DI constructor
/// </summary>
/// <param name="db"></param>
public ClearOldPasswordResetsJob(OpenShockContext db)
/// <param name="db"/>
/// <param name="logger"/>
public ClearOldPasswordResetsJob(OpenShockContext db, ILogger<ClearOldPasswordResetsJob> logger)
{
_db = db;
_logger = logger;
}

public async Task Execute()
{
// Delete all password reset requests that have not been used and are older than the lifetime.
// Leave expired requests that have been used for 14 days for moderation purposes.
var earliestCreatedOn = DateTime.Now - (Duration.PasswordResetRequestLifetime + TimeSpan.FromDays(14));
var earliestCreatedOnUtc = DateTime.SpecifyKind(earliestCreatedOn, DateTimeKind.Utc);
var expiredAtUtc = DateTime.UtcNow - Duration.PasswordResetRequestLifetime;
var earliestCreatedOnUtc = expiredAtUtc - Duration.AuditRetentionTime;

// Run the delete query
await _db.PasswordResets
.Where(x => x.UsedOn == null && x.CreatedOn < earliestCreatedOnUtc)
.ExecuteDeleteAsync();
int nDeleted = await _db.PasswordResets
.Where(x => x.UsedOn == null && x.CreatedOn < earliestCreatedOnUtc)
.ExecuteDeleteAsync();

_logger.LogInformation("Deleted {deletedCount} expired password resets since {earliestCreatedOnUtc}", nDeleted, earliestCreatedOnUtc);
}
}

0 comments on commit b85c8b6

Please sign in to comment.