Skip to content

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

10.9 KB
Raw Blame
@page "/users/invites"
@using AliasVault.Admin.Main.Components.Tables
@using AliasVault.Shared.Server.Services
@inject RegistrationInviteService RegistrationInviteService
@inherits MainBase

<LayoutPageTitle>Invites</LayoutPageTitle>

<PageHeader
    BreadcrumbItems="@BreadcrumbItems"
    Title="Invites"
    Description="Invite links let new users create an account while public registration is disabled in the server settings. When public registration is enabled, invites are not needed.">
    <CustomActions>
        <RefreshButton OnClick="RefreshData" ButtonText="Refresh" />
    </CustomActions>
</PageHeader>

<div class="p-4 mb-4 mx-4 bg-white border border-gray-200 rounded-lg shadow-sm dark:border-gray-700 sm:p-6 dark:bg-gray-800">
    <h3 class="mb-4 text-lg font-medium text-gray-900 dark:text-white">Create invite</h3>
    <div class="flex flex-col gap-4 max-w-md mb-4">
        <div>
            <label for="maxUses" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Number of accounts</label>
            <input type="number" min="1" max="1000" @bind="MaxUses" id="maxUses" 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">How many accounts may register with this invite</p>
        </div>
        <div>
            <label for="expiresInDays" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Valid for (days)</label>
            <input type="number" min="0" max="3650" @bind="ExpiresInDays" id="expiresInDays" 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">0 = never expires</p>
        </div>
        <div>
            <label for="note" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Note (optional)</label>
            <input type="text" @bind="Note" id="note" maxlength="255" placeholder="e.g. who the invite is for" 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">
        </div>
    </div>
    <Button OnClick="CreateInvite">Create invite</Button>
</div>

<div class="p-4 mb-4 mx-4 bg-white border border-gray-200 rounded-lg shadow-sm dark:border-gray-700 sm:p-6 dark:bg-gray-800">
    <h3 class="mb-4 text-lg font-medium text-gray-900 dark:text-white">Invites</h3>
    @if (IsLoading)
    {
        <LoadingIndicator />
    }
    else if (InviteList.Count == 0)
    {
        <p class="text-sm text-gray-500 dark:text-gray-400">No invites created yet.</p>
    }
    else
    {
        <SortableTable Columns="@_tableColumns" SortColumn="@SortColumn" SortDirection="@SortDirection" OnSortChanged="HandleSortChanged">
            @foreach (var invite in SortedInviteList)
            {
                <SortableTableRow>
                    <SortableTableColumn IsPrimary="true">@invite.CreatedAt.ToString("yyyy-MM-dd HH:mm")</SortableTableColumn>
                    <SortableTableColumn>@(invite.Note ?? "-")</SortableTableColumn>
                    <SortableTableColumn>@invite.UseCount / @invite.MaxUses</SortableTableColumn>
                    <SortableTableColumn>@(invite.ExpiresAt?.ToString("yyyy-MM-dd HH:mm") ?? "Never")</SortableTableColumn>
                    <SortableTableColumn>@(invite.LastUsedAt?.ToString("yyyy-MM-dd HH:mm") ?? "-")</SortableTableColumn>
                    <SortableTableColumn>
                        <StatusPill Enabled="@IsUsable(invite)" TextTrue="Active" TextFalse="@(invite.UseCount >= invite.MaxUses ? "Used" : "Expired")" />
                    </SortableTableColumn>
                    <SortableTableColumn>
                        <div class="flex gap-2">
                            @if (IsUsable(invite))
                            {
                                <Button OnClick="() => ShowLink(invite, false)">Show link</Button>
                            }
                            <Button Color="danger" OnClick="() => DeleteInvite(invite)">Delete</Button>
                        </div>
                    </SortableTableColumn>
                </SortableTableRow>
            }
        </SortableTable>
    }
</div>

@if (LinkInvite is not null)
{
    <div class="fixed inset-0 z-[1000]">
        <div class="fixed inset-0 bg-gray-600/50 backdrop-blur-sm dark:bg-black/70"></div>
        <div class="fixed inset-0 overflow-y-auto">
            <div class="flex min-h-full items-center justify-center p-4" @onclick="CloseLink">
                <div class="relative w-full max-w-2xl rounded-lg border border-gray-200 bg-white p-6 shadow-xl dark:border-gray-600 dark:bg-gray-800 dark:shadow-2xl" @onclick:stopPropagation="true">
                    <h3 class="text-lg font-medium text-gray-900 dark:text-white">@(LinkIsNew ? "Invite created" : "Invite link")@(LinkInvite.Note is null ? string.Empty : $" for \"{LinkInvite.Note}\"")</h3>
                    <p class="mt-1 mb-4 text-sm text-gray-500 dark:text-gray-400">
                        Send this link to the person you are inviting. It can register @LinkInvite.MaxUses @(LinkInvite.MaxUses == 1 ? "account" : "accounts")
                        @(LinkInvite.ExpiresAt is null ? "and never expires." : $"until {LinkInvite.ExpiresAt:yyyy-MM-dd HH:mm} UTC.")
                    </p>
                    <CopyField Value="@BuildLink(LinkInvite.Code)" />
                    <p class="mt-3 text-xs text-gray-500 dark:text-gray-400">The link assumes the web app is served from the current host address. If you host AliasVault on a different public address, update the URL accordingly.</p>
                    <div class="mt-6 flex justify-end">
                        <Button Color="secondary" OnClick="CloseLink">Close</Button>
                    </div>
                </div>
            </div>
        </div>
    </div>
}

