Skip to content

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

9.2 KB
Raw Blame
@using AliasVault.Admin.Main.Components.Tables

<div class="d-flex justify-content-between mb-3">
    <div class="flex items-center space-x-2 mt-2">
        <Button Color="secondary" OnClick="ToggleShowRemoved">
            @(ShowRemoved ? "Hide removed aliases" : "Show removed aliases")
        </Button>
        @if (EmailClaimList.Any(e => e.State != EmailClaimState.Removed))
        {
            <Button Color="danger" OnClick="RemoveAllEmailClaims">Disable All</Button>
        }
    </div>
</div>

@if (IsLoading)
{
    <LoadingIndicator />
}
else
{
    <SortableTable Columns="@_emailClaimTableColumns" SortColumn="@SortColumn" SortDirection="@SortDirection" OnSortChanged="HandleSortChanged">
        @foreach (var entry in SortedEmailClaimList)
        {
            <SortableTableRow Class="@(entry.State == EmailClaimState.Removed ? "bg-secondary" : "")">
                <SortableTableColumn IsPrimary="true">@entry.Id</SortableTableColumn>
                <SortableTableColumn>@entry.CreatedAt.ToString("yyyy-MM-dd HH:mm")</SortableTableColumn>
                <SortableTableColumn><a href="emails?search=@entry.Address">@entry.Address</a></SortableTableColumn>
                <SortableTableColumn>@entry.EmailCount</SortableTableColumn>
                <SortableTableColumn>
                    @switch (entry.State)
                    {
                        case EmailClaimState.Active:
                            <StatusPill Enabled="true" TextTrue="Active" />
                            break;
                        case EmailClaimState.Paused:
                            <span class="bg-yellow-100 text-yellow-800 text-xs font-medium px-2.5 py-0.5 rounded dark:bg-yellow-900 dark:text-yellow-300" title="The user switched this alias off. Stored mail stays readable, new mail is rejected.">Paused</span>
                            break;
                        default:
                            <StatusPill Enabled="false" TextFalse="Removed" />
                            break;
                    }
                </SortableTableColumn>
                <SortableTableColumn>
                    @if (entry.State == EmailClaimState.Removed)
                    {
                        <Button Color="success" OnClick="() => SetClaimStateAsync(entry, EmailClaimState.Active)">Enable</Button>
                    }
                    else
                    {
                        <Button Color="danger" OnClick="() => SetClaimStateAsync(entry, EmailClaimState.Removed)">Disable</Button>
                    }
                </SortableTableColumn>
            </SortableTableRow>
        }
    </SortableTable>
}

