Skip to content

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

47.5 KB
Raw Blame
@page "/users/{Id}"
@using AliasServerDb.Legacy
@using AliasServerDb.Retention
@using AliasVault.Admin.Main.Pages.Users.View.Components
@using AliasVault.Admin.Main.Models
@using AliasVault.Admin.Services
@using AliasVault.Auth
@using AliasVault.Shared.Models.Enums
@using AliasVault.Shared.Server.Services
@using Microsoft.EntityFrameworkCore
@inherits MainBase
@inject StatisticsService StatisticsService
@inject ServerSettingsService SettingsService
@inject ILogger<Index> Logger

<LayoutPageTitle>User</LayoutPageTitle>

@if (IsLoading || User == null)
{
    <LoadingIndicator/>
}
else
{
    <PageHeader
        BreadcrumbItems="@BreadcrumbItems"
        Title="View user"
        Description="View details of the user below.">
        <CustomActions>
            <RefreshButton OnClick="RefreshData" ButtonText="Refresh" />
            <LinkButton Color="danger" Href="@($"users/{Id}/delete")" Text="Delete user" />
        </CustomActions>
    </PageHeader>

    <div class="grid grid-cols-2 px-4 pt-6 md:grid-cols-3 lg:gap-4 dark:bg-gray-900">
        <div class="col-span-full">
            <div class="p-4 mb-4 bg-white border border-gray-200 rounded-lg shadow-sm dark:border-gray-700 sm:p-6 dark:bg-gray-800">
                <div class="items-center xl:block sm:space-x-4 xl:space-x-0 2xl:space-x-4">
                    <div>
                        <div class="mb-4 border-b border-gray-200 dark:border-gray-700 pb-2">
                            <div class="flex items-center gap-2">
                                <h3 class="text-2xl font-bold text-gray-900 dark:text-white">@User.UserName</h3>
                                @if (!IsEditingUsername)
                                {
                                    <button type="button" id="edit-username-button" @onclick="StartEditingUsername"
                                            class="inline-flex items-center justify-center px-3 py-2 text-sm font-medium text-white rounded-lg focus:outline-none focus:ring-4 bg-gray-700 hover:bg-gray-800 focus:ring-gray-300 dark:bg-gray-600 dark:hover:bg-gray-700 dark:focus:ring-gray-800"
                                            title="Change username">
                                        <UiIcon Icon="UiIcons.PencilAlt" class="w-4 h-4" />
                                    </button>
                                }
                            </div>
                        </div>

                        @if (IsEditingUsername)
                        {
                            <div class="mb-4 space-y-3 p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
                                <div class="mb-3">
                                    <div class="flex items-center mb-2">
                                        <UiIcon Icon="UiIcons.Exclamation" class="w-5 h-5 text-orange-600 dark:text-orange-400 mr-2" />
                                        <h4 class="text-lg font-semibold text-gray-900 dark:text-white">Change Username</h4>
                                    </div>
                                    <p class="text-sm text-gray-600 dark:text-gray-300 mb-3">
                                        Changing a username is permanent and may affect the user's ability to log in.
                                    </p>
                                </div>
                                <div class="space-y-3">
                                    <div>
                                        <label class="block mb-1 text-sm font-medium text-gray-900 dark:text-white">New Username</label>
                                        <input type="text" @bind="NewUsername" placeholder="Enter new username"
                                               class="bg-white border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-500 focus:border-primary-500 block w-full max-w-md p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500" />
                                        @if (!string.IsNullOrEmpty(UsernameValidationError))
                                        {
                                            <p class="text-sm text-red-600 dark:text-red-400 mt-1">@UsernameValidationError</p>
                                        }
                                    </div>
                                    <div class="flex space-x-2 pt-2">
                                        <Button Color="danger" OnClick="ChangeUsername">Change Username</Button>
                                        <Button Color="secondary" OnClick="CancelEditingUsername">Cancel</Button>
                                    </div>
                                </div>
                            </div>
                        }

                        <!-- Usage Statistics Section -->
                        @if (UserUsageStats != null)
                        {
                            <div class="mb-6 bg-gray-100 dark:bg-gray-700 rounded-lg p-4">
                                <h4 class="text-lg font-semibold text-gray-900 dark:text-white text-center mb-3">Usage Statistics</h4>
                                <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                                    <div>
                                        <div class="text-xl text-center font-semibold text-gray-900 dark:text-white">@UserUsageStats.TotalCredentials.ToString("N0")</div>
                                        <div class="text-sm text-center text-gray-600 dark:text-gray-400">Credentials</div>
                                    </div>
                                    <div>
                                        <div class="text-xl text-center font-semibold text-gray-900 dark:text-white">@UserUsageStats.ActiveEmailClaims.ToString("N0")</div>
                                        <div class="text-sm text-center text-gray-600 dark:text-gray-400">Active email aliases</div>
                                    </div>
                                    <div>
                                        <div class="text-xl text-center font-semibold text-gray-900 dark:text-white">@UserUsageStats.TotalReceivedEmails.ToString("N0")</div>
                                        <div class="text-sm text-center text-gray-600 dark:text-gray-400">Emails received</div>
                                    </div>
                                </div>
                            </div>
                        }

                        <div class="w-full mb-4 overflow-x-auto">
                            <table class="w-full text-sm text-left text-gray-500 dark:text-gray-400">
                                <tbody>
                                    <tr class="">
                                        <th scope="row" class="px-4 py-3 font-medium text-gray-900 whitespace-nowrap dark:text-white">Registered at (UTC)</th>
                                        <td class="px-4 py-3">@User.CreatedAt.ToString("yyyy-MM-dd HH:mm")</td>
                                    </tr>
                                    <tr>
                                        <th scope="row" class="px-4 py-3 font-medium text-gray-900 whitespace-nowrap dark:text-white">2FA Status</th>
                                        <td class="px-4 py-3">
                                            <div class="flex items-center space-x-2">
                                                <StatusPill Enabled="@User.TwoFactorEnabled"/>
                                                <span class="text-gray-700 dark:text-gray-300">Authenticator key(s) active: @TwoFactorKeysCount</span>
                                                @if (User.TwoFactorEnabled)
                                                {
                                                    <Button Color="danger" OnClick="DisableTwoFactor">Disable 2FA</Button>
                                                }
                                                else
                                                {
                                                    if (TwoFactorKeysCount > 0)
                                                    {
                                                        <Button Color="success" OnClick="EnableTwoFactor">Enable 2FA</Button>
                                                        <Button Color="danger" OnClick="ResetTwoFactor">Remove 2FA keys</Button>
                                                    }
                                                }
                                            </div>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th scope="row" class="px-4 py-3 font-medium text-gray-900 whitespace-nowrap dark:text-white">Account Status</th>
                                        <td class="px-4 py-3">
                                            <div class="flex items-center space-x-2">
                                                <StatusPill Enabled="@(!User.Blocked)" TextTrue="Active" TextFalse="Blocked" />
                                                @if (User.Blocked && User.BlockedAt is not null)
                                                {
                                                    <span class="text-sm text-gray-500 dark:text-gray-400">since @User.BlockedAt.Value.ToString("yyyy-MM-dd HH:mm") UTC</span>
                                                }
                                                <Button Color="@(User.Blocked ? "success" : "danger")" OnClick="ToggleBlockStatus">
                                                    @(User.Blocked ? "Unblock User" : "Block User")
                                                </Button>
                                                <span class="text-sm text-gray-500 dark:text-gray-400">
                                                    <i class="fas fa-info-circle mr-1"></i>
                                                    Blocking a user prevents them from logging in or accessing AliasVault
                                                </span>
                                            </div>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th scope="row" class="px-4 py-3 font-medium text-gray-900 whitespace-nowrap dark:text-white">Email Limits</th>
                                        <td class="px-4 py-3">
                                            @if (!IsEditingEmailLimits)
                                            {
                                                <div class="flex flex-col space-y-2">
                                                    <div class="flex items-center space-x-2">
                                                        <span class="text-gray-700 dark:text-gray-300">
                                                            <strong>Max Emails:</strong> @(User.PersonalGroup.MaxEmails == 0 ? "Unlimited" : User.PersonalGroup.MaxEmails.ToString("N0"))
                                                        </span>
                                                    </div>
                                                    <div class="flex items-center space-x-2">
                                                        <span class="text-gray-700 dark:text-gray-300">
                                                            <strong>Max Age:</strong> @(User.PersonalGroup.MaxEmailAgeDays == 0 ? "Unlimited" : User.PersonalGroup.MaxEmailAgeDays + " days")
                                                        </span>
                                                    </div>
                                                    <div class="mt-2">
                                                        <Button Color="primary" OnClick="@(() => StartEditingEmailLimits())">Edit Limits</Button>
                                                    </div>
                                                </div>
                                            }
                                            else
                                            {
                                                <div class="space-y-3 p-3 bg-gray-50 dark:bg-gray-700 rounded-lg">
                                                    <div>
                                                        <label class="block mb-1 text-sm font-medium text-gray-900 dark:text-white">Max Emails</label>
                                                        <div class="flex items-center space-x-2">
                                                            <input type="number" min="0" @bind="EditMaxEmails" class="bg-white border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-500 focus:border-primary-500 block w-32 p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500" />
                                                            <span class="text-sm text-gray-500 dark:text-gray-400">(0 = unlimited)</span>
                                                        </div>
                                                    </div>
                                                    <div>
                                                        <label class="block mb-1 text-sm font-medium text-gray-900 dark:text-white">Max Email Age</label>
                                                        <div class="flex items-center space-x-2">
                                                            <input type="number" min="0" @bind="EditMaxEmailAgeDays" class="bg-white border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-500 focus:border-primary-500 block w-32 p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500" />
                                                            <span class="text-sm text-gray-500 dark:text-gray-400">days (0 = unlimited)</span>
                                                        </div>
                                                    </div>
                                                    <div class="flex space-x-2 pt-2">
                                                        <Button Color="success" OnClick="SaveEmailLimits">Save</Button>
                                                        <Button Color="secondary" OnClick="CancelEditingEmailLimits">Cancel</Button>
                                                    </div>
                                                </div>
                                            }
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <div class="p-4 mb-4 bg-white border border-gray-200 rounded-lg shadow-sm dark:border-gray-700 sm:p-6 dark:bg-gray-800">
                <div class="items-center">
                    <div>
                        <h3 class="mb-1 text-xl font-bold text-gray-900 dark:text-white">Vault storage</h3>
                        <p class="mb-3 text-sm text-gray-500 dark:text-gray-400">
                            A vault is stored as a manifest, one or more data buckets and optional blob objects (attachments).
                        </p>

                        <div class="mb-6 bg-gray-100 dark:bg-gray-700 rounded-lg p-4">
                            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                                <div>
                                    <div class="text-xl text-center font-semibold text-gray-900 dark:text-white">@StatisticsService.FormatBytes(StorageOverview.ManifestBytes)</div>
                                    <div class="text-sm text-center text-gray-600 dark:text-gray-400">@StorageOverview.ManifestRevisions.Count manifest revisions</div>
                                </div>
                                <div>
                                    <div class="text-xl text-center font-semibold text-gray-900 dark:text-white">@StatisticsService.FormatBytes(StorageOverview.BucketBytes)</div>
                                    <div class="text-sm text-center text-gray-600 dark:text-gray-400">@StorageOverview.BucketRevisions.Count bucket revisions</div>
                                </div>
                                <div>
                                    <div class="text-xl text-center font-semibold text-gray-900 dark:text-white">@StatisticsService.FormatBytes(StorageOverview.BlobBytes)</div>
                                    <div class="text-sm text-center text-gray-600 dark:text-gray-400">@StorageOverview.BlobCount.ToString("N0") blob objects</div>
                                </div>
                                <div>
                                    <div class="text-xl text-center font-semibold text-gray-900 dark:text-white">@StatisticsService.FormatBytes(StorageOverview.TotalBytes)</div>
                                    <div class="text-sm text-center text-gray-600 dark:text-gray-400">Total</div>
                                </div>
                            </div>
                            @if (StorageOverview.UnreferencedBlobCount > 0)
                            {
                                <p class="mt-4 text-sm text-center text-gray-600 dark:text-gray-400">
                                    @StorageOverview.UnreferencedBlobCount.ToString("N0") blob objects (@StatisticsService.FormatBytes(StorageOverview.UnreferencedBlobBytes))
                                    are no longer referenced by any manifest revision and become reclaimable once the revisions that used them age out.
                                </p>
                            }
                        </div>

                        <h4 class="mb-2 text-lg font-semibold text-gray-900 dark:text-white">Manifest revisions (@StorageOverview.ManifestRevisions.Count)</h4>
                        <ManifestTable Revisions="@StorageOverview.ManifestRevisions" AllowRevertToLegacy="@(!TakesPartInSharing)" OnMakeCurrent="@MakeCurrentAsync" OnRevertToLegacy="@RevertToLegacyAsync" />

                        <h4 class="mt-6 mb-2 text-lg font-semibold text-gray-900 dark:text-white">Data bucket revisions</h4>
                        <DataBucketTable Revisions="@StorageOverview.BucketRevisions" OnRestore="@RestoreBucketAsync" />

                        <h4 class="mt-6 mb-2 text-lg font-semibold text-gray-900 dark:text-white">Blob objects (@StorageOverview.BlobCount.ToString("N0"))</h4>
                        <BlobUsageTable Categories="@StorageOverview.BlobCategories" />
                    </div>
                </div>
            </div>

            <div class="p-4 mb-4 bg-white border border-gray-200 rounded-lg shadow-sm dark:border-gray-700 sm:p-6 dark:bg-gray-800">
                <div class="items-center">
                    <div>
                        <h3 class="mb-1 text-xl font-bold text-gray-900 dark:text-white">Previous master passwords (@PasswordHistoryList.Count)</h3>
                        <p class="mb-3 text-sm text-gray-500 dark:text-gray-400">
                            Allows to revert a password change in case of a failure. Historic records are automatically deleted after the configured Password Revert Window.
                        </p>

                        <PasswordHistoryTable PasswordHistoryList="@PasswordHistoryList" RetentionDays="@UnlockMethodHistoryRetentionDays" OnRevert="@RevertPasswordChangeAsync" />
                    </div>
                </div>
            </div>

            <div class="p-4 mb-4 bg-white border border-gray-200 rounded-lg shadow-sm dark:border-gray-700 sm:p-6 dark:bg-gray-800">
                <div class="items-center">
                    <div>
                        <h3 class="mb-1 text-xl font-bold text-gray-900 dark:text-white">Logged in devices (@RefreshTokenList.Count)</h3>

                        <RefreshTokenTable RefreshTokenList="@RefreshTokenList" OnRevokeToken="@RevokeRefreshToken" OnRevokeAllTokens="@RevokeAllTokens" />
                    </div>
                </div>
            </div>

            <div class="p-4 mb-4 bg-white border border-gray-200 rounded-lg shadow-sm dark:border-gray-700 sm:p-6 dark:bg-gray-800">
                <div class="items-center">
                    <div>
                        <h3 class="mb-1 text-xl font-bold text-gray-900 dark:text-white">Recent authentication logs (@AuthLogList.Count)</h3>
                        <p class="text-sm text-gray-500 dark:text-gray-400">
                            Shows the last 5 authentication attempts for this user. Click "View all auth logs" to see complete history.
                        </p>
                        <AuthLogTable Username="@(User.UserName ?? string.Empty)" AuthLogList="@AuthLogList" />
                    </div>
                </div>
            </div>

            <div class="p-4 mb-4 bg-white border border-gray-200 rounded-lg shadow-sm dark:border-gray-700 sm:p-6 dark:bg-gray-800">
                <div class="items-center">
                    <div>
                        <h3 class="mb-1 text-xl font-bold text-gray-900 dark:text-white">Email aliases (@EmailClaimsCount)</h3>
                        <p class="text-sm text-gray-500 dark:text-gray-400">
                            Every email address this user's vault has ever claimed.
                        </p>
                        <EmailClaimTable User="@User" @ref="EmailClaimTableRef" OnCountChanged="HandleCountChanged" />
                    </div>
                </div>
            </div>
        </div>
    </div>
}

