Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Add user last active day tracking and email cleanup task (#1200)

Leendert de Borst077a4fb3ee1b
diff --git a/apps/server/AliasVault.Admin/Main/Models/UserViewModel.cs b/apps/server/AliasVault.Admin/Main/Models/UserViewModel.cs
index 229fa8d61..4bd5350fd 100644
--- a/apps/server/AliasVault.Admin/Main/Models/UserViewModel.cs
+++ b/apps/server/AliasVault.Admin/Main/Models/UserViewModel.cs
@@ -66,4 +66,14 @@ public class UserViewModel
/// Gets or sets the last time the vault was updated.
/// </summary>
public DateTime LastVaultUpdate { get; set; }
+
+ /// <summary>
+ /// Gets or sets the last activity date of the user.
+ /// </summary>
+ public DateTime? LastActivityDate { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the user is considered inactive.
+ /// </summary>
+ public bool IsInactive { get; set; }
}
diff --git a/apps/server/AliasVault.Admin/Main/Pages/Settings/Server.razor b/apps/server/AliasVault.Admin/Main/Pages/Settings/Server.razor
index bf893e1c5..2fd437b3c 100644
--- a/apps/server/AliasVault.Admin/Main/Pages/Settings/Server.razor
+++ b/apps/server/AliasVault.Admin/Main/Pages/Settings/Server.razor
@@ -63,6 +63,16 @@
<input type="number" @bind="Settings.MaxEmailsPerUser" id="maxEmails" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500">
<p class="mt-1 text-sm text-gray-500 dark:text-gray-400">Number of emails a user can have in total. Emails exceeding this limit will be deleted, oldest first. Set to 0 for unlimited emails</p>
</div>
+ <div>
+ <label for="markInactiveDays" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Mark User as Inactive After (days)</label>
+ <input type="number" @bind="Settings.MarkUserInactiveAfterDays" id="markInactiveDays" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500">
+ <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">Users that have not logged in or had activity in the last number of days are marked as inactive. Other retention rules can act on this. Set to 0 to disable.</p>
+ </div>
+ <div>
+ <label for="maxEmailsInactive" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Max Emails per Inactive User</label>
+ <input type="number" @bind="Settings.MaxEmailsPerInactiveUser" id="maxEmailsInactive" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500">
+ <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">This limit only applies to users that are marked as inactive per the Mark User as Inactive After (days) setting. Set to 0 for unlimited emails.</p>
+ </div>
</div>
</div>
diff --git a/apps/server/AliasVault.Admin/Main/Pages/Users/Users.razor b/apps/server/AliasVault.Admin/Main/Pages/Users/Users.razor
index aaf3ea90e..97d297de6 100644
--- a/apps/server/AliasVault.Admin/Main/Pages/Users/Users.razor
+++ b/apps/server/AliasVault.Admin/Main/Pages/Users/Users.razor
@@ -1,5 +1,7 @@
@page "/users"
@using AliasVault.RazorComponents.Tables
+@using AliasVault.Shared.Server.Services
+@inject ServerSettingsService SettingsService
@inherits MainBase
<LayoutPageTitle>Users</LayoutPageTitle>
@@ -17,10 +19,21 @@
{
<div class="px-4">
<ResponsivePaginator CurrentPage="CurrentPage" PageSize="PageSize" TotalRecords="TotalRecords" OnPageChanged="HandlePageChanged" />
- <div class="mb-3">
- <div class="relative">
- <SearchIcon />
- <input type="text" @bind-value="SearchTerm" @bind-value:event="oninput" id="search" placeholder="Search users..." class="w-full px-4 ps-10 py-2 border rounded text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white">
+ <div class="mb-3 flex space-x-4">
+ <div class="w-3/4">
+ <div class="relative">
+ <SearchIcon />
+ <input type="text" @bind-value="SearchTerm" @bind-value:event="oninput" id="search" placeholder="Search users..." class="w-full px-4 ps-10 py-2 border rounded text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white">
+ </div>
+ </div>
+ <div class="w-1/4">
+ <select @bind="SelectedUserFilter" class="w-full px-4 py-2 border rounded text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white">
+ <option value="">All Users</option>
+ <option value="active">Active Users</option>
+ <option value="inactive">Inactive Users</option>
+ <option value="blocked">Blocked Users</option>
+ <option value="2fa">2FA Enabled</option>
+ </select>
</div>
</div>
</div>
@@ -44,16 +57,22 @@ else
<SortableTableColumn>@user.EmailClaimCount</SortableTableColumn>
<SortableTableColumn>@user.ReceivedEmailCount</SortableTableColumn>
<SortableTableColumn>@Math.Round((double)user.VaultStorageInKb / 1024, 1) MB</SortableTableColumn>
- <SortableTableColumn>@user.LastVaultUpdate.ToString("yyyy-MM-dd HH:mm")</SortableTableColumn>
+ <SortableTableColumn>@(user.LastActivityDate?.ToString("yyyy-MM-dd HH:mm") ?? "Never")</SortableTableColumn>
<SortableTableColumn>
- @if (user.Blocked)
- {
- <StatusPill Enabled="false" TextFalse="Blocked" />
- }
- @if (user.TwoFactorEnabled)
- {
- <StatusPill Enabled="true" TextTrue="2FA enabled" />
- }
+ <div class="flex flex-wrap gap-1">
+ @if (user.Blocked)
+ {
+ <StatusPill Enabled="false" TextFalse="Blocked" />
+ }
+ @if (user.TwoFactorEnabled)
+ {
+ <StatusPill Enabled="true" TextTrue="2FA enabled" />
+ }
+ @if (user.IsInactive)
+ {
+ <StatusPill Enabled="false" TextFalse="Inactive" />
+ }
+ </div>
</SortableTableColumn>
<SortableTableColumn>
<LinkButton Color="primary" Href="@($"users/{user.Id}")" Text="View" />
@@ -73,7 +92,7 @@ else
new TableColumn { Title = "# Email claims", PropertyName = "EmailClaimCount" },
new TableColumn { Title = "# Received emails", PropertyName = "ReceivedEmailCount" },
new TableColumn { Title = "Storage", PropertyName = "VaultStorageInKb" },
- new TableColumn { Title = "LastVaultUpdate", PropertyName = "LastVaultUpdate" },
+ new TableColumn { Title = "Last Activity", PropertyName = "LastActivityDate" },
new TableColumn { Title = "Status", Sortable = false },
new TableColumn { Title = "Actions", Sortable = false},
];
@@ -108,6 +127,23 @@ else
}
}
+ private string _selectedUserFilter = string.Empty;
+ private string _lastSelectedUserFilter = string.Empty;
+ private string SelectedUserFilter
+ {
+ get => _selectedUserFilter;
+ set
+ {
+ if (_selectedUserFilter != value)
+ {
+ _selectedUserFilter = value;
+ _searchCancellationTokenSource?.Cancel();
+ _searchCancellationTokenSource = new CancellationTokenSource();
+ _ = RefreshData(_searchCancellationTokenSource.Token);
+ }
+ }
+ }
+
private string SortColumn { get; set; } = "CreatedAt";
private SortDirection SortDirection { get; set; } = SortDirection.Descending;
@@ -147,10 +183,16 @@ else
IsLoading = true;
StateHasChanged();
+ var settings = await SettingsService.GetAllSettingsAsync();
+ var inactivityCutoffDate = settings.MarkUserInactiveAfterDays > 0
+ ? DateTime.UtcNow.AddDays(-settings.MarkUserInactiveAfterDays)
+ : (DateTime?)null;
+
await using var dbContext = await DbContextFactory.CreateDbContextAsync(cancellationToken);
IQueryable<AliasVaultUser> query = dbContext.AliasVaultUsers;
query = ApplySearchFilter(query);
+ query = ApplyUserFilter(query, inactivityCutoffDate);
query = ApplySort(query, dbContext);
TotalRecords = await query.CountAsync(cancellationToken);
@@ -164,6 +206,7 @@ else
u.CreatedAt,
u.TwoFactorEnabled,
u.Blocked,
+ u.LastActivityDate,
Vaults = u.Vaults.Select(v => new
{
v.FileSize,
@@ -185,19 +228,27 @@ else
return;
}
- UserList = users.Select(user => new UserViewModel
+ UserList = users.Select(user =>
{
- Id = user.Id,
- UserName = user.UserName?.ToLower() ?? "N/A",
- TwoFactorEnabled = user.TwoFactorEnabled,
- Blocked = user.Blocked,
- CreatedAt = user.CreatedAt,
- VaultCount = user.Vaults.Count(),
- CredentialCount = user.Vaults.OrderByDescending(x => x.RevisionNumber).First().CredentialCount,
- EmailClaimCount = user.EmailClaims.Count(),
- ReceivedEmailCount = user.ReceivedEmails,
- VaultStorageInKb = user.Vaults.Sum(x => x.FileSize),
- LastVaultUpdate = user.Vaults.Any() ? user.Vaults.Max(x => x.CreatedAt) : user.CreatedAt,
+ var lastActivity = user.LastActivityDate ?? user.CreatedAt;
+ var isInactive = inactivityCutoffDate.HasValue && lastActivity < inactivityCutoffDate.Value;
+
+ return new UserViewModel
+ {
+ Id = user.Id,
+ UserName = user.UserName?.ToLower() ?? "N/A",
+ TwoFactorEnabled = user.TwoFactorEnabled,
+ Blocked = user.Blocked,
+ CreatedAt = user.CreatedAt,
+ LastActivityDate = user.LastActivityDate,
+ IsInactive = isInactive,
+ VaultCount = user.Vaults.Count(),
+ CredentialCount = user.Vaults.OrderByDescending(x => x.RevisionNumber).First().CredentialCount,
+ EmailClaimCount = user.EmailClaims.Count(),
+ ReceivedEmailCount = user.ReceivedEmails,
+ VaultStorageInKb = user.Vaults.Sum(x => x.FileSize),
+ LastVaultUpdate = user.Vaults.Any() ? user.Vaults.Max(x => x.CreatedAt) : user.CreatedAt,
+ };
}).ToList();
IsLoading = false;
@@ -231,6 +282,47 @@ else
return query;
}
+ /// <summary>
+ /// Apply user filter to the query.
+ /// </summary>
+ private IQueryable<AliasVaultUser> ApplyUserFilter(IQueryable<AliasVaultUser> query, DateTime? inactivityCutoffDate)
+ {
+ if (!string.IsNullOrEmpty(SelectedUserFilter))
+ {
+ // Reset page number back to 1 if the filter has changed.
+ if (SelectedUserFilter != _lastSelectedUserFilter && CurrentPage != 1)
+ {
+ CurrentPage = 1;
+ }
+ _lastSelectedUserFilter = SelectedUserFilter;
+
+ switch (SelectedUserFilter)
+ {
+ case "active":
+ if (inactivityCutoffDate.HasValue)
+ {
+ query = query.Where(u => u.LastActivityDate >= inactivityCutoffDate.Value || (u.LastActivityDate == null && u.CreatedAt >= inactivityCutoffDate.Value));
+ }
+ query = query.Where(u => !u.Blocked);
+ break;
+ case "inactive":
+ if (inactivityCutoffDate.HasValue)
+ {
+ query = query.Where(u => (u.LastActivityDate != null && u.LastActivityDate < inactivityCutoffDate.Value) || (u.LastActivityDate == null && u.CreatedAt < inactivityCutoffDate.Value));
+ }
+ break;
+ case "blocked":
+ query = query.Where(u => u.Blocked);
+ break;
+ case "2fa":
+ query = query.Where(u => u.TwoFactorEnabled);
+ break;
+ }
+ }
+
+ return query;
+ }
+
/// <summary>
/// Apply sort to the query.
/// </summary>
@@ -279,10 +371,10 @@ else
? query.OrderBy(x => x.Vaults.Sum(v => v.FileSize))
: query.OrderByDescending(x => x.Vaults.Sum(v => v.FileSize));
break;
- case "LastVaultUpdate":
+ case "LastActivityDate":
query = SortDirection == SortDirection.Ascending
- ? query.OrderBy(x => x.Vaults.Max(v => v.CreatedAt))
- : query.OrderByDescending(x => x.Vaults.Max(v => v.CreatedAt));
+ ? query.OrderBy(x => x.LastActivityDate ?? x.CreatedAt)
+ : query.OrderByDescending(x => x.LastActivityDate ?? x.CreatedAt);
break;
default:
query = SortDirection == SortDirection.Ascending
diff --git a/apps/server/AliasVault.Admin/wwwroot/css/tailwind.css b/apps/server/AliasVault.Admin/wwwroot/css/tailwind.css
index 0e165f248..3c320f10e 100644
--- a/apps/server/AliasVault.Admin/wwwroot/css/tailwind.css
+++ b/apps/server/AliasVault.Admin/wwwroot/css/tailwind.css
@@ -908,6 +908,10 @@ video {
width: 0.75rem;
}
+.w-3\/4 {
+ width: 75%;
+}
+
.w-32 {
width: 8rem;
}
@@ -1076,6 +1080,10 @@ video {
gap: 1.5rem;
}
+.gap-1 {
+ gap: 0.25rem;
+}
+
.space-x-1 > :not([hidden]) ~ :not([hidden]) {
--tw-space-x-reverse: 0;
margin-right: calc(0.25rem * var(--tw-space-x-reverse));
diff --git a/apps/server/Databases/AliasServerDb/AliasVaultUser.cs b/apps/server/Databases/AliasServerDb/AliasVaultUser.cs
index 850f955d3..b43c06a0f 100644
--- a/apps/server/Databases/AliasServerDb/AliasVaultUser.cs
+++ b/apps/server/Databases/AliasServerDb/AliasVaultUser.cs
@@ -44,6 +44,12 @@ public class AliasVaultUser : IdentityUser
/// </summary>
public int MaxEmailAgeDays { get; set; } = 0;
+ /// <summary>
+ /// Gets or sets the date of the user's last activity (login, API call, etc.).
+ /// Updated automatically on successful authentication events.
+ /// </summary>
+ public DateTime? LastActivityDate { get; set; }
+
/// <summary>
/// Gets or sets the collection of vaults.
/// </summary>
diff --git a/apps/server/Databases/AliasServerDb/Migrations/20250911151303_AddUserLastActivityDate.Designer.cs b/apps/server/Databases/AliasServerDb/Migrations/20250911151303_AddUserLastActivityDate.Designer.cs
new file mode 100644
index 000000000..b7e3d9572
--- /dev/null
+++ b/apps/server/Databases/AliasServerDb/Migrations/20250911151303_AddUserLastActivityDate.Designer.cs
@@ -0,0 +1,929 @@
+// <auto-generated />
+using System;
+using AliasServerDb;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
+
+#nullable disable
+
+namespace AliasServerDb.Migrations
+{
+ [DbContext(typeof(AliasServerDbContext))]
+ [Migration("20250911151303_AddUserLastActivityDate")]
+ partial class AddUserLastActivityDate
+ {
+ /// <inheritdoc />
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder
+ .HasAnnotation("ProductVersion", "9.0.4")
+ .HasAnnotation("Proxies:ChangeTracking", false)
+ .HasAnnotation("Proxies:CheckEquality", false)
+ .HasAnnotation("Proxies:LazyLoading", true)
+ .HasAnnotation("Relational:MaxIdentifierLength", 63);
+
+ NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
+
+ modelBuilder.Entity("AliasServerDb.AdminRole", b =>
+ {
+ b.Property<string>("Id")
+ .HasColumnType("text");
+
+ b.Property<string>("ConcurrencyStamp")
+ .HasColumnType("text");
+
+ b.Property<string>("Name")
+ .HasColumnType("text");
+
+ b.Property<string>("NormalizedName")
+ .HasColumnType("text");
+
+ b.HasKey("Id");
+
+ b.ToTable("AdminRoles");
+ });
+
+ modelBuilder.Entity("AliasServerDb.AdminUser", b =>
+ {
+ b.Property<string>("Id")
+ .HasColumnType("text");
+
+ b.Property<int>("AccessFailedCount")
+ .HasColumnType("integer");
+
+ b.Property<string>("ConcurrencyStamp")
+ .HasColumnType("text");
+
+ b.Property<string>("Email")
+ .HasColumnType("text");
+
+ b.Property<bool>("EmailConfirmed")
+ .HasColumnType("boolean");
+
+ b.Property<DateTime?>("LastPasswordChanged")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<bool>("LockoutEnabled")
+ .HasColumnType("boolean");
+
+ b.Property<DateTimeOffset?>("LockoutEnd")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<string>("NormalizedEmail")
+ .HasColumnType("text");
+
+ b.Property<string>("NormalizedUserName")
+ .HasColumnType("text");
+
+ b.Property<string>("PasswordHash")
+ .HasColumnType("text");
+
+ b.Property<string>("PhoneNumber")
+ .HasColumnType("text");
+
+ b.Property<bool>("PhoneNumberConfirmed")
+ .HasColumnType("boolean");
+
+ b.Property<string>("SecurityStamp")
+ .HasColumnType("text");
+
+ b.Property<bool>("TwoFactorEnabled")
+ .HasColumnType("boolean");
+
+ b.Property<string>("UserName")
+ .HasColumnType("text");
+
+ b.HasKey("Id");
+
+ b.ToTable("AdminUsers");
+ });
+
+ modelBuilder.Entity("AliasServerDb.AliasVaultRole", b =>
+ {
+ b.Property<string>("Id")
+ .HasColumnType("text");
+
+ b.Property<string>("ConcurrencyStamp")
+ .HasColumnType("text");
+
+ b.Property<string>("Name")
+ .HasColumnType("text");
+
+ b.Property<string>("NormalizedName")
+ .HasColumnType("text");
+
+ b.HasKey("Id");
+
+ b.ToTable("AliasVaultRoles");
+ });
+
+ modelBuilder.Entity("AliasServerDb.AliasVaultUser", b =>
+ {
+ b.Property<string>("Id")
+ .HasColumnType("text");
+
+ b.Property<int>("AccessFailedCount")
+ .HasColumnType("integer");
+
+ b.Property<bool>("Blocked")
+ .HasColumnType("boolean");
+
+ b.Property<string>("ConcurrencyStamp")
+ .HasColumnType("text");
+
+ b.Property<DateTime>("CreatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<string>("Email")
+ .HasColumnType("text");
+
+ b.Property<bool>("EmailConfirmed")
+ .HasColumnType("boolean");
+
+ b.Property<DateTime?>("LastActivityDate")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<bool>("LockoutEnabled")
+ .HasColumnType("boolean");
+
+ b.Property<DateTimeOffset?>("LockoutEnd")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<int>("MaxEmailAgeDays")
+ .HasColumnType("integer");
+
+ b.Property<int>("MaxEmails")
+ .HasColumnType("integer");
+
+ b.Property<string>("NormalizedEmail")
+ .HasColumnType("text");
+
+ b.Property<string>("NormalizedUserName")
+ .HasColumnType("text");
+
+ b.Property<DateTime>("PasswordChangedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<string>("PasswordHash")
+ .HasColumnType("text");
+
+ b.Property<string>("PhoneNumber")
+ .HasColumnType("text");
+
+ b.Property<bool>("PhoneNumberConfirmed")
+ .HasColumnType("boolean");
+
+ b.Property<string>("SecurityStamp")
+ .HasColumnType("text");
+
+ b.Property<bool>("TwoFactorEnabled")
+ .HasColumnType("boolean");
+
+ b.Property<DateTime>("UpdatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<string>("UserName")
+ .HasColumnType("text");
+
+ b.HasKey("Id");
+
+ b.ToTable("AliasVaultUsers");
+ });
+
+ modelBuilder.Entity("AliasServerDb.AliasVaultUserRefreshToken", b =>
+ {
+ b.Property<Guid>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property<DateTime>("CreatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<string>("DeviceIdentifier")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)");
+
+ b.Property<DateTime>("ExpireDate")
+ .HasMaxLength(255)
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<string>("IpAddress")
+ .HasMaxLength(45)
+ .HasColumnType("character varying(45)");
+
+ b.Property<string>("PreviousTokenValue")
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)");
+
+ b.Property<string>("UserId")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)");
+
+ b.Property<string>("Value")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)");
+
+ b.HasKey("Id");
+
+ b.HasIndex("UserId");
+
+ b.ToTable("AliasVaultUserRefreshTokens");
+ });
+
+ modelBuilder.Entity("AliasServerDb.AuthLog", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("integer");
+
+ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
+
+ b.Property<string>("AdditionalInfo")
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)");
+
+ b.Property<string>("Browser")
+ .HasMaxLength(100)
+ .HasColumnType("character varying(100)");
+
+ b.Property<string>("Client")
+ .HasMaxLength(100)
+ .HasColumnType("character varying(100)");
+
+ b.Property<string>("Country")
+ .HasMaxLength(50)
+ .HasColumnType("character varying(50)");
+
+ b.Property<string>("DeviceType")
+ .HasMaxLength(100)
+ .HasColumnType("character varying(100)");
+
+ b.Property<int>("EventType")
+ .HasColumnType("integer");
+
+ b.Property<int?>("FailureReason")
+ .HasColumnType("integer");
+
+ b.Property<string>("IpAddress")
+ .HasMaxLength(50)
+ .HasColumnType("character varying(50)");
+
+ b.Property<bool>("IsSuccess")
+ .HasColumnType("boolean");
+
+ b.Property<bool>("IsSuspiciousActivity")
+ .HasColumnType("boolean");
+
+ b.Property<string>("OperatingSystem")
+ .HasMaxLength(100)
+ .HasColumnType("character varying(100)");
+
+ b.Property<string>("RequestPath")
+ .HasMaxLength(100)
+ .HasColumnType("character varying(100)");
+
+ b.Property<DateTime>("Timestamp")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<string>("UserAgent")
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)");
+
+ b.Property<string>("Username")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)");
+
+ b.HasKey("Id");
+
+ b.HasIndex(new[] { "EventType" }, "IX_EventType");
+
+ b.HasIndex(new[] { "IpAddress" }, "IX_IpAddress");
+
+ b.HasIndex(new[] { "Timestamp" }, "IX_Timestamp");
+
+ b.HasIndex(new[] { "Username", "IsSuccess", "Timestamp" }, "IX_Username_IsSuccess_Timestamp")
+ .IsDescending(false, false, true);
+
+ b.HasIndex(new[] { "Username", "Timestamp" }, "IX_Username_Timestamp")
+ .IsDescending(false, true);
+
+ b.ToTable("AuthLogs");
+ });
+
+ modelBuilder.Entity("AliasServerDb.Email", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("integer");
+
+ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
+
+ b.Property<DateTime>("Date")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<DateTime>("DateSystem")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<string>("EncryptedSymmetricKey")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property<string>("From")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property<string>("FromDomain")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property<string>("FromLocal")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property<string>("MessageHtml")
+ .HasColumnType("text");
+
+ b.Property<string>("MessagePlain")
+ .HasColumnType("text");
+
+ b.Property<string>("MessagePreview")
+ .HasColumnType("text");
+
+ b.Property<string>("MessageSource")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property<bool>("PushNotificationSent")
+ .HasColumnType("boolean");
+
+ b.Property<string>("Subject")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property<string>("To")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property<string>("ToDomain")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property<string>("ToLocal")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property<Guid>("UserEncryptionKeyId")
+ .HasMaxLength(255)
+ .HasColumnType("uuid");
+
+ b.Property<bool>("Visible")
+ .HasColumnType("boolean");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Date");
+
+ b.HasIndex("DateSystem");
+
+ b.HasIndex("PushNotificationSent");
+
+ b.HasIndex("ToLocal");
+
+ b.HasIndex("UserEncryptionKeyId");
+
+ b.HasIndex("Visible");
+
+ b.ToTable("Emails");
+ });
+
+ modelBuilder.Entity("AliasServerDb.EmailAttachment", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("integer");
+
+ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
+
+ b.Property<byte[]>("Bytes")
+ .IsRequired()
+ .HasColumnType("bytea");
+
+ b.Property<DateTime>("Date")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<int>("EmailId")
+ .HasColumnType("integer");
+
+ b.Property<string>("Filename")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property<int>("Filesize")
+ .HasColumnType("integer");
+
+ b.Property<string>("MimeType")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.HasKey("Id");
+
+ b.HasIndex("EmailId");
+
+ b.ToTable("EmailAttachments");
+ });
+
+ modelBuilder.Entity("AliasServerDb.Log", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("integer");
+
+ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
+
+ b.Property<string>("Application")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("character varying(50)");
+
+ b.Property<string>("Exception")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property<string>("Level")
+ .IsRequired()
+ .HasMaxLength(128)
+ .HasColumnType("character varying(128)");
+
+ b.Property<string>("LogEvent")
+ .IsRequired()
+ .HasColumnType("text")
+ .HasColumnName("LogEvent");
+
+ b.Property<string>("Message")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property<string>("MessageTemplate")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property<string>("Properties")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property<string>("SourceContext")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)");
+
+ b.Property<DateTime>("TimeStamp")
+ .HasColumnType("timestamp with time zone");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Application");
+
+ b.HasIndex("TimeStamp");
+
+ b.ToTable("Logs", (string)null);
+ });
+
+ modelBuilder.Entity("AliasServerDb.ServerSetting", b =>
+ {
+ b.Property<string>("Key")
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)");
+
+ b.Property<DateTime>("CreatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<DateTime>("UpdatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<string>("Value")
+ .HasColumnType("text");
+
+ b.HasKey("Key");
+
+ b.ToTable("ServerSettings");
+ });
+
+ modelBuilder.Entity("AliasServerDb.TaskRunnerJob", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("integer");
+
+ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
+
+ b.Property<TimeOnly?>("EndTime")
+ .HasColumnType("time without time zone");
+
+ b.Property<string>("ErrorMessage")
+ .HasColumnType("text");
+
+ b.Property<bool>("IsOnDemand")
+ .HasColumnType("boolean");
+
+ b.Property<string>("Name")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("character varying(50)");
+
+ b.Property<DateTime>("RunDate")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<TimeOnly>("StartTime")
+ .HasColumnType("time without time zone");
+
+ b.Property<int>("Status")
+ .HasColumnType("integer");
+
+ b.HasKey("Id");
+
+ b.ToTable("TaskRunnerJobs");
+ });
+
+ modelBuilder.Entity("AliasServerDb.UserEmailClaim", b =>
+ {
+ b.Property<Guid>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property<string>("Address")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)");
+
+ b.Property<string>("AddressDomain")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)");
+
+ b.Property<string>("AddressLocal")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)");
+
+ b.Property<DateTime>("CreatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<bool>("Disabled")
+ .HasColumnType("boolean");
+
+ b.Property<DateTime>("UpdatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<string>("UserId")
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Address")
+ .IsUnique();
+
+ b.HasIndex("UserId");
+
+ b.ToTable("UserEmailClaims");
+ });
+
+ modelBuilder.Entity("AliasServerDb.UserEncryptionKey", b =>
+ {
+ b.Property<Guid>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property<DateTime>("CreatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<bool>("IsPrimary")
+ .HasColumnType("boolean");
+
+ b.Property<string>("PublicKey")
+ .IsRequired()
+ .HasMaxLength(2000)
+ .HasColumnType("character varying(2000)");
+
+ b.Property<DateTime>("UpdatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<string>("UserId")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)");
+
+ b.HasKey("Id");
+
+ b.HasIndex("UserId");
+
+ b.ToTable("UserEncryptionKeys");
+ });
+
+ modelBuilder.Entity("AliasServerDb.Vault", b =>
+ {
+ b.Property<Guid>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property<string>("Client")
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)");
+
+ b.Property<DateTime>("CreatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<int>("CredentialsCount")
+ .HasColumnType("integer");
+
+ b.Property<int>("EmailClaimsCount")
+ .HasColumnType("integer");
+
+ b.Property<string>("EncryptionSettings")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property<string>("EncryptionType")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property<int>("FileSize")
+ .HasColumnType("integer");
+
+ b.Property<long>("RevisionNumber")
+ .HasColumnType("bigint");
+
+ b.Property<string>("Salt")
+ .IsRequired()
+ .HasMaxLength(100)
+ .HasColumnType("character varying(100)");
+
+ b.Property<DateTime>("UpdatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<string>("UserId")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)");
+
+ b.Property<string>("VaultBlob")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property<string>("Verifier")
+ .IsRequired()
+ .HasMaxLength(1000)
+ .HasColumnType("character varying(1000)");
+
+ b.Property<string>("Version")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)");
+
+ b.HasKey("Id");
+
+ b.HasIndex("UserId");
+
+ b.ToTable("Vaults");
+ });
+
+ modelBuilder.Entity("AliasVault.WorkerStatus.Database.WorkerServiceStatus", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("integer");
+
+ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
+
+ b.Property<string>("CurrentStatus")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("character varying(50)");
+
+ b.Property<string>("DesiredStatus")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("character varying(50)");
+
+ b.Property<DateTime>("Heartbeat")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<string>("ServiceName")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)");
+
+ b.HasKey("Id");
+
+ b.ToTable("WorkerServiceStatuses");
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.DataProtection.EntityFrameworkCore.DataProtectionKey", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("integer");
+
+ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
+
+ b.Property<string>("FriendlyName")
+ .HasColumnType("text");
+
+ b.Property<string>("Xml")
+ .HasColumnType("text");
+
+ b.HasKey("Id");
+
+ b.ToTable("DataProtectionKeys");
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("integer");
+
+ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
+
+ b.Property<string>("ClaimType")
+ .HasColumnType("text");
+
+ b.Property<string>("ClaimValue")
+ .HasColumnType("text");
+
+ b.Property<string>("RoleId")
+ .HasColumnType("text");
+
+ b.HasKey("Id");
+
+ b.ToTable("RoleClaims", (string)null);
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("integer");
+
+ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
+
+ b.Property<string>("ClaimType")
+ .HasColumnType("text");
+
+ b.Property<string>("ClaimValue")
+ .HasColumnType("text");
+
+ b.Property<string>("UserId")
+ .HasColumnType("text");
+
+ b.HasKey("Id");
+
+ b.ToTable("UserClaims", (string)null);
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
+ {
+ b.Property<string>("LoginProvider")
+ .HasColumnType("text");
+
+ b.Property<string>("ProviderKey")
+ .HasColumnType("text");
+
+ b.Property<string>("ProviderDisplayName")
+ .HasColumnType("text");
+
+ b.Property<string>("UserId")
+ .HasColumnType("text");
+
+ b.HasKey("LoginProvider", "ProviderKey");
+
+ b.ToTable("UserLogins", (string)null);
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
+ {
+ b.Property<string>("UserId")
+ .HasColumnType("text");
+
+ b.Property<string>("RoleId")
+ .HasColumnType("text");
+
+ b.HasKey("UserId", "RoleId");
+
+ b.ToTable("UserRoles", (string)null);
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
+ {
+ b.Property<string>("UserId")
+ .HasColumnType("text");
+
+ b.Property<string>("LoginProvider")
+ .HasColumnType("text");
+
+ b.Property<string>("Name")
+ .HasColumnType("text");
+
+ b.Property<string>("Value")
+ .HasColumnType("text");
+
+ b.HasKey("UserId", "LoginProvider", "Name");
+
+ b.ToTable("UserTokens", (string)null);
+ });
+
+ modelBuilder.Entity("AliasServerDb.AliasVaultUserRefreshToken", b =>
+ {
+ b.HasOne("AliasServerDb.AliasVaultUser", "User")
+ .WithMany()
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("User");
+ });
+
+ modelBuilder.Entity("AliasServerDb.Email", b =>
+ {
+ b.HasOne("AliasServerDb.UserEncryptionKey", "EncryptionKey")
+ .WithMany("Emails")
+ .HasForeignKey("UserEncryptionKeyId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("EncryptionKey");
+ });
+
+ modelBuilder.Entity("AliasServerDb.EmailAttachment", b =>
+ {
+ b.HasOne("AliasServerDb.Email", "Email")
+ .WithMany("Attachments")
+ .HasForeignKey("EmailId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Email");
+ });
+
+ modelBuilder.Entity("AliasServerDb.UserEmailClaim", b =>
+ {
+ b.HasOne("AliasServerDb.AliasVaultUser", "User")
+ .WithMany("EmailClaims")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.SetNull);
+
+ b.Navigation("User");
+ });
+
+ modelBuilder.Entity("AliasServerDb.UserEncryptionKey", b =>
+ {
+ b.HasOne("AliasServerDb.AliasVaultUser", "User")
+ .WithMany("EncryptionKeys")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("User");
+ });
+
+ modelBuilder.Entity("AliasServerDb.Vault", b =>
+ {
+ b.HasOne("AliasServerDb.AliasVaultUser", "User")
+ .WithMany("Vaults")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("User");
+ });
+
+ modelBuilder.Entity("AliasServerDb.AliasVaultUser", b =>
+ {
+ b.Navigation("EmailClaims");
+
+ b.Navigation("EncryptionKeys");
+
+ b.Navigation("Vaults");
+ });
+
+ modelBuilder.Entity("AliasServerDb.Email", b =>
+ {
+ b.Navigation("Attachments");
+ });
+
+ modelBuilder.Entity("AliasServerDb.UserEncryptionKey", b =>
+ {
+ b.Navigation("Emails");
+ });
+#pragma warning restore 612, 618
+ }
+ }
+}
diff --git a/apps/server/Databases/AliasServerDb/Migrations/20250911151303_AddUserLastActivityDate.cs b/apps/server/Databases/AliasServerDb/Migrations/20250911151303_AddUserLastActivityDate.cs
new file mode 100644
index 000000000..7d9cd8e44
--- /dev/null
+++ b/apps/server/Databases/AliasServerDb/Migrations/20250911151303_AddUserLastActivityDate.cs
@@ -0,0 +1,49 @@
+using System;
+using Microsoft.EntityFrameworkCore.Migrations;
+
+#nullable disable
+
+namespace AliasServerDb.Migrations
+{
+ /// <inheritdoc />
+ public partial class AddUserLastActivityDate : Migration
+ {
+ /// <inheritdoc />
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.AddColumn<DateTime>(
+ name: "LastActivityDate",
+ table: "AliasVaultUsers",
+ type: "timestamp with time zone",
+ nullable: true);
+
+ // Populate LastActivityDate with the most recent activity for each user
+ // Priority: 1) Latest successful auth log, 2) Latest vault update, 3) User creation date
+ migrationBuilder.Sql(@"
+ UPDATE ""AliasVaultUsers""
+ SET ""LastActivityDate"" = COALESCE(
+ -- First try to get the latest successful login from auth logs
+ (SELECT MAX(""Timestamp"")
+ FROM ""AuthLogs""
+ WHERE ""Username"" = ""AliasVaultUsers"".""UserName""
+ AND ""IsSuccess"" = true
+ AND ""EventType"" = 0), -- Login event type
+ -- Fall back to the latest vault update
+ (SELECT MAX(""CreatedAt"")
+ FROM ""Vaults""
+ WHERE ""UserId"" = ""AliasVaultUsers"".""Id""),
+ -- Final fallback to user creation date
+ ""AliasVaultUsers"".""CreatedAt""
+ );
+ ");
+ }
+
+ /// <inheritdoc />
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropColumn(
+ name: "LastActivityDate",
+ table: "AliasVaultUsers");
+ }
+ }
+}
diff --git a/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs b/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs
index fd1377f29..8a8db46c9 100644
--- a/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs
+++ b/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs
@@ -141,6 +141,9 @@ namespace AliasServerDb.Migrations
b.Property<bool>("EmailConfirmed")
.HasColumnType("boolean");
+ b.Property<DateTime?>("LastActivityDate")
+ .HasColumnType("timestamp with time zone");
+
b.Property<bool>("LockoutEnabled")
.HasColumnType("boolean");
diff --git a/apps/server/Services/AliasVault.TaskRunner/Tasks/EmailQuotaCleanupTask.cs b/apps/server/Services/AliasVault.TaskRunner/Tasks/EmailQuotaCleanupTask.cs
index 123343933..4b093fd7e 100644
--- a/apps/server/Services/AliasVault.TaskRunner/Tasks/EmailQuotaCleanupTask.cs
+++ b/apps/server/Services/AliasVault.TaskRunner/Tasks/EmailQuotaCleanupTask.cs
@@ -48,15 +48,24 @@ public class EmailQuotaCleanupTask : IMaintenanceTask
// Get all users with their email claims and limits
var usersWithClaims = await (from u in dbContext.AliasVaultUsers
join c in dbContext.UserEmailClaims on u.Id equals c.UserId
- select new { u.Id, u.UserName, u.MaxEmails, c.Address })
+ select new { u.Id, u.UserName, u.MaxEmails, u.LastActivityDate, u.CreatedAt, c.Address })
.ToListAsync(cancellationToken);
+ // Get minimum activity date which is used to determine if user is active.
+ var inactivityCutoffDate = settings.MarkUserInactiveAfterDays > 0
+ ? DateTime.UtcNow.AddDays(-settings.MarkUserInactiveAfterDays)
+ : (DateTime?)null;
+
var totalEmailsDeleted = 0;
var usersProcessed = 0;
// Group by user
- foreach (var userGroup in usersWithClaims.GroupBy(x => new { x.Id, x.UserName, x.MaxEmails }))
+ foreach (var userGroup in usersWithClaims.GroupBy(x => new { x.Id, x.UserName, x.MaxEmails, x.LastActivityDate, x.CreatedAt }))
{
+ // Calculate if user is inactive
+ var lastActivity = userGroup.Key.LastActivityDate ?? userGroup.Key.CreatedAt;
+ var isInactive = inactivityCutoffDate.HasValue && lastActivity < inactivityCutoffDate.Value;
+
// Determine the effective limit for this user
int effectiveLimit;
string limitSource;
@@ -67,6 +76,12 @@ public class EmailQuotaCleanupTask : IMaintenanceTask
effectiveLimit = userGroup.Key.MaxEmails;
limitSource = "user-specific";
}
+ else if (isInactive && settings.MaxEmailsPerInactiveUser > 0)
+ {
+ // User is inactive, use inactive limit
+ effectiveLimit = settings.MaxEmailsPerInactiveUser;
+ limitSource = "inactive-user";
+ }
else if (settings.MaxEmailsPerUser > 0)
{
// Use global limit
diff --git a/apps/server/Shared/AliasVault.Shared.Server/Models/ServerSettingsModel.cs b/apps/server/Shared/AliasVault.Shared.Server/Models/ServerSettingsModel.cs
index c65f32136..78c6d24aa 100644
--- a/apps/server/Shared/AliasVault.Shared.Server/Models/ServerSettingsModel.cs
+++ b/apps/server/Shared/AliasVault.Shared.Server/Models/ServerSettingsModel.cs
@@ -38,6 +38,19 @@ public class ServerSettingsModel
/// </summary>
public int MaxEmailsPerUser { get; set; }
+ /// <summary>
+ /// Gets or sets the number of days of inactivity before marking a user as inactive. Defaults to 90 days.
+ /// Users that have not logged in or had activity in the last number of days are marked as inactive.
+ /// Other retention rules can act on this status.
+ /// </summary>
+ public int MarkUserInactiveAfterDays { get; set; } = 90;
+
+ /// <summary>
+ /// Gets or sets the max emails per inactive user. Defaults to 0 (unlimited).
+ /// This limit only applies to users that are marked as inactive per the MarkUserInactiveAfterDays setting.
+ /// </summary>
+ public int MaxEmailsPerInactiveUser { get; set; }
+
/// <summary>
/// Gets or sets the time when maintenance tasks are run (24h format). Defaults to 00:00.
/// </summary>
diff --git a/apps/server/Tests/AliasVault.E2ETests/Tests/Admin/ServerSettingsTests.cs b/apps/server/Tests/AliasVault.E2ETests/Tests/Admin/ServerSettingsTests.cs
index 263a41454..9d2dc224e 100644
--- a/apps/server/Tests/AliasVault.E2ETests/Tests/Admin/ServerSettingsTests.cs
+++ b/apps/server/Tests/AliasVault.E2ETests/Tests/Admin/ServerSettingsTests.cs
@@ -33,6 +33,8 @@ public class ServerSettingsTests : AdminPlaywrightTest
await Page.Locator("input[id='authLogRetention']").FillAsync("120");
await Page.Locator("input[id='emailRetention']").FillAsync("60");
await Page.Locator("input[id='maxEmails']").FillAsync("200");
+ await Page.Locator("input[id='markInactiveDays']").FillAsync("180");
+ await Page.Locator("input[id='maxEmailsInactive']").FillAsync("50");
// Set maintenance time
await Page.Locator("input[id='schedule']").FillAsync("03:30");
@@ -64,6 +66,12 @@ public class ServerSettingsTests : AdminPlaywrightTest
var maxEmails = settings.Find(s => s.Key == "MaxEmailsPerUser");
Assert.That(maxEmails?.Value, Is.EqualTo("200"), "Max emails per user not saved correctly");
+ var markInactiveDays = settings.Find(s => s.Key == "MarkUserInactiveAfterDays");
+ Assert.That(markInactiveDays?.Value, Is.EqualTo("180"), "Mark user inactive after days not saved correctly");
+
+ var maxEmailsInactive = settings.Find(s => s.Key == "MaxEmailsPerInactiveUser");
+ Assert.That(maxEmailsInactive?.Value, Is.EqualTo("50"), "Max emails per inactive user not saved correctly");
+
// Check maintenance schedule
var maintenanceTime = settings.Find(s => s.Key == "MaintenanceTime");
Assert.That(maintenanceTime?.Value, Is.EqualTo("03:30"), "Maintenance time not saved correctly");
diff --git a/apps/server/Utilities/AliasVault.Auth/AuthLoggingService.cs b/apps/server/Utilities/AliasVault.Auth/AuthLoggingService.cs
index 64b04a571..944b07602 100644
--- a/apps/server/Utilities/AliasVault.Auth/AuthLoggingService.cs
+++ b/apps/server/Utilities/AliasVault.Auth/AuthLoggingService.cs
@@ -11,6 +11,7 @@ using AliasServerDb;
using AliasVault.Shared.Models.Configuration;
using AliasVault.Shared.Models.Enums;
using Microsoft.AspNetCore.Http;
+using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
/// <summary>
@@ -55,6 +56,14 @@ public class AuthLoggingService(IServiceProvider serviceProvider, IHttpContextAc
};
dbContext.AuthLogs.Add(authAttempt);
+
+ // Update user's last activity date.
+ var user = await dbContext.AliasVaultUsers.FirstOrDefaultAsync(u => u.UserName == username);
+ if (user != null)
+ {
+ user.LastActivityDate = DateTime.UtcNow;
+ }
+
await dbContext.SaveChangesAsync();
}