@code {
    /// <summary>
    /// Gets or sets the user.
    /// </summary>
    [Parameter]
    public AliasVaultUser User { get; set; } = new();

    /// <summary>
    /// Gets or sets the event callback for when the count changes.
    /// </summary>
    [Parameter]
    public EventCallback OnCountChanged { get; set; }

    /// <summary>
    /// Gets or sets the list of email claims to display.
    /// </summary>
    private List<EmailClaimWithCount> EmailClaimList { get; set; } = [];

    private bool IsLoading { get; set; } = true;

    private string SortColumn { get; set; } = "CreatedAt";
    private SortDirection SortDirection { get; set; } = SortDirection.Descending;
    private bool ShowRemoved { get; set; } = false;

    private readonly List<TableColumn> _emailClaimTableColumns = [
        new TableColumn { Title = "ID", PropertyName = "Id" },
        new TableColumn { Title = "Created (UTC)", PropertyName = "CreatedAt" },
        new TableColumn { Title = "Email", PropertyName = "Address" },
        new TableColumn { Title = "Email Count", PropertyName = "EmailCount" },
        new TableColumn { Title = "Status", PropertyName = "State" },
        new TableColumn { Title = "Actions", PropertyName = "" },
    ];

    private IEnumerable<EmailClaimWithCount> SortedEmailClaimList =>
        SortList(ShowRemoved ? EmailClaimList : EmailClaimList.Where(e => e.State != EmailClaimState.Removed).ToList(), SortColumn, SortDirection);

    /// <inheritdoc />
    protected override async Task OnInitializedAsync()
    {
        IsLoading = true;
        StateHasChanged();

        await RefreshData();

        IsLoading = false;
        StateHasChanged();
    }

    /// <summary>
    /// Loads the claims owned by the user's personal manifest, in any state, with the number of stored emails per address.
    /// </summary>
    private async Task RefreshData()
    {
        await using var dbContext = await DbContextFactory.CreateDbContextAsync();

        if (string.IsNullOrEmpty(User.Id))
        {
            EmailClaimList = [];
            return;
        }

        var claims = await dbContext.EmailClaims
            .Where(c => c.VaultManifest!.OwnerGroupId == User.PersonalGroupId)
            .Select(c => new { c.Id, c.Address, c.CreatedAt, c.UpdatedAt, c.State })
            .OrderBy(x => x.CreatedAt)
            .ToListAsync();

        var addresses = claims.Select(x => x.Address).ToList();
        var emailCounts = await dbContext.Emails
            .Where(e => addresses.Contains(e.To))
            .GroupBy(e => e.To)
            .Select(g => new { Address = g.Key, Count = g.Count() })
            .ToDictionaryAsync(x => x.Address, x => x.Count);

        EmailClaimList = claims.Select(x => new EmailClaimWithCount
        {
            Id = x.Id,
            Address = x.Address,
            CreatedAt = x.CreatedAt,
            UpdatedAt = x.UpdatedAt,
            State = x.State,
            EmailCount = emailCounts.GetValueOrDefault(x.Address),
        }).ToList();

        // Notify parent that count has changed
        await OnCountChanged.InvokeAsync();
    }

    private void HandleSortChanged((string column, SortDirection direction) sort)
    {
        SortColumn = sort.column;
        SortDirection = sort.direction;
        StateHasChanged();
    }

    private void ToggleShowRemoved()
    {
        ShowRemoved = !ShowRemoved;
        StateHasChanged();
    }

    /// <summary>
    /// Sets the state of a claim owned by the personal manifest. Disabling marks it Removed, after which the
    /// server rejects mail for the address; enabling puts it back to Active. The user's next vault sync recomputes
    /// the state from their vault contents, so either change is undone as soon as the vault says otherwise.
    /// </summary>
    private async Task SetClaimStateAsync(EmailClaimWithCount entry, EmailClaimState state)
    {
        if (state == EmailClaimState.Removed && !await ConfirmModalService.ShowConfirmation(
            title: "Confirm Email Alias Disable",
            message: @"Are you sure you want to disable this email alias?

Important notes:
• Disabling an email alias means that emails will no longer be received for this address and will be rejected by the server.
• The user can re-enable this at will by re-saving their vault which will claim it again.

Do you want to proceed with disabling this alias?"))
        {
            return;
        }

        await using var dbContext = await DbContextFactory.CreateDbContextAsync();
        await dbContext.EmailClaims
            .Where(c => c.Id == entry.Id && c.VaultManifest!.OwnerGroupId == User.PersonalGroupId)
            .ExecuteUpdateAsync(s => s.SetProperty(c => c.State, state).SetProperty(c => c.UpdatedAt, DateTime.UtcNow));

        await RefreshData();
    }

    private async Task RemoveAllEmailClaims()
    {
        if (await ConfirmModalService.ShowConfirmation(
            title: "Confirm Email Alias Disable",
            message: @"Are you sure you want to disable all email aliases of this user?

Important notes:
• Disabling an email alias means that emails will no longer be received for this address and will be rejected by the server.
• The user can re-enable this at will by re-saving their vault which will claim it again.

Do you want to proceed with disabling all email aliases?"))
        {
            await using var dbContext = await DbContextFactory.CreateDbContextAsync();
            await dbContext.EmailClaims
                .Where(c => c.State != EmailClaimState.Removed && c.VaultManifest!.OwnerGroupId == User.PersonalGroupId)
                .ExecuteUpdateAsync(s => s.SetProperty(c => c.State, EmailClaimState.Removed));

            await RefreshData();
        }
    }

    private static IEnumerable<EmailClaimWithCount> SortList(List<EmailClaimWithCount> emailClaims, string sortColumn, SortDirection sortDirection)
    {
        return sortColumn switch
        {
            "Id" => SortableTable.SortListByProperty(emailClaims, e => e.Id, sortDirection),
            "CreatedAt" => SortableTable.SortListByProperty(emailClaims, e => e.CreatedAt, sortDirection),
            "Address" => SortableTable.SortListByProperty(emailClaims, e => e.Address, sortDirection),
            "EmailCount" => SortableTable.SortListByProperty(emailClaims, e => e.EmailCount, sortDirection),
            "State" => SortableTable.SortListByProperty(emailClaims, e => e.State, sortDirection),
            _ => emailClaims
        };
    }

    /// <summary>
    /// Gets the total count of email claims (including removed).
    /// </summary>
    public int GetTotalEmailClaimsCount()
    {
        return EmailClaimList.Count;
    }
}