Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

11.5 KB
Raw Blame
/* eslint-disable @repo/no-abstracted-overlay-trigger, @typescript-eslint/no-deprecated, @typescript-eslint/no-use-before-define -- Legacy UI usage retained during migration to design-system components. */
import Header from "@/src/components/layouts/header";
import { Card } from "@/src/components/ui/card";
import { Button } from "@/src/components/ui/button";
import { Input } from "@/src/components/ui/input";
import { api, reportNonTrpcError } from "@/src/utils/api";
import * as z from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormMessage,
} from "@/src/components/ui/form";
import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/src/components/ui/dialog";
import { useSession } from "next-auth/react";
import { signOutCleanly } from "@/src/features/auth/lib/signOut";
import { SettingsDangerZone } from "@/src/components/SettingsDangerZone";
import { StringNoHTML } from "@langfuse/shared";
import Link from "next/link";
import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
import { showErrorToast } from "@/src/features/notifications/showErrorToast";
import { ConfirmationDialogController } from "@/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController";
import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";

const displayNameSchema = z.object({
  name: StringNoHTML.min(1, "Name cannot be empty").max(
    100,
    "Name must be at most 100 characters",
  ),
});

function UpdateDisplayName() {
  const { data: session, update: updateSession } = useSession();
  const utils = api.useUtils();

  const form = useForm({
    resolver: zodResolver(displayNameSchema),
    defaultValues: {
      name: "",
    },
  });

  const updateDisplayName = api.userAccount.updateDisplayName.useMutation({
    onSuccess: async () => {
      await updateSession();
      await utils.invalidate();
      form.reset();
      showSuccessToast({
        operation: "account.display_name_update",
        title: "Display Name Updated",
        description: "Your display name has been successfully updated.",
      });
    },
    onError: (error) => form.setError("name", { message: error.message }),
  });

  function onSubmit(values: z.infer<typeof displayNameSchema>) {
    updateDisplayName.mutate({ name: values.name });
  }

  return (
    <div>
      <Header title="Display Name" />
      <Card className="p-3">
        {form.getValues().name !== "" ? (
          <p className="text-primary mb-4 text-sm">
            Your display name will be updated from &quot;
            {session?.user?.name ?? ""}
            &quot; to &quot;
            <b>{form.watch().name}</b>&quot;.
          </p>
        ) : (
          <p className="text-primary mb-4 text-sm">
            Your display name is currently &quot;
            <b>{session?.user?.name ?? ""}</b>
            &quot;.
          </p>
        )}
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="flex-1">
            <FormField
              control={form.control}
              name="name"
              render={({ field }) => (
                <FormItem>
                  <FormControl>
                    <Input
                      placeholder={session?.user?.name ?? ""}
                      {...field}
                      className="flex-1"
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <Button
              variant="secondary"
              type="submit"
              loading={updateDisplayName.isPending}
              disabled={form.getValues().name === ""}
              className="mt-4"
            >
              Save
            </Button>
          </form>
        </Form>
      </Card>
    </div>
  );
}

function DeleteAccountButton() {
  const { data: session } = useSession();
  const userEmail = session?.user?.email ?? "";

  const { data: canDeleteData } = api.userAccount.checkCanDelete.useQuery();
  const deleteAccount = api.userAccount.delete.useMutation();

  const formSchema = z.object({
    email: z.string().refine((val) => val === userEmail, {
      message: `Please enter your email address: ${userEmail}`,
    }),
  });

  const form = useForm({
    resolver: zodResolver(formSchema),
    defaultValues: {
      email: "",
    },
  });

  const canDelete = canDeleteData?.canDelete ?? false;
  const blockingOrganizations = canDeleteData?.blockingOrganizations ?? [];

  const onSubmit = async () => {
    if (!canDelete) return;
    try {
      await deleteAccount.mutateAsync();
      showSuccessToast({
        operation: "account.delete",
        title: "Account Deleted",
        description: "Your account has been successfully deleted.",
      });
      await new Promise((resolve) => setTimeout(resolve, 2000));
      await signOutCleanly();
    } catch (error) {
      reportNonTrpcError(error, "account");
      showErrorToast(
        "Failed to Delete Account",
        error instanceof Error ? error.message : "An unexpected error occurred",
        classifyTrpcToastError(error, "account.delete"),
      );
    }
  };

  return (
    <Dialog>
      <DialogTrigger asChild>
        <Button variant="destructive-secondary">Delete Account</Button>
      </DialogTrigger>
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle className="text-lg font-bold">
            Delete Account
          </DialogTitle>
          <DialogDescription>
            {!canDelete && blockingOrganizations.length > 0 ? (
              <div>
                <p className="mb-2">
                  You cannot delete your account because you are the last owner
                  of the following organization(s):
                </p>
                <ul className="list-inside list-disc space-y-1">
                  {blockingOrganizations.map((org) => (
                    <li key={org.id}>
                      <Link
                        href={`/organization/${org.id}/settings`}
                        className="text-primary hover:text-primary/80 font-bold underline"
                      >
                        {org.name}
                      </Link>
                    </li>
                  ))}
                </ul>
                <p className="mt-2">
                  Please add another owner or delete these organizations before
                  deleting your account.
                </p>
              </div>
            ) : (
              `To confirm, type your email address "${userEmail}" in the input box`
            )}
          </DialogDescription>
        </DialogHeader>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
            {canDelete && (
              <DialogBody>
                <FormField
                  control={form.control}
                  name="email"
                  render={({ field }) => (
                    <FormItem>
                      <FormControl>
                        <Input placeholder={userEmail} {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </DialogBody>
            )}
            <DialogFooter>
              <Button
                type="submit"
                variant="destructive"
                loading={deleteAccount.isPending}
                disabled={!canDelete}
                className="w-full"
              >
                Delete Account
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}

function SignOutAllSessionsButton() {
  const signOutAllSessions = api.userAccount.signOutAllSessions.useMutation();

  const onConfirm = async () => {
    try {
      await signOutAllSessions.mutateAsync();
      showSuccessToast({
        operation: "account.revoke_sessions",
        title: "Signed Out of All Sessions",
        description: "All sessions have been invalidated.",
      });
    } catch (error) {
      reportNonTrpcError(error, "account");
      showErrorToast(
        "Failed to Sign Out of All Sessions",
        error instanceof Error ? error.message : "An unexpected error occurred",
        classifyTrpcToastError(error, "account.revoke_sessions"),
      );
      throw error;
    }

    // Sessions are already revoked server-side at this point, so a failure to
    // clear local state must not be reported as a failed revocation.
    try {
      await signOutCleanly();
    } catch (error) {
      reportNonTrpcError(error, "account");
    }
  };

  return (
    <ConfirmationDialogController
      title="Sign Out of All Sessions"
      text="This will sign you out on this device and every other device where you are currently signed in. You will need to sign in again."
      confirmLabel="Sign Out of All Sessions"
      variant="destructive"
      loading={signOutAllSessions.isPending}
      onConfirm={onConfirm}
    >
      {({ openDialog }) => (
        <Button variant="destructive-secondary" onClick={openDialog}>
          Sign Out of All Sessions
        </Button>
      )}
    </ConfirmationDialogController>
  );
}

type AccountSettingsPage = {
  title: string;
  slug: string;
  show?: boolean | (() => boolean);
  cmdKKeywords?: string[];
} & ({ content: React.ReactNode } | { href: string });

export function useAccountSettingsPages(): AccountSettingsPage[] {
  const { data: session } = useSession();
  const userEmail = session?.user?.email ?? "";

  return getAccountSettingsPages({ userEmail });
}

const getAccountSettingsPages = ({
  userEmail,
}: {
  userEmail: string;
}): AccountSettingsPage[] => [
  {
    title: "General",
    slug: "index",
    cmdKKeywords: [
      "account",
      "user",
      "profile",
      "email",
      "password",
      "name",
      "display",
      "delete",
      "remove",
    ],
    content: (
      <div className="flex flex-col gap-6">
        <div>
          <Header title="Email" />
          <Card className="p-3">
            <p className="text-primary text-sm">
              Your email address: <b>{userEmail}</b>
            </p>
          </Card>
        </div>
        <UpdateDisplayName />
        <div>
          <Header title="Password" />
          <Card className="p-3">
            <p className="text-primary mb-4 text-sm">
              To change your password, we will email a one-time code to your
              address. Enter the code together with your new password.
            </p>
            <Button asChild variant="secondary">
              <Link href="/auth/reset-password">Change Password</Link>
            </Button>
          </Card>
        </div>
        <SettingsDangerZone
          items={[
            {
              title: "Sign out of all sessions",
              description:
                "Invalidate every active session for your account, including this device. You will need to sign in again.",
              button: <SignOutAllSessionsButton />,
            },
            {
              title: "Delete your account",
              description:
                "You can delete your account if you are not the last owner of any organization. If you are the last owner, please add another owner or delete the organization and all projects first.",
              button: <DeleteAccountButton />,
            },
          ]}
        />
      </div>
    ),
  },
];