@code {
    /// <summary>
    /// Gets or sets the user ID.
    /// </summary>
    [Parameter]
    public string Id { get; set; } = string.Empty;

    private bool IsLoading { get; set; } = true;
    private AliasVaultUser? User { get; set; } = new();
    private int TwoFactorKeysCount { get; set; }
    private List<AliasVaultUserRefreshToken> RefreshTokenList { get; set; } = [];
    private VaultStorageOverview StorageOverview { get; set; } = new();
    private List<UserUnlockMethodsHistory> PasswordHistoryList { get; set; } = [];
    private int UnlockMethodHistoryRetentionDays { get; set; }
    private bool HasManifestAccessKeys { get; set; }
    private bool TakesPartInSharing { get; set; }
    private List<AuthLog> AuthLogList { get; set; } = [];
    private UserUsageStatistics? UserUsageStats { get; set; }
    private bool IsEditingEmailLimits { get; set; }
    private int EditMaxEmails { get; set; }
    private int EditMaxEmailAgeDays { get; set; }
    private bool IsEditingUsername { get; set; }
    private string NewUsername { get; set; } = string.Empty;
    private string UsernameValidationError { get; set; } = string.Empty;
    private EmailClaimTable? EmailClaimTableRef { get; set; }

    private int EmailClaimsCount => EmailClaimTableRef?.GetTotalEmailClaimsCount() ?? 0;

    /// <inheritdoc />
    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        BreadcrumbItems.Add(new BreadcrumbItem { DisplayName = "Users", Url = "users" });
        BreadcrumbItems.Add(new BreadcrumbItem { DisplayName = "View user" });
    }

    /// <inheritdoc />
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);

        if (firstRender)
        {
            await RefreshData();
        }
    }

    /// <inheritdoc />
    protected override async Task OnParametersSetAsync()
    {
        await base.OnParametersSetAsync();

        // Refresh data when navigating to a different user (e.g., clicking related user links)
        if (!IsLoading && User?.Id != Id)
        {
            await RefreshData();
        }
    }

    private async Task RefreshData()
    {
        IsLoading = true;
        StateHasChanged();

        // Load the aliases from the webapi via AliasService. Eager-load the personal group as it holds the user's email limits.
        await using var dbContext = await DbContextFactory.CreateDbContextAsync();
        User = await dbContext.AliasVaultUsers.Include(u => u.PersonalGroup).FirstOrDefaultAsync(u => u.Id == Id);

        // Get count of user authenticator tokens.
        TwoFactorKeysCount = await dbContext.UserTokens.CountAsync(x => x.UserId == User!.Id && x.Name == "AuthenticatorKey");

        if (User is null)
        {
            // Error loading user.
            GlobalNotificationService.AddErrorMessage("This user does not exist (anymore). Please try again.");
            NavigationService.RedirectTo("users");
            return;
        }

        // Load all active refresh tokens for this user to show which devices are logged in.
        RefreshTokenList = await dbContext.AliasVaultUserRefreshTokens.Where(x => x.UserId == User.Id).Select(x => new AliasVaultUserRefreshToken()
            {
                Id = x.Id,
                DeviceIdentifier = x.DeviceIdentifier,
                IpAddress = x.IpAddress,
                ExpireDate = x.ExpireDate,
                CreatedAt = x.CreatedAt,
            })
            .Where(x => x.ExpireDate > DateTime.UtcNow)
            .OrderBy(x => x.CreatedAt)
            .ToListAsync();

        // Load the storage breakdown of the user's personal vault: manifest and bucket revisions plus blob usage.
        StorageOverview = await VaultStorageQueries.GetPersonalVaultStorageAsync(dbContext, User.PersonalGroupId);

        // Whether the user is on the key model where the vault manifest no longer carries the login credentials.
        HasManifestAccessKeys = await dbContext.VaultManifestAccessKeys.AnyAsync(x => x.UserId == User.Id);

        // Whether this user can still be taken back to the legacy storage format, the escape hatch for a bad migration.
        TakesPartInSharing = await TakesPartInSharingAsync(dbContext, User.Id);

        // Load the archived master password credentials that are still inside the retention window.
        UnlockMethodHistoryRetentionDays = (await SettingsService.GetAllSettingsAsync()).UnlockMethodHistoryRetentionDays;
        PasswordHistoryList = await UnlockMethodHistoryPolicy
            .WithinRetention(dbContext.UserUnlockMethodsHistory.Where(x => x.UserId == User.Id), UnlockMethodHistoryRetentionDays, DateTime.UtcNow)
            .OrderByDescending(x => x.ArchivedAt)
            .ToListAsync();

        // Load recent auth logs for this user (last 3 records).
        AuthLogList = await dbContext.AuthLogs
            .Where(x => x.Username == User.UserName)
            .OrderByDescending(x => x.Timestamp)
            .Take(5)
            .ToListAsync();

        // Load user usage statistics
        try
        {
            UserUsageStats = await StatisticsService.GetUserUsageStatisticsAsync(User.Id);
        }
        catch (Exception ex)
        {
            GlobalNotificationService.AddErrorMessage($"Error loading user usage statistics: {ex.Message}");
            UserUsageStats = null;
        }

        IsLoading = false;
        StateHasChanged();
    }

    /// <summary>
    /// This method will revoke a refresh token for the user which will log out the device.
    /// </summary>
    private async Task RevokeRefreshToken(AliasVaultUserRefreshToken entry)
    {
        await using var dbContext = await DbContextFactory.CreateDbContextAsync();
        var token = await dbContext.AliasVaultUserRefreshTokens.FindAsync(entry.Id);

        if (token != null)
        {
            dbContext.AliasVaultUserRefreshTokens.Remove(token);
            await dbContext.SaveChangesAsync();
            await RefreshData();
        }
    }

    /// <summary>
    /// This method enables two-factor authentication for the user based on existing keys. If no keys are present
    /// then 2FA will not work. The user will need to manually set up a new authenticator device.
    /// </summary>
    private async Task EnableTwoFactor()
    {
        await using var dbContext = await DbContextFactory.CreateDbContextAsync();
        User = await dbContext.AliasVaultUsers.FindAsync(Id);

        if (User != null)
        {
            User.TwoFactorEnabled = true;
            await dbContext.SaveChangesAsync();
            await RefreshData();
        }
    }

    /// <summary>
    /// This method disables two-factor authentication for the user. This will not remove the authenticator keys.
    /// This means the admin can re-enable 2FA for the user without the user having to set up a new authenticator
    /// keys.
    /// </summary>
    private async Task DisableTwoFactor()
    {
        await using var dbContext = await DbContextFactory.CreateDbContextAsync();
        User = await dbContext.AliasVaultUsers.FindAsync(Id);

        if (User != null)
        {
            User.TwoFactorEnabled = false;
            await dbContext.SaveChangesAsync();
            await RefreshData();
        }
    }

    /// <summary>
    /// This method resets the two-factor authentication for the user which will remove all authenticator keys. The
    /// next time the user enables two-factor authentication new keys will be generated. When keys are removed it
    /// also means 2FA cannot be re-enabled until the user manually sets up a new authenticator device.
    /// </summary>
    private async Task ResetTwoFactor()
    {
        await using var dbContext = await DbContextFactory.CreateDbContextAsync();
        User = await dbContext.AliasVaultUsers.FindAsync(Id);

        if (User != null)
        {
            // Remove all authenticator keys and recovery codes.
            await dbContext.UserTokens
                .Where(x => x.UserId == User.Id && (x.Name == "AuthenticatorKey" || x.Name == "RecoveryCodes"))
                .ForEachAsync(x => dbContext.UserTokens.Remove(x));

            await dbContext.SaveChangesAsync();
            await RefreshData();
        }
    }

    /// <summary>
    /// Handles the action of restoring a manifest history revision as the current one. The current revision is
    /// archived into history first, then the chosen history revision's payload is copied onto the current row with a
    /// new (higher) revision number so the monotonic revision sequence is preserved for client concurrency checks.
    /// </summary>
    /// <param name="revision">The manifest revision to make current.</param>
    private async Task MakeCurrentAsync(ManifestRevisionRow revision)
    {
        if (revision.IsCurrent)
        {
            // Already the current revision; nothing to restore.
            return;
        }

        await using var dbContext = await DbContextFactory.CreateDbContextAsync();

        var passwordNote = HasManifestAccessKeys
            ? "• The user's master password is not affected; use \"Previous master passwords\" to revert a password change."
            : "• If the user has changed their password recently, their password will be reverted to the one associated with this vault.";
        if (await ConfirmModalService.ShowConfirmation(
                title: "Confirm Manifest Restoration",
                message: $@"Are you sure you want to restore this specific manifest revision and make it the active one?

Important notes:
• The next time the user logs in, they will load this vault version.
{passwordNote}
• Data buckets and blob objects are not rolled back with it.
• All active sessions will be revoked and the user will need to login again on all devices.

Do you want to proceed with the restoration?")) {
            // Load the current row and the full history revision (including its blob payload).
            var currentVault = await dbContext.VaultManifests.FindAsync(revision.ManifestId);
            var revisionToRestore = await dbContext.VaultManifestsHistory.FindAsync(revision.ManifestId, revision.RevisionNumber);
            if (currentVault == null || revisionToRestore == null)
            {
                return;
            }

            // Crossing storage formats leaves the account with a vault its keys cannot open, so it only ever happens
            // through the deliberate revert action below.
            if (currentVault.StorageFormat != revisionToRestore.StorageFormat)
            {
                GlobalNotificationService.AddErrorMessage("This revision is in a different vault storage format than the one the account is on and cannot be restored. Restoring it would leave the account unable to open its vault.", true);
                return;
            }

            // Archive the current revision into history first, then copy the restored payload onto the current row
            // with a new revision number one above the previous current.
            var newRevisionNumber = currentVault.RevisionNumber + 1;
            dbContext.VaultManifestsHistory.Add(VaultManifestsHistory.CreateFrom(currentVault));
            currentVault.CopyPayloadFrom(revisionToRestore);
            currentVault.RevisionNumber = newRevisionNumber;

            // The restored revision moves out of history; re-key its blob references to the new revision number.
            dbContext.VaultManifestsHistory.Remove(revisionToRestore);
            await dbContext.VaultBlobReferences
                .Where(r => r.ManifestId == currentVault.ManifestId && r.RevisionNumber == revision.RevisionNumber)
                .ExecuteUpdateAsync(s => s.SetProperty(r => r.RevisionNumber, newRevisionNumber));

            // Save it.
            await dbContext.SaveChangesAsync();

            // Revoke all user sessions to force re-authentication with potentially reverted password
            await RevokeAllTokens();
            Logger.LogInformation("Revoked all sessions for user {UserName} ({UserId}) after vault restoration to revision {RevisionNumber}.",
                User!.UserName, User.Id, currentVault.RevisionNumber);

            // Reload the page.
            await RefreshData();
        }
    }

    /// <summary>
    /// Whether the user holds any state that only exists on the current storage format because of vault sharing: a
    /// grant on a shared manifest, a membership of a shared group, or an invitation encrypted to their account keypair.
    /// Reverting such a user would delete the keypair all of that is encrypted to, so the revert is not offered.
    /// </summary>
    /// <param name="dbContext">The database context to query.</param>
    /// <param name="userId">The user to check.</param>
    /// <returns>True when the user takes part in vault sharing.</returns>
    private static async Task<bool> TakesPartInSharingAsync(AliasServerDbContext dbContext, string userId)
    {
        return await dbContext.VaultManifestAccessKeys.AnyAsync(x => x.UserId == userId && x.Type == ManifestKeyType.GrantKey)
            || await dbContext.GroupMembers.AnyAsync(x => x.UserId == userId && x.Group.Type != GroupType.Personal)
            || await dbContext.VaultManifestInvitations.AnyAsync(x => x.InviteeUserId == userId);
    }

    /// <summary>
    /// Handles the action of putting the user back on the legacy storage format by making a pre-migration revision
    /// current again. This is the escape hatch for a migration that went wrong: it tears down everything the
    /// manifest format added so the account can be opened by a v1 client and migrate a second time.
    /// </summary>
    /// <param name="revision">The pre-migration revision to revert to.</param>
    private async Task RevertToLegacyAsync(ManifestRevisionRow revision)
    {
        await using var dbContext = await DbContextFactory.CreateDbContextAsync();

        // Re-check against the database rather than trusting the state the page was rendered with.
        if (await TakesPartInSharingAsync(dbContext, User!.Id))
        {
            GlobalNotificationService.AddErrorMessage("This user can no longer be reverted to the legacy vault storage format because it takes part in vault sharing.", true);
            await RefreshData();
            return;
        }

        if (!await ConfirmModalService.ShowConfirmation(
                title: "Confirm Revert To Legacy Format",
                message: $@"Are you sure you want to revert this user to the legacy sqlite-blob vault storage format, using revision {revision.RevisionNumber}?

This is meant as a recovery step for a migration that went wrong. All migrated data and any updates done since the migration will be lost. It cannot be undone.

Do you want to proceed with the revert?"))
        {
            return;
        }

        var newRevisionNumber = await LegacyVaultRollback.RevertAsync(DbContextFactory, User.Id, revision.ManifestId, revision.RevisionNumber);

        Logger.LogWarning("Reverted user {UserName} ({UserId}) to the legacy vault storage format using revision {RevisionNumber}, now current at revision {NewRevisionNumber}. Account keys removed and all sessions revoked.",
            User.UserName, User.Id, revision.RevisionNumber, newRevisionNumber);
        GlobalNotificationService.AddSuccessMessage("User reverted to the legacy vault storage format. They can log in again with the master password that belonged to this vault revision.", true);

        await RefreshData();
    }

    /// <summary>
    /// Handles the action of restoring a data bucket history revision as the current one.
    /// </summary>
    /// <param name="revision">The bucket revision to make current.</param>
    private async Task RestoreBucketAsync(BucketRevisionRow revision)
    {
        if (revision.IsCurrent)
        {
            // Already the current revision; nothing to restore.
            return;
        }

        await using var dbContext = await DbContextFactory.CreateDbContextAsync();

        var currentBucket = await dbContext.VaultDataBuckets.FindAsync(revision.ManifestId, revision.Category);
        var revisionToRestore = await dbContext.VaultDataBucketsHistory.FindAsync(revision.ManifestId, revision.Category, revision.RevisionNumber);
        if (currentBucket == null || revisionToRestore == null)
        {
            return;
        }

        var newRevisionNumber = currentBucket.RevisionNumber + 1;
        dbContext.VaultDataBucketsHistory.Add(VaultDataBucketsHistory.CreateFrom(currentBucket));
        currentBucket.CopyPayloadFrom(revisionToRestore);
        currentBucket.RevisionNumber = newRevisionNumber;
        dbContext.VaultDataBucketsHistory.Remove(revisionToRestore);

        await dbContext.SaveChangesAsync();

        Logger.LogInformation("Restored the {Category} data bucket of user {UserName} ({UserId}) to revision {RevisionNumber}.",
            revision.Category, User!.UserName, User.Id, newRevisionNumber);

        await RefreshData();
    }

    /// <summary>
    /// Toggles the blocked status of the user.
    /// </summary>
    private async Task ToggleBlockStatus()
    {
        await using var dbContext = await DbContextFactory.CreateDbContextAsync();
        User = await dbContext.AliasVaultUsers.FindAsync(Id);

        if (User != null)
        {
            User.Blocked = !User.Blocked;

            // Record when the block was activated; clear the trace again when the user is unblocked.
            if (User.Blocked)
            {
                User.BlockedAt = DateTime.UtcNow;
            }
            else
            {
                User.BlockedAt = null;
            }

            // If user is unblocked by the admin, also reset any lockout status, which can be
            // automatically triggered by the system when user has entered an incorrect password too many times.
            if (!User.Blocked) {
                User.AccessFailedCount = 0;
                User.LockoutEnd = null;
            }

            await dbContext.SaveChangesAsync();

            // Add log entry for block/unblock action
            var action = User.Blocked ? "Blocked" : "Unblocked";
            Logger.LogInformation("{Action} user {UserName} ({UserId}).", action, User.UserName, User.Id);

            await RefreshData();
        }
    }

    /// <summary>
    /// Restore a previous master password credential to the user's current one.
    /// </summary>
    /// <param name="entry">The archived credential to restore.</param>
    private async Task RevertPasswordChangeAsync(UserUnlockMethodsHistory entry)
    {
        await using var dbContext = await DbContextFactory.CreateDbContextAsync();
        var now = DateTime.UtcNow;

        // Re-read the row under the retention window to ensure it is still available.
        var archived = await UnlockMethodHistoryPolicy
            .WithinRetention(dbContext.UserUnlockMethodsHistory.Where(x => x.Id == entry.Id && x.UserId == User!.Id), UnlockMethodHistoryRetentionDays, now)
            .FirstOrDefaultAsync();

        if (archived == null)
        {
            GlobalNotificationService.AddErrorMessage("This previous password is no longer available. It has passed the retention window and has been discarded.", true);
            await RefreshData();
            return;
        }

        var unlockMethod = await dbContext.UserUnlockMethods.FirstOrDefaultAsync(x => x.UserId == User!.Id && x.Type == archived.Type);
        if (unlockMethod == null)
        {
            GlobalNotificationService.AddErrorMessage("This user no longer has an unlock method of this type to revert.", true);
            return;
        }

        var strategy = dbContext.Database.CreateExecutionStrategy();
        await strategy.ExecuteAsync(async () =>
        {
            await using var writeContext = await DbContextFactory.CreateDbContextAsync();
            await using var transaction = await writeContext.Database.BeginTransactionAsync();

            var target = await writeContext.UserUnlockMethods.FirstAsync(x => x.Id == unlockMethod.Id);
            var source = await writeContext.UserUnlockMethodsHistory.FirstAsync(x => x.Id == archived.Id);

            await writeContext.AliasVaultUsers.Where(x => x.Id == User!.Id).ExecuteUpdateAsync(s => s.SetProperty(x => x.PasswordChangedAt, now));
            await writeContext.AliasVaultUserRefreshTokens.Where(x => x.UserId == User!.Id).ExecuteDeleteAsync();
            writeContext.UserUnlockMethodsHistory.Remove(source);
            await writeContext.SaveChangesAsync();
            await UnlockMethodHistoryPolicy.ArchiveAsync(writeContext, target, UnlockMethodHistoryRetentionDays, now, "admin-revert");
            source.RestoreOnto(target, now);

            await writeContext.SaveChangesAsync();
            await transaction.CommitAsync();
        });

        Logger.LogWarning("Reverted master password for user {UserName} ({UserId}) to the credential archived at {ArchivedAt}. All sessions revoked.", User!.UserName, User.Id, archived.ArchivedAt);
        GlobalNotificationService.AddSuccessMessage("Master password reverted. The user can log in again with the password they used before the change. All sessions have been revoked.", true);

        await RefreshData();
    }

    /// <summary>
    /// Revoke all refresh tokens for the user which will log out all their devices.
    /// </summary>
    private async Task RevokeAllTokens()
    {
        await using var dbContext = await DbContextFactory.CreateDbContextAsync();
        var tokens = await dbContext.AliasVaultUserRefreshTokens.Where(x => x.UserId == User!.Id).ToListAsync();

        if (tokens.Any())
        {
            dbContext.AliasVaultUserRefreshTokens.RemoveRange(tokens);
            await dbContext.SaveChangesAsync();
            await RefreshData();
        }
    }

    /// <summary>
    /// Starts editing email limits for the user.
    /// </summary>
    private void StartEditingEmailLimits()
    {
        IsEditingEmailLimits = true;
        EditMaxEmails = User!.PersonalGroup.MaxEmails;
        EditMaxEmailAgeDays = User.PersonalGroup.MaxEmailAgeDays;
    }

    /// <summary>
    /// Cancels editing email limits.
    /// </summary>
    private void CancelEditingEmailLimits()
    {
        IsEditingEmailLimits = false;
        EditMaxEmails = 0;
        EditMaxEmailAgeDays = 0;
    }

    /// <summary>
    /// Saves the email limits for the user.
    /// </summary>
    private async Task SaveEmailLimits()
    {
        await using var dbContext = await DbContextFactory.CreateDbContextAsync();
        var personalGroup = await dbContext.Groups.FirstOrDefaultAsync(g => dbContext.AliasVaultUsers.Any(u => u.Id == Id && u.PersonalGroupId == g.Id));

        if (personalGroup != null)
        {
            personalGroup.MaxEmails = EditMaxEmails;
            personalGroup.MaxEmailAgeDays = EditMaxEmailAgeDays;
            await dbContext.SaveChangesAsync();
            IsEditingEmailLimits = false;
            await RefreshData();
            GlobalNotificationService.AddSuccessMessage("Email limits updated successfully.", true);
        }
    }

    /// <summary>
    /// Starts editing username for the user.
    /// </summary>
    private void StartEditingUsername()
    {
        IsEditingUsername = true;
        NewUsername = User!.UserName ?? string.Empty;
        UsernameValidationError = string.Empty;
    }

    /// <summary>
    /// Cancels editing username.
    /// </summary>
    private void CancelEditingUsername()
    {
        IsEditingUsername = false;
        NewUsername = string.Empty;
        UsernameValidationError = string.Empty;
    }

    /// <summary>
    /// Changes the username for the user with validation.
    /// </summary>
    private async Task ChangeUsername()
    {
        // Normalize to lowercase and trim to match how usernames are stored at registration.
        NewUsername = UsernameHelper.NormalizeUsername(NewUsername);

        if (string.IsNullOrWhiteSpace(NewUsername))
        {
            UsernameValidationError = "Username cannot be empty.";
            return;
        }

        if (NewUsername.Length < 3)
        {
            UsernameValidationError = "Username must be at least 3 characters long.";
            return;
        }

        if (NewUsername.Length > 256)
        {
            UsernameValidationError = "Username cannot be longer than 256 characters.";
            return;
        }

        if (NewUsername == User!.UserName)
        {
            UsernameValidationError = "New username must be different from current username.";
            return;
        }

        await using var dbContext = await DbContextFactory.CreateDbContextAsync();

        // Check if username already exists
        var existingUser = await dbContext.AliasVaultUsers.FirstOrDefaultAsync(x => x.UserName == NewUsername);
        if (existingUser != null)
        {
            UsernameValidationError = "This username is already in use by another user.";
            return;
        }

        // Reload user to ensure we have the latest data
        User = await dbContext.AliasVaultUsers.FindAsync(Id);
        if (User != null)
        {
            var oldUsername = User.UserName;
            User.UserName = NewUsername;
            User.NormalizedUserName = NewUsername.ToUpperInvariant();
            User.Email = NewUsername;
            User.NormalizedEmail = NewUsername.ToUpperInvariant();
            User.UpdatedAt = DateTime.UtcNow;

            try
            {
                await dbContext.SaveChangesAsync();

                // Add log entry for username change
                Logger.LogInformation("Changed username for user {OldUsername} ({UserId}) to {NewUsername}.", oldUsername, User.Id, NewUsername);

                IsEditingUsername = false;
                UsernameValidationError = string.Empty;
                await RefreshData();
                GlobalNotificationService.AddSuccessMessage($"Username changed from '{oldUsername}' to '{NewUsername}' successfully.", true);
            }
            catch (Exception ex)
            {
                UsernameValidationError = $"Error updating username: {ex.Message}";
            }
        }
    }

    /// <summary>
    /// Handle count changes from child components to trigger re-render.
    /// </summary>
    private void HandleCountChanged()
    {
        StateHasChanged();
    }
}