import { IdentityProvider } from "@prisma/client"; import crypto from "crypto"; import { GetServerSidePropsContext } from "next"; import { signOut } from "next-auth/react"; import { BaseSyntheticEvent, useEffect, useRef, useState } from "react"; import { Controller, useForm } from "react-hook-form"; import { ErrorCode } from "@calcom/lib/auth"; import { APP_NAME } from "@calcom/lib/constants"; import { useLocale } from "@calcom/lib/hooks/useLocale"; import { TRPCClientErrorLike } from "@calcom/trpc/client"; import { trpc } from "@calcom/trpc/react"; import { AppRouter } from "@calcom/trpc/server/routers/_app"; import { Alert, Avatar, Button, Dialog, DialogClose, DialogContent, DialogFooter, DialogTrigger, Form, getSettingsLayout as getLayout, Icon, ImageUploader, Label, Meta, PasswordField, showToast, SkeletonAvatar, SkeletonButton, SkeletonContainer, SkeletonText, TextField, } from "@calcom/ui"; import TwoFactor from "@components/auth/TwoFactor"; import { UsernameAvailabilityField } from "@components/ui/UsernameAvailability"; import { ssrInit } from "@server/lib/ssr"; const SkeletonLoader = ({ title, description }: { title: string; description: string }) => { return (
); }; interface DeleteAccountValues { totpCode: string; } const ProfileView = () => { const { t } = useLocale(); const utils = trpc.useContext(); const { data: user, isLoading } = trpc.viewer.me.useQuery(); const mutation = trpc.viewer.updateProfile.useMutation({ onSuccess: () => { showToast(t("settings_updated_successfully"), "success"); }, onError: () => { showToast(t("error_updating_settings"), "error"); }, }); const [confirmPasswordOpen, setConfirmPasswordOpen] = useState(false); const [confirmPasswordErrorMessage, setConfirmPasswordDeleteErrorMessage] = useState(""); const [deleteAccountOpen, setDeleteAccountOpen] = useState(false); const [hasDeleteErrors, setHasDeleteErrors] = useState(false); const [deleteErrorMessage, setDeleteErrorMessage] = useState(""); const form = useForm(); const emailMd5 = crypto .createHash("md5") .update(user?.email || "example@example.com") .digest("hex"); const onDeleteMeSuccessMutation = async () => { await utils.viewer.me.invalidate(); showToast(t("Your account was deleted"), "success"); setHasDeleteErrors(false); // dismiss any open errors if (process.env.NEXT_PUBLIC_WEBAPP_URL === "https://app.cal.com") { signOut({ callbackUrl: "/auth/logout?survey=true" }); } else { signOut({ callbackUrl: "/auth/logout" }); } }; const confirmPasswordMutation = trpc.viewer.auth.verifyPassword.useMutation({ onSuccess() { mutation.mutate(formMethods.getValues()); setConfirmPasswordOpen(false); }, onError() { setConfirmPasswordDeleteErrorMessage(t("incorrect_password")); }, }); const onDeleteMeErrorMutation = (error: TRPCClientErrorLike) => { setHasDeleteErrors(true); setDeleteErrorMessage(errorMessages[error.message]); }; const deleteMeMutation = trpc.viewer.deleteMe.useMutation({ onSuccess: onDeleteMeSuccessMutation, onError: onDeleteMeErrorMutation, async onSettled() { await utils.viewer.me.invalidate(); }, }); const deleteMeWithoutPasswordMutation = trpc.viewer.deleteMeWithoutPassword.useMutation({ onSuccess: onDeleteMeSuccessMutation, onError: onDeleteMeErrorMutation, async onSettled() { await utils.viewer.me.invalidate(); }, }); const isCALIdentityProviver = user?.identityProvider === IdentityProvider.CAL; const onConfirmPassword = (e: Event | React.MouseEvent) => { e.preventDefault(); const password = passwordRef.current.value; confirmPasswordMutation.mutate({ passwordInput: password }); }; const onConfirmButton = (e: Event | React.MouseEvent) => { e.preventDefault(); if (isCALIdentityProviver) { const totpCode = form.getValues("totpCode"); const password = passwordRef.current.value; deleteMeMutation.mutate({ password, totpCode }); } else { deleteMeWithoutPasswordMutation.mutate(); } }; const onConfirm = ({ totpCode }: DeleteAccountValues, e: BaseSyntheticEvent | undefined) => { e?.preventDefault(); if (isCALIdentityProviver) { const password = passwordRef.current.value; deleteMeMutation.mutate({ password, totpCode }); } else { deleteMeWithoutPasswordMutation.mutate(); } }; const formMethods = useForm({ defaultValues: { username: "", avatar: "", name: "", email: "", bio: "", }, }); const { reset, formState: { isSubmitting, isDirty }, } = formMethods; useEffect(() => { if (user) { reset( { avatar: user?.avatar || "", username: user?.username || "", name: user?.name || "", email: user?.email || "", bio: user?.bio || "", }, { keepDirtyValues: true, } ); } }, [reset, user]); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const passwordRef = useRef(null!); const errorMessages: { [key: string]: string } = { [ErrorCode.SecondFactorRequired]: t("2fa_enabled_instructions"), [ErrorCode.IncorrectPassword]: `${t("incorrect_password")} ${t("please_try_again")}`, [ErrorCode.UserNotFound]: t("no_account_exists"), [ErrorCode.IncorrectTwoFactorCode]: `${t("incorrect_2fa_code")} ${t("please_try_again")}`, [ErrorCode.InternalServerError]: `${t("something_went_wrong")} ${t("please_try_again_and_contact_us")}`, [ErrorCode.ThirdPartyIdentityProviderEnabled]: t("account_created_with_identity_provider"), }; const onSuccessfulUsernameUpdate = async () => { showToast(t("settings_updated_successfully"), "success"); await utils.viewer.me.invalidate(); }; const onErrorInUsernameUpdate = () => { showToast(t("error_updating_settings"), "error"); }; if (isLoading || !user) return ; const isDisabled = isSubmitting || !isDirty; return ( <>
{ if (values.email !== user?.email && isCALIdentityProviver) { setConfirmPasswordOpen(true); } else { mutation.mutate(values); } }}>
( <>
{ formMethods.setValue("avatar", newAvatar, { shouldDirty: true }); }} imageSrc={value} />
)} />

{/* Delete account Dialog */} <>

{t("delete_account_confirmation_message", { appName: APP_NAME })}

{isCALIdentityProviver && ( )} {user?.twoFactorEnabled && isCALIdentityProviver && ( )} {hasDeleteErrors && }
{/* If changing email, confirm password */} <> {confirmPasswordErrorMessage && } ); }; ProfileView.getLayout = getLayout; export const getServerSideProps = async (context: GetServerSidePropsContext) => { const ssr = await ssrInit(context); return { props: { trpcState: ssr.dehydrate(), }, }; }; export default ProfileView;