@code {
    private readonly List<TableColumn> _tableColumns = [
        new TableColumn { Title = "Created (UTC)", PropertyName = "CreatedAt" },
        new TableColumn { Title = "Note", PropertyName = "Note" },
        new TableColumn { Title = "Used", PropertyName = "UseCount" },
        new TableColumn { Title = "Expires (UTC)", PropertyName = "ExpiresAt" },
        new TableColumn { Title = "Last used (UTC)", PropertyName = "LastUsedAt" },
        new TableColumn { Title = "Status", Sortable = false },
        new TableColumn { Title = "Actions", Sortable = false },
    ];

    private List<RegistrationInvite> InviteList { get; set; } = [];
    private bool IsLoading { get; set; } = true;
    private string SortColumn { get; set; } = "CreatedAt";
    private SortDirection SortDirection { get; set; } = SortDirection.Descending;

    private string? Note { get; set; }
    private int MaxUses { get; set; } = 1;
    private int ExpiresInDays { get; set; } = 3;
    private RegistrationInvite? LinkInvite { get; set; }
    private bool LinkIsNew { get; set; }

    private IEnumerable<RegistrationInvite> SortedInviteList => SortColumn switch
    {
        "Note" => SortableTable.SortListByProperty(InviteList, x => x.Note, SortDirection),
        "UseCount" => SortableTable.SortListByProperty(InviteList, x => x.UseCount, SortDirection),
        "ExpiresAt" => SortableTable.SortListByProperty(InviteList, x => x.ExpiresAt, SortDirection),
        "LastUsedAt" => SortableTable.SortListByProperty(InviteList, x => x.LastUsedAt, SortDirection),
        _ => SortableTable.SortListByProperty(InviteList, x => x.CreatedAt, SortDirection),
    };

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

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

    private static bool IsUsable(RegistrationInvite invite) => invite.UseCount < invite.MaxUses && (invite.ExpiresAt == null || invite.ExpiresAt > DateTime.UtcNow);

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

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

        await using var dbContext = await DbContextFactory.CreateDbContextAsync();
        InviteList = await dbContext.RegistrationInvites.AsNoTracking().OrderByDescending(x => x.CreatedAt).ToListAsync();

        IsLoading = false;
        StateHasChanged();
    }

    private async Task CreateInvite()
    {
        if (MaxUses < 1 || MaxUses > 1000 || ExpiresInDays < 0 || ExpiresInDays > 365)
        {
            GlobalNotificationService.AddErrorMessage("Number of accounts must be between 1 and 1000, and valid for between 0 and 365 days.", true);
            return;
        }

        DateTime? expiresAt = ExpiresInDays > 0 ? DateTime.UtcNow.AddDays(ExpiresInDays) : null;
        var code = await RegistrationInviteService.CreateAsync(Note, MaxUses, expiresAt, GetUsername());
        Note = null;

        await RefreshData();

        var normalized = RegistrationInviteService.NormalizeCode(code);
        var created = InviteList.FirstOrDefault(x => x.Code == normalized);
        if (created is not null)
        {
            ShowLink(created, true);
        }
    }

    private void ShowLink(RegistrationInvite invite, bool isNew)
    {
        LinkInvite = invite;
        LinkIsNew = isNew;
    }

    private void CloseLink()
    {
        LinkInvite = null;
    }

    private string BuildLink(string code) => new Uri(new Uri(NavigationService.BaseUri), "/user/setup?invite=" + RegistrationInviteService.FormatCode(RegistrationInviteService.NormalizeCode(code))).ToString();

    private async Task DeleteInvite(RegistrationInvite invite)
    {
        if (!await ConfirmModalService.ShowConfirmation("Delete invite", "Are you sure you want to delete this invite? It can no longer be used to register. Accounts already registered with it are not affected."))
        {
            return;
        }

        await using var dbContext = await DbContextFactory.CreateDbContextAsync();
        await dbContext.RegistrationInvites.Where(x => x.Id == invite.Id).ExecuteDeleteAsync();
        await RefreshData();
    }
}