Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 54 additions & 15 deletions app/src/components/settings/delete-account.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,14 +62,17 @@ import {
import { signInAgainAtProvider } from "@/lib/account-deletion/reauthenticate";
import { signOutMutationOptions } from "@/lib/auth/mutations";
import { currentUserQueryOptions } from "@/lib/auth/queries";
import { isOrganizationAdmin } from "@/lib/auth/roles";
import { ClientError } from "@/lib/client";
import { deploymentCapabilitiesQueryOptions } from "@/lib/deployment/queries";
import { failureSaid } from "@/lib/load-failure";
import { useCurrentOrganizationId } from "@/lib/organizations/current";
import { switchOrganizationMutationOptions } from "@/lib/organizations/mutations";
import { ownOrganizationsQueryOptions } from "@/lib/organizations/queries";
import { queryClient } from "@/query-client";

const ORGANIZATION_SETTINGS = "/settings/organization";
const ADMIN_COMPUTERS = "/admin/computers";
const GENERAL_SETTINGS = "/settings";

/**
Expand Down Expand Up @@ -166,6 +169,7 @@ export function DeleteAccountSection() {
/** One organization that stops the account being deleted, and the one thing to do there. */
function BlockerRow({ blocker }: { blocker: AccountDeletionBlocker }) {
const [leaving, setLeaving] = useState(false);
const adminThere = useAdminOf(blocker.organizationId);
const organization = {
id: blocker.organizationId,
name: blocker.organizationName,
Expand All @@ -181,12 +185,26 @@ function BlockerRow({ blocker }: { blocker: AccountDeletionBlocker }) {
</ItemDescription>
</ItemContent>
{/* Under the words on a phone, as on Organization's members: a button beside them squeezes them.
A blocker with nothing to do here (a Windows computer an admin settles) has no actions at all,
so its row keeps no empty line under the words. */}
A blocker with nothing to do here (a Windows computer, for somebody who isn't an admin there)
has no actions at all, so its row keeps no empty line under the words. */}
{settledInItsSettings(blocker) ? (
<ItemActions className="max-sm:basis-full">
<OpenOrganizationSettings organizationId={blocker.organizationId} />
<OpenInOrganization
label="Open its settings"
organizationId={blocker.organizationId}
to={ORGANIZATION_SETTINGS}
/>
</ItemActions>
) : blocker.reason === "windows_computer" ? (
adminThere ? (
<ItemActions className="max-sm:basis-full">
<OpenInOrganization
label="Open Computers"
organizationId={blocker.organizationId}
to={ADMIN_COMPUTERS}
/>
</ItemActions>
) : null
) : settledByLeaving(blocker) ? (
<ItemActions className="max-sm:basis-full">
<Button onClick={() => setLeaving(true)} size="sm" variant="outline">
Expand All @@ -210,36 +228,57 @@ function BlockerRow({ blocker }: { blocker: AccountDeletionBlocker }) {
}

/**
* An organization's settings, where its owner makes someone else an owner or deletes it. The
* settings are the one the person works in, so another one is switched to first, as the account
* menu switches.
* Whether the person is an admin (or the owner) of an organization, as the list of their
* organizations says: Computers, where a Windows computer is removed or forgotten, is an admin's,
* and sends anybody else home. Where OpenBot keeps one organization and lists none, the one they
* work in, as they are signed in to it.
*/
function useAdminOf(organizationId: string): boolean {
const mine = useQuery(ownOrganizationsQueryOptions()).data;
const user = useQuery(currentUserQueryOptions()).data;
const current = useCurrentOrganizationId();
const listed = mine?.organizations.find((one) => one.id === organizationId);
if (listed) return isOrganizationAdmin(listed.role);
return organizationId === current && isOrganizationAdmin(user?.role);
}

/**
* A page of an organization: its settings, where its owner makes someone else an owner or deletes
* it, or Computers, where its admin removes or forgets a Windows computer. Both are the one the
* person works in, so another one is switched to first, as the account menu switches.
*
* The page is opened once the switch has finished, never as the switch's `leave`: that runs before
* the app changes over, so Admin's gate would read the person as they are in the organization being
* left, and send somebody who is only a member there home.
*/
function OpenOrganizationSettings({
function OpenInOrganization({
label,
organizationId,
to,
}: {
label: string;
organizationId: string;
to: typeof ORGANIZATION_SETTINGS | typeof ADMIN_COMPUTERS;
}) {
const navigate = useNavigate();
const current = useCurrentOrganizationId();
const open = () => navigate({ to: ORGANIZATION_SETTINGS });
const switching = useMutation(
switchOrganizationMutationOptions(queryClient, async () => {
await open();
}),
);
const open = () => navigate({ to });
const switching = useMutation(switchOrganizationMutationOptions(queryClient));
return (
<div className="flex flex-col items-end gap-1 max-sm:items-start">
<Button
disabled={switching.isPending}
onClick={() =>
organizationId === current
? void open()
: switching.mutate(organizationId)
: void switching.mutateAsync(organizationId).then(open, () => {
// Said under the button, from the mutation's error.
})
}
size="sm"
variant="outline"
>
{switching.isPending ? "Opening…" : "Open its settings"}
{switching.isPending ? "Opening…" : label}
</Button>
{switching.error ? (
<p className="text-destructive text-sm" role="alert">
Expand Down
24 changes: 24 additions & 0 deletions app/src/lib/auth/admin-gate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import type { QueryClient } from "@tanstack/react-query";
import { redirect } from "@tanstack/react-router";
import { deploymentCapabilitiesQueryOptions } from "../deployment/queries";
import { currentUserQueryOptions } from "./queries";
import { isOrganizationAdmin } from "./roles";

/**
* Admin's gate: Admin is for an admin of the organization the person is working in, in every
* edition, and anybody else is sent home. In the personal edition the one person is the admin:
* single-user mode signs them in as one (`DEV_ACTOR` on the server).
*
* The edition is read first, though nothing here depends on it: a page that draws something else
* in the personal edition (`components/edition/for-a-team.tsx`) then knows which on its first
* frame. One that could not be read is the team edition, as everywhere else.
*/
export async function adminGate(queryClient: QueryClient): Promise<void> {
await queryClient
.ensureQueryData(deploymentCapabilitiesQueryOptions())
.catch(() => undefined);
const user = await queryClient.ensureQueryData(currentUserQueryOptions());
if (!isOrganizationAdmin(user?.role)) {
throw redirect({ to: "/" });
}
}
27 changes: 4 additions & 23 deletions app/src/routes/_authed/admin/route.tsx
Original file line number Diff line number Diff line change
@@ -1,34 +1,15 @@
import { createFileRoute, Outlet, redirect } from "@tanstack/react-router";
import { createFileRoute, Outlet } from "@tanstack/react-router";
import { AdminSidebar } from "@/components/admin/admin-sidebar";
import { ConnectionBanner } from "@/components/layout/connection-banner";
import { PlanBanner } from "@/components/layout/plan-banner";
import { SidebarShell } from "@/components/layout/sidebar-shell";
import { SidebarInset } from "@/components/ui/sidebar";
import { BotListScopeProvider } from "@/lib/agents/list-scope";
import { isOrganizationAdmin } from "@/lib/auth/roles";
import { deploymentCapabilitiesQueryOptions } from "@/lib/deployment/queries";
import { currentUserQueryOptions } from "../../../lib/auth/queries";
import { adminGate } from "@/lib/auth/admin-gate";

export const Route = createFileRoute("/_authed/admin")({
/*
* Admin is for an admin, in every edition. In the personal edition the one person is the admin:
* single-user mode signs them in as one (`DEV_ACTOR` on the server).
*
* The edition is read first, though nothing here depends on it: a page that draws something else
* in the personal edition (`components/edition/for-a-team.tsx`) then knows which on its first
* frame. One that could not be read is the team edition, as everywhere else.
*/
beforeLoad: async ({ context }) => {
await context.queryClient
.ensureQueryData(deploymentCapabilitiesQueryOptions())
.catch(() => undefined);
const user = await context.queryClient.ensureQueryData(
currentUserQueryOptions(),
);
if (!isOrganizationAdmin(user?.role)) {
throw redirect({ to: "/" });
}
},
// Admin is for an admin of the organization the person works in (lib/auth/admin-gate.ts).
beforeLoad: ({ context }) => adminGate(context.queryClient),
component: RouteComponent,
});

Expand Down
71 changes: 66 additions & 5 deletions app/tests/delete-account.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ import {
RequestAccountDeletionHeader,
RequestAccountDeletionResponse,
} from "@/lib/api/generated/people/people.zod";
import { adminGate } from "@/lib/auth/admin-gate";
import { signedInUser } from "@/lib/auth/queries";
import { ReportedErrorComponent } from "@/lib/error-reporting";
import {
Expand Down Expand Up @@ -126,6 +127,8 @@ let server: {
| null;
/** The operation isn't served: an OpenBot older than it. */
older: boolean;
/** Dana's role in each organization, where it isn't owner. */
roles: Record<string, "admin" | "member">;
/** Which product the deployment says it is; the personal edition doesn't serve the operation. */
edition: "team" | "personal";
/** The sign-in providers the deployment offers, and the ones the person signed in through. */
Expand Down Expand Up @@ -308,7 +311,7 @@ async function answer(
return checked(ListOrganizationsResponse, {
organizations: ORGANIZATIONS.map((one) => ({
...one,
role: "owner",
role: server.roles[one.id] ?? "owner",
active: one.id === server.active,
})),
canCreate: true,
Expand All @@ -335,7 +338,8 @@ async function answer(
name: "Dana Fresh",
needsName: false,
image: null,
role: "owner",
// As the server answers it: the role they have in the organization asked about.
role: server.roles[organization] ?? "owner",
onboarding: null,
providers: server.signedInWith,
lastSignedInAt: null,
Expand Down Expand Up @@ -365,6 +369,7 @@ beforeEach(() => {
deleted: false,
refuse: null,
older: false,
roles: {},
edition: "team",
providers: [],
signedInWith: [],
Expand Down Expand Up @@ -432,6 +437,13 @@ async function open(start = "/settings") {
at("/", () => <p>Home</p>),
at("/sign", () => <p>Sign in</p>),
at("/settings/organization", () => <p>Organization settings</p>),
createRoute({
getParentRoute: () => rootRoute,
path: "/admin/computers",
// Admin's own gate, which sends anybody who isn't an admin where they work home.
beforeLoad: () => adminGate(queryClient),
component: () => <p>Computers</p>,
}),
at("/settings", () => (
<PageShell title="General">
<DeleteAccountSection />
Expand Down Expand Up @@ -554,7 +566,7 @@ describe("deleting your account", () => {
);
});

test("a Windows computer OpenBot made is listed with who settles it, and offers no Leave, which wouldn't", async () => {
test("a Windows computer OpenBot made is listed with who settles it, offers no Leave, which wouldn't, and opens Computers for an admin there", async () => {
server.blockers = [WINDOWS];
const app = await open();
const acme = (await app.view.findByText("Acme")).closest(
Expand All @@ -569,13 +581,62 @@ describe("deleting your account", () => {
expect(
within(acme).queryByRole("button", { name: "Open its settings" }),
).toBeNull();
// No empty actions area: on a phone it would wrap onto a line of its own under the words.
expect(acme.querySelector("[data-slot=item-actions]")).toBeNull();
expect(
app.view
.getByRole("button", { name: "Delete account" })
.hasAttribute("disabled"),
).toBe(true);
// Computers is the organization's own: it is switched to first.
await app.person.click(
await within(acme).findByRole("button", { name: "Open Computers" }),
);
await waitFor(() =>
expect(app.router.state.location.pathname).toBe("/admin/computers"),
);
expect(server.active).toBe("org_acme");
expect(currentOrganizationId()).toBe("org_acme");
});

test("Open Computers takes an admin of the computer's organization who is only a member where she works there, not home", async () => {
server.blockers = [WINDOWS];
server.roles = { org_dana: "member", org_acme: "admin" };
const app = await open();
const acme = (await app.view.findByText("Acme")).closest(
"[data-slot=item]",
) as HTMLElement;
await app.person.click(
await within(acme).findByRole("button", { name: "Open Computers" }),
);
// Admin's gate reads her as she is in Acme, after the switch, never as a member where she was.
await waitFor(() => expect(currentOrganizationId()).toBe("org_acme"));
await waitFor(() =>
expect(app.router.state.location.pathname).toBe("/admin/computers"),
);
expect(await app.view.findByText("Computers")).toBeTruthy();
});

test("a Windows computer where the person isn't an admin offers nothing to open, which would send them home", async () => {
// Beside it, one where she is an admin, so the list of her organizations has been read.
server.blockers = [
WINDOWS,
{ ...WINDOWS, organizationId: "org_globex", organizationName: "Globex" },
];
server.roles = { org_acme: "member", org_globex: "admin" };
const app = await open();
const row = async (name: string) =>
(await app.view.findByText(name)).closest(
"[data-slot=item]",
) as HTMLElement;
const acme = await row("Acme");
await within(await row("Globex")).findByRole("button", {
name: "Open Computers",
});
expect(acme.textContent).toContain(
"An admin removes or forgets it under Computers first.",
);
expect(within(acme).queryByRole("button")).toBeNull();
// No empty actions area: on a phone it would wrap onto a line of its own under the words.
expect(acme.querySelector("[data-slot=item-actions]")).toBeNull();
});

test("the dialog's Delete account waits for both the email address and the phrase, GitHub style", async () => {
Expand Down
Loading