Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add top users by email table to admin all time stats page (#1082)
Leendert de Borstcd306ef87845
diff --git a/apps/server/AliasVault.Admin/Main/Models/ServerStatistics.cs b/apps/server/AliasVault.Admin/Main/Models/ServerStatistics.csindex 004349b75..0402edc48 100644--- a/apps/server/AliasVault.Admin/Main/Models/ServerStatistics.cs+++ b/apps/server/AliasVault.Admin/Main/Models/ServerStatistics.cs@@ -42,6 +42,11 @@ public class ServerStatistics/// </summary>public List<TopUserByAliases> TopUsersByAliases { get; set; } = new();+ /// <summary>+ /// Gets or sets the list of top users by number of emails.+ /// </summary>+ public List<TopUserByEmails> TopUsersByEmails { get; set; } = new();+/// <summary>/// Gets or sets the list of top IP addresses by user activity./// </summary>diff --git a/apps/server/AliasVault.Admin/Main/Models/TopUserByEmails.cs b/apps/server/AliasVault.Admin/Main/Models/TopUserByEmails.csnew file mode 100644index 000000000..c03ccf0f6--- /dev/null+++ b/apps/server/AliasVault.Admin/Main/Models/TopUserByEmails.cs@@ -0,0 +1,29 @@+//-----------------------------------------------------------------------+// <copyright file="TopUserByEmails.cs" company="lanedirt">+// Copyright (c) lanedirt. All rights reserved.+// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.+// </copyright>+//-----------------------------------------------------------------------++namespace AliasVault.Admin.Main.Models;++/// <summary>+/// Model representing a user with many stored emails.+/// </summary>+public class TopUserByEmails+{+ /// <summary>+ /// Gets or sets the user ID.+ /// </summary>+ public string UserId { get; set; } = string.Empty;++ /// <summary>+ /// Gets or sets the username.+ /// </summary>+ public string Username { get; set; } = string.Empty;++ /// <summary>+ /// Gets or sets the number of emails.+ /// </summary>+ public int EmailCount { get; set; }+}diff --git a/apps/server/AliasVault.Admin/Main/Pages/Dashboard/AllTimeStats.razor b/apps/server/AliasVault.Admin/Main/Pages/Dashboard/AllTimeStats.razorindex 563e54ba9..9a1affdbb 100644--- a/apps/server/AliasVault.Admin/Main/Pages/Dashboard/AllTimeStats.razor+++ b/apps/server/AliasVault.Admin/Main/Pages/Dashboard/AllTimeStats.razor@@ -3,6 +3,7 @@@using AliasVault.Admin.Services@using AliasVault.Admin.Main.Pages.Dashboard.Components@using AliasVault.RazorComponents.Tables+@using AliasVault.RazorComponents@inherits MainBase@inject StatisticsService StatisticsService@@ -86,7 +87,7 @@</div><!-- Top Users Analysis -->- <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">+ <div class="space-y-6"><!-- Top Users by Storage --><div class="p-4 bg-white border border-gray-200 rounded-lg shadow-sm dark:border-gray-700 sm:p-6 dark:bg-gray-800"><div class="flex items-center justify-between mb-4">@@ -112,6 +113,7 @@}</SortableTable></div>+ <Paginator CurrentPage="_storageCurrentPage" PageSize="_pageSize" TotalRecords="_storageTotalRecords" OnPageChanged="HandleStoragePageChanged" />}else{@@ -146,6 +148,42 @@}</SortableTable></div>+ <Paginator CurrentPage="_aliasCurrentPage" PageSize="_pageSize" TotalRecords="_aliasTotalRecords" OnPageChanged="HandleAliasPageChanged" />+ }+ else+ {+ <div class="px-6 py-8 flex justify-center">+ <LoadingIndicator />+ </div>+ }+ </div>++ <!-- Top Users by Emails -->+ <div class="p-4 bg-white border border-gray-200 rounded-lg shadow-sm dark:border-gray-700 sm:p-6 dark:bg-gray-800">+ <div class="flex items-center justify-between mb-4">+ <div>+ <h3 class="text-lg font-semibold text-gray-900 dark:text-white">Top Users by Emails</h3>+ <p class="text-sm text-gray-500 dark:text-gray-400">Users with the most emails stored in their aliases</p>+ </div>+ </div>+ @if (_topUsersByEmails != null)+ {+ <div class="overflow-x-auto">+ <SortableTable Columns="@_emailTableColumns">+ @foreach (var user in _topUsersByEmails)+ {+ <tr class="hover:bg-gray-50 dark:hover:bg-gray-700">+ <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-gray-100">+ <a href="users/@user.UserId" class="text-gray-900 dark:text-gray-100 hover:text-blue-600 dark:hover:text-blue-400 cursor-pointer">+ @user.Username+ </a>+ </td>+ <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400 text-right">@user.EmailCount.ToString("N0")</td>+ </tr>+ }+ </SortableTable>+ </div>+ <Paginator CurrentPage="_emailCurrentPage" PageSize="_pageSize" TotalRecords="_emailTotalRecords" OnPageChanged="HandleEmailPageChanged" />}else{@@ -239,10 +277,20 @@// Detailed statistics (loaded separately)private List<TopUserByStorage>? _topUsersByStorage;private List<TopUserByAliases>? _topUsersByAliases;+ private List<TopUserByEmails>? _topUsersByEmails;private List<TopIpAddress>? _topIpAddresses;private bool _ipAddressesLoading = true;private bool _loadingError = false;+ // Pagination variables+ private const int _pageSize = 10;+ private int _storageCurrentPage = 1;+ private int _aliasCurrentPage = 1;+ private int _emailCurrentPage = 1;+ private int _storageTotalRecords = 0;+ private int _aliasTotalRecords = 0;+ private int _emailTotalRecords = 0;+private readonly List<TableColumn> _storageTableColumns = new(){new() { Title = "User", PropertyName = "Username", Sortable = false },@@ -255,6 +303,12 @@new() { Title = "Aliases", PropertyName = "AliasCount", Sortable = false }};+ private readonly List<TableColumn> _emailTableColumns = new()+ {+ new() { Title = "User", PropertyName = "Username", Sortable = false },+ new() { Title = "Emails", PropertyName = "EmailCount", Sortable = false }+ };+private readonly List<TableColumn> _ipTableColumns = new(){new() { Title = "IP Range", PropertyName = "IpAddress", Sortable = false },@@ -282,10 +336,19 @@_totalEmailAttachments = null;_topUsersByStorage = null;_topUsersByAliases = null;+ _topUsersByEmails = null;_topIpAddresses = null;_ipAddressesLoading = true;_loadingError = false;+ // Reset pagination+ _storageCurrentPage = 1;+ _aliasCurrentPage = 1;+ _emailCurrentPage = 1;+ _storageTotalRecords = 0;+ _aliasTotalRecords = 0;+ _emailTotalRecords = 0;+StateHasChanged();// Reload statistics@@ -318,10 +381,28 @@{try{- var stats = await StatisticsService.GetServerStatisticsAsync();+ // Load paginated data for all three tables+ var storageTask = StatisticsService.GetTopUsersByStoragePaginatedAsync(_storageCurrentPage, _pageSize);+ var aliasTask = StatisticsService.GetTopUsersByAliasesPaginatedAsync(_aliasCurrentPage, _pageSize);+ var emailTask = StatisticsService.GetTopUsersByEmailsPaginatedAsync(_emailCurrentPage, _pageSize);+ var ipTask = StatisticsService.GetServerStatisticsAsync();++ await Task.WhenAll(storageTask, aliasTask, emailTask, ipTask);++ var (storageUsers, storageTotalCount) = await storageTask;+ var (aliasUsers, aliasTotalCount) = await aliasTask;+ var (emailUsers, emailTotalCount) = await emailTask;+ var stats = await ipTask;++ _topUsersByStorage = storageUsers;+ _storageTotalRecords = storageTotalCount;++ _topUsersByAliases = aliasUsers;+ _aliasTotalRecords = aliasTotalCount;++ _topUsersByEmails = emailUsers;+ _emailTotalRecords = emailTotalCount;- _topUsersByStorage = stats.TopUsersByStorage;- _topUsersByAliases = stats.TopUsersByAliases;_topIpAddresses = stats.TopIpAddresses;_ipAddressesLoading = false;@@ -335,4 +416,79 @@StateHasChanged();}}++ private async Task HandleStoragePageChanged(int newPage)+ {+ _storageCurrentPage = newPage;+ await LoadStoragePageData();+ }++ private async Task HandleAliasPageChanged(int newPage)+ {+ _aliasCurrentPage = newPage;+ await LoadAliasPageData();+ }++ private async Task HandleEmailPageChanged(int newPage)+ {+ _emailCurrentPage = newPage;+ await LoadEmailPageData();+ }++ private async Task LoadStoragePageData()+ {+ try+ {+ _topUsersByStorage = null;+ StateHasChanged();++ var (users, totalCount) = await StatisticsService.GetTopUsersByStoragePaginatedAsync(_storageCurrentPage, _pageSize);+ _topUsersByStorage = users;+ _storageTotalRecords = totalCount;++ StateHasChanged();+ }+ catch (Exception ex)+ {+ GlobalNotificationService.AddErrorMessage($"Error loading storage statistics: {ex.Message}");+ }+ }++ private async Task LoadAliasPageData()+ {+ try+ {+ _topUsersByAliases = null;+ StateHasChanged();++ var (users, totalCount) = await StatisticsService.GetTopUsersByAliasesPaginatedAsync(_aliasCurrentPage, _pageSize);+ _topUsersByAliases = users;+ _aliasTotalRecords = totalCount;++ StateHasChanged();+ }+ catch (Exception ex)+ {+ GlobalNotificationService.AddErrorMessage($"Error loading alias statistics: {ex.Message}");+ }+ }++ private async Task LoadEmailPageData()+ {+ try+ {+ _topUsersByEmails = null;+ StateHasChanged();++ var (users, totalCount) = await StatisticsService.GetTopUsersByEmailsPaginatedAsync(_emailCurrentPage, _pageSize);+ _topUsersByEmails = users;+ _emailTotalRecords = totalCount;++ StateHasChanged();+ }+ catch (Exception ex)+ {+ GlobalNotificationService.AddErrorMessage($"Error loading email statistics: {ex.Message}");+ }+ }}\ No newline at end of filediff --git a/apps/server/AliasVault.Admin/Services/StatisticsService.cs b/apps/server/AliasVault.Admin/Services/StatisticsService.csindex b1a66c3fa..3516df5b1 100644--- a/apps/server/AliasVault.Admin/Services/StatisticsService.cs+++ b/apps/server/AliasVault.Admin/Services/StatisticsService.cs@@ -87,8 +87,9 @@ public class StatisticsServicestats.TotalEmailAttachments = results[3];// Get top users data- stats.TopUsersByStorage = await GetTopUsersByStorageAsync();- stats.TopUsersByAliases = await GetTopUsersByAliasesAsync();+ stats.TopUsersByStorage = await GetTopUsersByStorageAsync(10);+ stats.TopUsersByAliases = await GetTopUsersByAliasesAsync(10);+ stats.TopUsersByEmails = await GetTopUsersByEmailsAsync(10);stats.TopIpAddresses = await GetTopIpAddressesAsync();return stats;@@ -115,6 +116,126 @@ public class StatisticsServicereturn stats;}+ /// <summary>+ /// Gets paginated top users by storage size.+ /// </summary>+ /// <param name="page">Page number (1-based).</param>+ /// <param name="pageSize">Number of items per page.</param>+ /// <returns>Paginated list of top users by storage with total count.</returns>+ public async Task<(List<TopUserByStorage> Users, int TotalCount)> GetTopUsersByStoragePaginatedAsync(int page, int pageSize)+ {+ await using var context = await _contextFactory.CreateDbContextAsync();++ // Get total count+ var totalCount = await context.Vaults+ .GroupBy(v => v.UserId)+ .CountAsync();++ // Get paginated data+ var topUsers = await context.Vaults+ .GroupBy(v => v.UserId)+ .Select(g => new+ {+ UserId = g.Key,+ Username = g.First().User.UserName,+ TotalStorageBytes = g.OrderByDescending(v => v.Version).First().FileSize,+ })+ .OrderByDescending(u => u.TotalStorageBytes)+ .Skip((page - 1) * pageSize)+ .Take(pageSize)+ .ToListAsync();++ var users = topUsers.Select(u => new TopUserByStorage+ {+ UserId = u.UserId,+ Username = u.Username ?? UnknownUsername,+ StorageBytes = u.TotalStorageBytes,+ StorageDisplaySize = FormatKilobytes(u.TotalStorageBytes),+ }).ToList();++ return (users, totalCount);+ }++ /// <summary>+ /// Gets paginated top users by number of aliases.+ /// </summary>+ /// <param name="page">Page number (1-based).</param>+ /// <param name="pageSize">Number of items per page.</param>+ /// <returns>Paginated list of top users by aliases with total count.</returns>+ public async Task<(List<TopUserByAliases> Users, int TotalCount)> GetTopUsersByAliasesPaginatedAsync(int page, int pageSize)+ {+ await using var context = await _contextFactory.CreateDbContextAsync();++ // Get total count+ var totalCount = await context.UserEmailClaims+ .Where(uec => uec.UserId != null)+ .GroupBy(uec => uec.UserId)+ .CountAsync();++ // Get paginated data+ var topUsers = await context.UserEmailClaims+ .Where(uec => uec.UserId != null)+ .GroupBy(uec => uec.UserId)+ .Select(g => new+ {+ UserId = g.Key,+ Username = g.First().User!.UserName,+ AliasCount = g.Count(),+ })+ .OrderByDescending(u => u.AliasCount)+ .Skip((page - 1) * pageSize)+ .Take(pageSize)+ .ToListAsync();++ var users = topUsers.Select(u => new TopUserByAliases+ {+ UserId = u.UserId!,+ Username = u.Username ?? UnknownUsername,+ AliasCount = u.AliasCount,+ }).ToList();++ return (users, totalCount);+ }++ /// <summary>+ /// Gets paginated top users by number of emails.+ /// </summary>+ /// <param name="page">Page number (1-based).</param>+ /// <param name="pageSize">Number of items per page.</param>+ /// <returns>Paginated list of top users by emails with total count.</returns>+ public async Task<(List<TopUserByEmails> Users, int TotalCount)> GetTopUsersByEmailsPaginatedAsync(int page, int pageSize)+ {+ await using var context = await _contextFactory.CreateDbContextAsync();++ // Get total count+ var totalCount = await context.Emails+ .GroupBy(e => e.EncryptionKey.UserId)+ .CountAsync();++ // Get paginated data+ var topUsers = await context.Emails+ .GroupBy(e => e.EncryptionKey.UserId)+ .Select(g => new+ {+ UserId = g.Key,+ Username = g.First().EncryptionKey.User!.UserName,+ EmailCount = g.Count(),+ })+ .OrderByDescending(u => u.EmailCount)+ .Skip((page - 1) * pageSize)+ .Take(pageSize)+ .ToListAsync();++ var users = topUsers.Select(u => new TopUserByEmails+ {+ UserId = u.UserId!,+ Username = u.Username ?? UnknownUsername,+ EmailCount = u.EmailCount,+ }).ToList();++ return (users, totalCount);+ }+/// <summary>/// Gets user-specific usage statistics for both all-time and recent periods./// </summary>@@ -267,10 +388,11 @@ public class StatisticsService}/// <summary>- /// Gets the top 10 users by vault storage size.+ /// Gets the top users by vault storage size./// </summary>+ /// <param name="limit">Number of top users to retrieve.</param>/// <returns>List of top users by storage.</returns>- private async Task<List<TopUserByStorage>> GetTopUsersByStorageAsync()+ private async Task<List<TopUserByStorage>> GetTopUsersByStorageAsync(int limit = 10){await using var context = await _contextFactory.CreateDbContextAsync();@@ -284,7 +406,7 @@ public class StatisticsServiceTotalStorageBytes = g.OrderByDescending(v => v.Version).First().FileSize,}).OrderByDescending(u => u.TotalStorageBytes)- .Take(10)+ .Take(limit).ToListAsync();return topUsers.Select(u => new TopUserByStorage@@ -297,10 +419,11 @@ public class StatisticsService}/// <summary>- /// Gets the top 10 users by number of email aliases.+ /// Gets the top users by number of email aliases./// </summary>+ /// <param name="limit">Number of top users to retrieve.</param>/// <returns>List of top users by aliases.</returns>- private async Task<List<TopUserByAliases>> GetTopUsersByAliasesAsync()+ private async Task<List<TopUserByAliases>> GetTopUsersByAliasesAsync(int limit = 10){await using var context = await _contextFactory.CreateDbContextAsync();var topUsers = await context.UserEmailClaims@@ -313,7 +436,7 @@ public class StatisticsServiceAliasCount = g.Count(),}).OrderByDescending(u => u.AliasCount)- .Take(10)+ .Take(limit).ToListAsync();return topUsers.Select(u => new TopUserByAliases@@ -324,6 +447,34 @@ public class StatisticsService}).ToList();}+ /// <summary>+ /// Gets the top users by number of emails stored.+ /// </summary>+ /// <param name="limit">Number of top users to retrieve.</param>+ /// <returns>List of top users by emails.</returns>+ private async Task<List<TopUserByEmails>> GetTopUsersByEmailsAsync(int limit = 10)+ {+ await using var context = await _contextFactory.CreateDbContextAsync();+ var topUsers = await context.Emails+ .GroupBy(e => e.EncryptionKey.UserId)+ .Select(g => new+ {+ UserId = g.Key,+ Username = g.First().EncryptionKey.User!.UserName,+ EmailCount = g.Count(),+ })+ .OrderByDescending(u => u.EmailCount)+ .Take(limit)+ .ToListAsync();++ return topUsers.Select(u => new TopUserByEmails+ {+ UserId = u.UserId!,+ Username = u.Username ?? UnknownUsername,+ EmailCount = u.EmailCount,+ }).ToList();+ }+/// <summary>/// Gets the top 10 IP address ranges by number of associated user accounts./// Only includes non-anonymized IPs (not "xxx.xxx.xxx.xxx").