chore: App router migration - general settings (#16312)

* added lockedSMS to future routes

* add orgMigrations routes to future

* correct metadata

* small fix

* add orgMigrations to future

* Move components to client components

* Remove tRPC element from edit user RSC

* Get username for meta

* Remove suspense query

* Remove orgMigrations from app router

* Type fix

* Revert "Remove suspense query"

This reverts commit eadd814f6e4a5d6856d9218342b7909c22fe62c6.

* Handle suspenseQuery in app router

* User edit page, fetch data server side

* Update yarn.lock

* Export getFixedT

* Set PageWrapper as root layout for settings

* Settings Layout accepts strings for shell heading

* Add OOO to app router settings

* Refactor layout for my-account pages

* Remove instances of pages router from my-account

* Refactor security pages

* Add billing to app router

* Add admin API link to layout

* Add api keys page

* Webhooks WIP

* Refactor SettingsHeader to client component

* Add webhook pages

* Refactor API keys page

* Add admin app page

* Type fix

* fix types

* fix developer/webhooks/[id] param value type error

* remove unnecessary code

* do not pass t prop to CreateNewWebhookButton

* fix type errors in webhook-edit-view

* fix the remaining type errors

* do not use prisma directly in generateMetadata

* remove use client if unnecessary

* Remove unused shell heading from SettingsLayoutAppDir

* improve metadata

* fix billing page

* fix import in settings/teams

* Use next `notFound()`

* fix type check

* fix type check

* remove unused code

* Fix calendar setting page

* Separate settings pages into route groups

* Refactor admin settings pages

* Remove meta instance from billing page route

* Update settings layoutAppDir

* Refactor developer settings pages

* Refactor out of office

* Refactor my account settings

* Refactor admin api page

* Refactor security pages

* Type fix

* fix styling in settings layout

---------

Co-authored-by: Somay Chauhan <[email protected]>
Co-authored-by: Omar López <[email protected]>
Co-authored-by: Benny Joo <[email protected]>
This commit is contained in:
authored and GitHub committed 2024-09-09 01:15:03 -04:00
1 parent 21e23f32ac
commit 84a2e55125
187 files changed
+4628 -3586

No files matched your search

@@ -0,0 +1,150 @@
import { getPlaceholderAvatar } from "@calcom/lib/defaultAvatarImage";
import { getUserAvatarUrl } from "@calcom/lib/getAvatarUrl";
import { SMSLockState } from "@calcom/prisma/client";
import { trpc } from "@calcom/trpc/react";
import type { IconName } from "@calcom/ui";
import { Avatar, DropdownActions, Table } from "@calcom/ui";
const { Cell, ColumnTitle, Header, Row } = Table;
type Props = {
setSMSLockState: (param: { userId?: number; teamId?: number; lock: boolean }) => void;
};
type User = {
id: number;
username: string | null;
name: string | null;
email: string;
smsLockState: SMSLockState;
avatarUrl: string | null;
};
type Team = {
id: number;
name: string;
smsLockState: SMSLockState;
slug: string | null;
logoUrl?: string | null;
};
function UsersTable({ setSMSLockState }: Props) {
const { data: usersAndTeams } = trpc.viewer.admin.getSMSLockStateTeamsUsers.useQuery();
if (!usersAndTeams) {
return <></>;
}
const users = usersAndTeams.users.locked.concat(usersAndTeams.users.reviewNeeded);
const teams = usersAndTeams.teams.locked.concat(usersAndTeams.teams.reviewNeeded);
return <LockStatusTable users={users} teams={teams} setSMSLockState={setSMSLockState} />;
}
const LockStatusTable = ({
users = [],
teams = [],
setSMSLockState,
}: {
users?: User[];
teams?: Team[];
setSMSLockState: (param: { userId?: number; teamId?: number; lock: boolean }) => void;
}) => {
function getActions({ user, team }: { user?: User; team?: Team }) {
const smsLockState = user?.smsLockState ?? team?.smsLockState;
if (!smsLockState) return [];
const actions = [
{
id: "unlock-sms",
label: smsLockState === SMSLockState.LOCKED ? "Unlock SMS sending" : "Lock SMS sending",
onClick: () =>
setSMSLockState({
userId: user ? user.id : undefined,
teamId: team ? team.id : undefined,
lock: smsLockState !== SMSLockState.LOCKED,
}),
icon: "lock" as IconName,
},
];
if (smsLockState === SMSLockState.REVIEW_NEEDED) {
actions.push({
id: "reviewed",
label: "Mark as Reviewed",
onClick: () =>
setSMSLockState({
userId: user ? user.id : undefined,
teamId: team ? team.id : undefined,
lock: false,
}),
icon: "pencil" as IconName,
});
}
return actions;
}
return (
<>
<Table>
<Header>
<ColumnTitle widthClassNames="w-auto">User/Team</ColumnTitle>
<ColumnTitle>Status</ColumnTitle>
<ColumnTitle widthClassNames="w-auto">
<span className="sr-only">Edit</span>
</ColumnTitle>
</Header>
<tbody className="divide-subtle divide-y rounded-md">
{users.map((user) => (
<Row key={`user-${user.id}`}>
<Cell widthClassNames="w-auto">
<div className="min-h-10 flex items-center">
{" "}
<Avatar
size="md"
alt={`Avatar of ${user.username || "Nameless"}`}
imageSrc={getUserAvatarUrl(user)}
/>
<div className="text-subtle ml-4 font-medium">
<span className="text-default">{user.name}</span>
<span className="ml-3">/{user.username}</span>
<br />
<span className="break-all">{user.email}</span>
</div>
</div>
</Cell>
<Cell>{user.smsLockState}</Cell>
<Cell widthClassNames="w-auto">
<DropdownActions actions={getActions({ user })} />
</Cell>
</Row>
))}
{teams.map((team) => (
<Row key={`team-${team.id}`}>
<Cell widthClassNames="w-auto">
<div className="min-h-10 flex items-center">
<Avatar
size="md"
alt={`Avatar of ${team.name}`}
imageSrc={getPlaceholderAvatar(team.logoUrl, team.name)}
/>
<div className="text-subtle ml-4 font-medium">
<span className="text-default">{team.name}</span>
<span className="ml-3 break-all">/team/{team.slug}</span>
</div>
</div>
</Cell>
<Cell>{team.smsLockState}</Cell>
<Cell widthClassNames="w-auto">
<DropdownActions actions={getActions({ team })} />
</Cell>
</Row>
))}
</tbody>
</Table>
</>
);
};
export default UsersTable;
@@ -0,0 +1,57 @@
"use client";
import { signIn } from "next-auth/react";
import { useSearchParams } from "next/navigation";
import { useRef, useEffect } from "react";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Button, TextField } from "@calcom/ui";
const ImpersonationView = () => {
const { t } = useLocale();
const usernameRef = useRef<HTMLInputElement>(null);
const searchParams = useSearchParams();
const username = searchParams?.get("username")?.toLowerCase();
useEffect(() => {
if (username) {
const enteredUsername = username.toLowerCase();
signIn("impersonation-auth", {
username: enteredUsername,
callbackUrl: `${WEBAPP_URL}/event-types`,
});
}
}, [username]);
return (
<form
className="mb-6 w-full"
onSubmit={(e) => {
e.preventDefault();
const enteredUsername = usernameRef.current?.value.toLowerCase();
signIn("impersonation-auth", {
username: enteredUsername,
callbackUrl: `${WEBAPP_URL}/event-types`,
});
}}>
<div className="flex items-center space-x-2 rtl:space-x-reverse">
<TextField
containerClassName="w-full"
name={t("user_impersonation_heading")}
addOnLeading={<>{process.env.NEXT_PUBLIC_WEBSITE_URL}/</>}
ref={usernameRef}
hint={t("impersonate_user_tip")}
defaultValue={undefined}
data-testid="admin-impersonation-input"
/>
<Button type="submit" data-testid="impersonation-submit">
{t("impersonate")}
</Button>
</div>
</form>
);
};
export default ImpersonationView;
@@ -0,0 +1,82 @@
"use client";
import { useState } from "react";
import { trpc } from "@calcom/trpc";
import { Button, TextField, showToast } from "@calcom/ui";
import UsersTable from "./components/UsersTable";
export default function LockedSMSView() {
const [username, setUsername] = useState("");
const [teamSlug, setTeamSlug] = useState("");
const utils = trpc.useContext();
const mutation = trpc.viewer.admin.setSMSLockState.useMutation({
onSuccess: (data) => {
if (data) {
showToast(`${data.name} successfully ${data.locked ? "locked" : "unlocked"}`, "success");
}
utils.viewer.admin.getSMSLockStateTeamsUsers.invalidate();
},
onError: (error) => {
showToast(`${error}`, "error");
utils.viewer.admin.getSMSLockStateTeamsUsers.invalidate();
},
});
function setSMSLockState({ userId, teamId, lock }: { userId?: number; teamId?: number; lock: boolean }) {
mutation.mutate({
userId,
teamId,
lock,
});
}
return (
<div>
<div className="mb-4 flex w-full items-center justify-between space-x-2 rtl:space-x-reverse">
<div className="flex">
<TextField
name="Lock User"
placeholder="username"
defaultValue=""
onChange={(event) => setUsername(event.target.value)}
value={username}
/>
<Button
type="submit"
className="ml-2 mt-5"
onClick={() => {
mutation.mutate({ username, lock: true });
utils.viewer.admin.getSMSLockStateTeamsUsers.invalidate();
}}>
Lock User
</Button>
</div>
<div className="flex">
<TextField
name="Lock Team"
placeholder="team slug"
defaultValue=""
onChange={(event) => {
setTeamSlug(event.target.value);
}}
value={teamSlug}
/>
<Button
type="submit"
className="ml-2 mt-5"
onClick={() => {
mutation.mutate({ teamSlug, lock: true });
utils.viewer.admin.getSMSLockStateTeamsUsers.invalidate();
}}>
Lock Team
</Button>
</div>
</div>
<UsersTable setSMSLockState={setSMSLockState} />
</div>
);
}
@@ -0,0 +1,150 @@
"use client";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc";
import { Form, Button, Icon, TextField, showToast, Tooltip, ImageUploader, Avatar } from "@calcom/ui";
type FormValues = {
name: string;
redirectUri: string;
logo: string;
};
export default function OAuthView() {
const oAuthForm = useForm<FormValues>();
const [clientSecret, setClientSecret] = useState("");
const [clientId, setClientId] = useState("");
const [logo, setLogo] = useState("");
const { t } = useLocale();
const mutation = trpc.viewer.oAuth.addClient.useMutation({
onSuccess: async (data) => {
setClientSecret(data.clientSecret);
setClientId(data.clientId);
showToast(`Successfully added ${data.name} as new client`, "success");
},
onError: (error) => {
showToast(`Adding clientfailed: ${error.message}`, "error");
},
});
return (
<div>
{!clientId ? (
<Form
form={oAuthForm}
handleSubmit={(values) => {
mutation.mutate({
name: values.name,
redirectUri: values.redirectUri,
logo: values.logo,
});
}}>
<div className="">
<TextField
{...oAuthForm.register("name")}
label="Client name"
type="text"
id="name"
placeholder=""
className="mb-3"
required
/>
<TextField
{...oAuthForm.register("redirectUri")}
label="Redirect URI"
type="text"
id="redirectUri"
placeholder=""
required
/>
<div className="mb-5 mt-5 flex items-center">
<Avatar
alt=""
fallback={<Icon name="plus" className="text-subtle h-6 w-6" />}
className="mr-5 items-center"
imageSrc={logo}
size="lg"
/>
<ImageUploader
target="avatar"
id="avatar-upload"
buttonMsg="Upload Logo"
handleAvatarChange={(newLogo: string) => {
setLogo(newLogo);
oAuthForm.setValue("logo", newLogo);
}}
imageSrc={logo}
/>
</div>
</div>
<Button type="submit" className="mt-3">
{t("add_client")}
</Button>
</Form>
) : (
<div>
<div className="text-emphasis mb-5 text-xl font-semibold">{oAuthForm.getValues("name")}</div>
<div className="mb-2 font-medium">Client Id</div>
<div className="flex">
<code className="bg-subtle text-default w-full truncate rounded-md rounded-r-none py-[6px] pl-2 pr-2 align-middle font-mono">
{" "}
{clientId}
</code>
<Tooltip side="top" content="Copy to Clipboard">
<Button
onClick={() => {
navigator.clipboard.writeText(clientId);
showToast("Client ID copied!", "success");
}}
type="button"
className="rounded-l-none text-base"
StartIcon="clipboard">
{t("copy")}
</Button>
</Tooltip>
</div>
{clientSecret ? (
<>
<div className="mb-2 mt-4 font-medium">Client Secret</div>
<div className="flex">
<code className="bg-subtle text-default w-full truncate rounded-md rounded-r-none py-[6px] pl-2 pr-2 align-middle font-mono">
{" "}
{clientSecret}
</code>
<Tooltip side="top" content="Copy to Clipboard">
<Button
onClick={() => {
navigator.clipboard.writeText(clientSecret);
setClientSecret("");
showToast("Client secret copied!", "success");
}}
type="button"
className="rounded-l-none text-base"
StartIcon="clipboard">
{t("copy")}
</Button>
</Tooltip>
</div>
<div className="text-subtle text-sm">{t("copy_client_secret_info")}</div>
</>
) : (
<></>
)}
<Button
onClick={() => {
setClientId("");
setLogo("");
oAuthForm.reset();
}}
className="mt-5">
{t("add_new_client")}
</Button>
</div>
)}
</div>
);
}
@@ -0,0 +1,64 @@
"use client";
import { usePathname } from "next/navigation";
import { useIntercom } from "@calcom/features/ee/support/lib/intercom/useIntercom";
import { classNames } from "@calcom/lib";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Button } from "@calcom/ui";
interface CtaRowProps {
title: string;
description: string;
children: React.ReactNode;
className?: string;
}
const CtaRow = ({ title, description, className, children }: CtaRowProps) => {
return (
<>
<section className={classNames("text-default flex flex-col sm:flex-row", className)}>
<div>
<h2 className="text-base font-semibold">{title}</h2>
<p>{description}</p>
</div>
<div className="flex-shrink-0 pt-3 sm:ml-auto sm:pl-3 sm:pt-0">{children}</div>
</section>
</>
);
};
const BillingView = () => {
const pathname = usePathname();
const { t } = useLocale();
const { open } = useIntercom();
const returnTo = pathname;
const billingHref = `/api/integrations/stripepayment/portal?returnTo=${WEBAPP_URL}${returnTo}`;
const onContactSupportClick = async () => {
await open();
};
return (
<>
<div className="border-subtle space-y-6 rounded-b-lg border border-t-0 px-6 py-8 text-sm sm:space-y-8">
<CtaRow title={t("view_and_manage_billing_details")} description={t("view_and_edit_billing_details")}>
<Button color="primary" href={billingHref} target="_blank" EndIcon="external-link">
{t("billing_portal")}
</Button>
</CtaRow>
<hr className="border-subtle" />
<CtaRow title={t("need_anything_else")} description={t("further_billing_help")}>
<Button color="secondary" onClick={onContactSupportClick}>
{t("contact_support")}
</Button>
</CtaRow>
</div>
</>
);
};
export default BillingView;
@@ -0,0 +1,108 @@
"use client";
import { useState } from "react";
import type { TApiKeys } from "@calcom/ee/api-keys/components/ApiKeyListItem";
import LicenseRequired from "@calcom/ee/common/components/LicenseRequired";
import ApiKeyDialogForm from "@calcom/features/ee/api-keys/components/ApiKeyDialogForm";
import ApiKeyListItem from "@calcom/features/ee/api-keys/components/ApiKeyListItem";
import { APP_NAME } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import {
Button,
Dialog,
DialogContent,
EmptyScreen,
Meta,
SkeletonContainer,
SkeletonText,
} from "@calcom/ui";
const SkeletonLoader = ({ title, description }: { title: string; description: string }) => {
return (
<SkeletonContainer>
<Meta title={title} description={description} borderInShellHeader={true} />
<div className="divide-subtle border-subtle space-y-6 rounded-b-lg border border-t-0 px-6 py-4">
<SkeletonText className="h-8 w-full" />
<SkeletonText className="h-8 w-full" />
</div>
</SkeletonContainer>
);
};
const ApiKeysView = () => {
const { t } = useLocale();
const { data, isPending } = trpc.viewer.apiKeys.list.useQuery();
const [apiKeyModal, setApiKeyModal] = useState(false);
const [apiKeyToEdit, setApiKeyToEdit] = useState<(TApiKeys & { neverExpires?: boolean }) | undefined>(
undefined
);
const NewApiKeyButton = () => {
return (
<Button
color="secondary"
StartIcon="plus"
onClick={() => {
setApiKeyToEdit(undefined);
setApiKeyModal(true);
}}>
{t("add")}
</Button>
);
};
if (isPending || !data) {
return (
<SkeletonLoader
title={t("api_keys")}
description={t("create_first_api_key_description", { appName: APP_NAME })}
/>
);
}
return (
<>
<LicenseRequired>
<div>
{data?.length ? (
<>
<div className="border-subtle rounded-b-lg border border-t-0">
{data.map((apiKey, index) => (
<ApiKeyListItem
key={apiKey.id}
apiKey={apiKey}
lastItem={data.length === index + 1}
onEditClick={() => {
setApiKeyToEdit(apiKey);
setApiKeyModal(true);
}}
/>
))}
</div>
</>
) : (
<EmptyScreen
Icon="link"
headline={t("create_first_api_key")}
description={t("create_first_api_key_description", { appName: APP_NAME })}
className="rounded-b-lg rounded-t-none border-t-0"
buttonRaw={<NewApiKeyButton />}
/>
)}
</div>
</LicenseRequired>
<Dialog open={apiKeyModal} onOpenChange={setApiKeyModal}>
<DialogContent type="creation">
<ApiKeyDialogForm handleClose={() => setApiKeyModal(false)} defaultValues={apiKeyToEdit} />
</DialogContent>
</Dialog>
</>
);
};
export default ApiKeysView;
@@ -0,0 +1,38 @@
"use client";
import { useState } from "react";
import type { TApiKeys } from "@calcom/ee/api-keys/components/ApiKeyListItem";
import ApiKeyDialogForm from "@calcom/features/ee/api-keys/components/ApiKeyDialogForm";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Button, Dialog, DialogContent } from "@calcom/ui";
const NewApiKeyButton = () => {
const { t } = useLocale();
const [apiKeyModal, setApiKeyModal] = useState(false);
const [apiKeyToEdit, setApiKeyToEdit] = useState<(TApiKeys & { neverExpires?: boolean }) | undefined>(
undefined
);
return (
<>
<Button
color="secondary"
StartIcon="plus"
onClick={() => {
setApiKeyToEdit(undefined);
setApiKeyModal(true);
}}>
{t("add")}
</Button>
<Dialog open={apiKeyModal} onOpenChange={setApiKeyModal}>
<DialogContent type="creation">
<ApiKeyDialogForm handleClose={() => setApiKeyModal(false)} defaultValues={apiKeyToEdit} />
</DialogContent>
</Dialog>
</>
);
};
export default NewApiKeyButton;
@@ -0,0 +1,440 @@
"use client";
import { useSession } from "next-auth/react";
import { useState } from "react";
import { Controller, useForm } from "react-hook-form";
import type { z } from "zod";
import { BookerLayoutSelector } from "@calcom/features/settings/BookerLayoutSelector";
import SectionBottomActions from "@calcom/features/settings/SectionBottomActions";
import ThemeLabel from "@calcom/features/settings/ThemeLabel";
import { APP_NAME } from "@calcom/lib/constants";
import { DEFAULT_LIGHT_BRAND_COLOR, DEFAULT_DARK_BRAND_COLOR } from "@calcom/lib/constants";
import { checkWCAGContrastColor } from "@calcom/lib/getBrandColours";
import useGetBrandingColours from "@calcom/lib/getBrandColours";
import { useHasPaidPlan } from "@calcom/lib/hooks/useHasPaidPlan";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import useTheme from "@calcom/lib/hooks/useTheme";
import { validateBookerLayouts } from "@calcom/lib/validateBookerLayouts";
import type { userMetadata } from "@calcom/prisma/zod-utils";
import { trpc } from "@calcom/trpc/react";
import type { RouterOutputs } from "@calcom/trpc/react";
import {
Alert,
Button,
ColorPicker,
Form,
showToast,
SkeletonButton,
SkeletonContainer,
SkeletonText,
SettingsToggle,
UpgradeTeamsBadge,
useCalcomTheme,
} from "@calcom/ui";
const SkeletonLoader = () => {
return (
<SkeletonContainer>
<div className="border-subtle mt-6 flex items-center rounded-t-xl border p-6 text-sm">
<SkeletonText className="h-8 w-1/3" />
</div>
<div className="border-subtle space-y-6 border-x px-4 py-6 sm:px-6">
<div className="[&>*]:bg-emphasis flex w-full items-center justify-center gap-x-2 [&>*]:animate-pulse">
<div className="h-32 flex-1 rounded-md p-5" />
<div className="h-32 flex-1 rounded-md p-5" />
<div className="h-32 flex-1 rounded-md p-5" />
</div>
<div className="flex justify-between">
<SkeletonText className="h-8 w-1/3" />
<SkeletonText className="h-8 w-1/3" />
</div>
<SkeletonText className="h-8 w-full" />
</div>
<div className="rounded-b-lg">
<SectionBottomActions align="end">
<SkeletonButton className="mr-6 h-8 w-20 rounded-md p-5" />
</SectionBottomActions>
</div>
</SkeletonContainer>
);
};
const useBrandColors = (
currentTheme: string | null,
{
brandColor,
darkBrandColor,
}: {
brandColor?: string | null;
darkBrandColor?: string | null;
}
): void => {
const brandTheme = useGetBrandingColours({
lightVal: brandColor,
darkVal: darkBrandColor,
});
const selectedTheme = currentTheme ? brandTheme[currentTheme as "light" | "dark"] : {};
useCalcomTheme({
root: selectedTheme,
});
};
const AppearanceView = ({
user,
hasPaidPlan,
}: {
user: RouterOutputs["viewer"]["me"];
hasPaidPlan: boolean;
}) => {
const { t } = useLocale();
const utils = trpc.useUtils();
const session = useSession();
const isApartOfOrganization = session.data?.user.org?.id;
const [darkModeError, setDarkModeError] = useState(false);
const [lightModeError, setLightModeError] = useState(false);
const [isCustomBrandColorChecked, setIsCustomBranColorChecked] = useState(
user?.brandColor !== DEFAULT_LIGHT_BRAND_COLOR || user?.darkBrandColor !== DEFAULT_DARK_BRAND_COLOR
);
const [hideBrandingValue, setHideBrandingValue] = useState(user?.hideBranding ?? false);
useTheme(user?.appTheme);
useBrandColors(user?.appTheme ?? null, {
brandColor: user?.brandColor,
darkBrandColor: user?.darkBrandColor,
});
const userAppThemeFormMethods = useForm({
defaultValues: {
appTheme: user.appTheme,
},
});
const {
formState: { isSubmitting: isUserAppThemeSubmitting, isDirty: isUserAppThemeDirty },
reset: resetUserAppThemeReset,
} = userAppThemeFormMethods;
const userThemeFormMethods = useForm({
defaultValues: {
theme: user.theme,
},
});
const {
formState: { isSubmitting: isUserThemeSubmitting, isDirty: isUserThemeDirty },
reset: resetUserThemeReset,
} = userThemeFormMethods;
const bookerLayoutFormMethods = useForm({
defaultValues: {
metadata: user.metadata as z.infer<typeof userMetadata>,
},
});
const {
formState: { isSubmitting: isBookerLayoutFormSubmitting, isDirty: isBookerLayoutFormDirty },
reset: resetBookerLayoutThemeReset,
} = bookerLayoutFormMethods;
const DEFAULT_BRAND_COLOURS = {
light: user.brandColor ?? DEFAULT_LIGHT_BRAND_COLOR,
dark: user.darkBrandColor ?? DEFAULT_DARK_BRAND_COLOR,
};
const brandColorsFormMethods = useForm({
defaultValues: {
brandColor: DEFAULT_BRAND_COLOURS.light,
darkBrandColor: DEFAULT_BRAND_COLOURS.dark,
},
});
const {
formState: { isSubmitting: isBrandColorsFormSubmitting, isDirty: isBrandColorsFormDirty },
reset: resetBrandColorsThemeReset,
} = brandColorsFormMethods;
const selectedTheme = userThemeFormMethods.watch("theme");
const selectedThemeIsDark =
selectedTheme === "dark" ||
(selectedTheme === "" &&
typeof document !== "undefined" &&
document.documentElement.classList.contains("dark"));
const mutation = trpc.viewer.updateProfile.useMutation({
onSuccess: async (data) => {
await utils.viewer.me.invalidate();
showToast(t("settings_updated_successfully"), "success");
resetBrandColorsThemeReset({ brandColor: data.brandColor, darkBrandColor: data.darkBrandColor });
resetBookerLayoutThemeReset({ metadata: data.metadata });
resetUserThemeReset({ theme: data.theme });
resetUserAppThemeReset({ appTheme: data.appTheme });
},
onError: (error) => {
if (error.message) {
showToast(error.message, "error");
} else {
showToast(t("error_updating_settings"), "error");
}
},
onSettled: async () => {
await utils.viewer.me.invalidate();
},
});
return (
<div>
<div className="border-subtle mt-6 flex items-center rounded-t-lg border p-6 text-sm">
<div>
<p className="text-default text-base font-semibold">{t("app_theme")}</p>
<p className="text-default">{t("app_theme_applies_note")}</p>
</div>
</div>
<Form
form={userAppThemeFormMethods}
handleSubmit={(values) => {
mutation.mutate({
appTheme: values.appTheme === "" ? null : values.appTheme,
});
}}>
<div className="border-subtle flex flex-col justify-between border-x px-6 py-8 sm:flex-row">
<ThemeLabel
variant="system"
value={undefined}
label={t("theme_system")}
defaultChecked={user.appTheme === null}
register={userAppThemeFormMethods.register}
fieldName="appTheme"
/>
<ThemeLabel
variant="light"
value="light"
label={t("light")}
defaultChecked={user.appTheme === "light"}
register={userAppThemeFormMethods.register}
fieldName="appTheme"
/>
<ThemeLabel
variant="dark"
value="dark"
label={t("dark")}
defaultChecked={user.appTheme === "dark"}
register={userAppThemeFormMethods.register}
fieldName="appTheme"
/>
</div>
<SectionBottomActions className="mb-6" align="end">
<Button
disabled={isUserAppThemeSubmitting || !isUserAppThemeDirty}
type="submit"
data-testid="update-app-theme-btn"
color="primary">
{t("update")}
</Button>
</SectionBottomActions>
</Form>
{isApartOfOrganization ? null : (
<>
<div className="border-subtle mt-6 flex items-center rounded-t-lg border p-6 text-sm">
<div>
<p className="text-default text-base font-semibold">{t("theme")}</p>
<p className="text-default">{t("theme_applies_note")}</p>
</div>
</div>
<Form
form={userThemeFormMethods}
handleSubmit={(values) => {
mutation.mutate({
// Radio values don't support null as values, therefore we convert an empty string
// back to null here.
theme: values.theme === "" ? null : values.theme,
});
}}>
<div className="border-subtle flex flex-col justify-between border-x px-6 py-8 sm:flex-row">
<ThemeLabel
variant="system"
value={undefined}
label={t("theme_system")}
defaultChecked={user.theme === null}
register={userThemeFormMethods.register}
/>
<ThemeLabel
variant="light"
value="light"
label={t("light")}
defaultChecked={user.theme === "light"}
register={userThemeFormMethods.register}
/>
<ThemeLabel
variant="dark"
value="dark"
label={t("dark")}
defaultChecked={user.theme === "dark"}
register={userThemeFormMethods.register}
/>
</div>
<SectionBottomActions className="mb-6" align="end">
<Button
loading={mutation.isPending}
disabled={isUserThemeSubmitting || !isUserThemeDirty}
type="submit"
data-testid="update-theme-btn"
color="primary">
{t("update")}
</Button>
</SectionBottomActions>
</Form>
<Form
form={bookerLayoutFormMethods}
handleSubmit={(values) => {
const layoutError = validateBookerLayouts(values?.metadata?.defaultBookerLayouts || null);
if (layoutError) {
showToast(t(layoutError), "error");
return;
} else {
mutation.mutate(values);
}
}}>
<BookerLayoutSelector
isDark={selectedThemeIsDark}
name="metadata.defaultBookerLayouts"
title={t("bookerlayout_user_settings_title")}
description={t("bookerlayout_user_settings_description")}
isDisabled={isBookerLayoutFormSubmitting || !isBookerLayoutFormDirty}
isLoading={mutation.isPending}
/>
</Form>
<Form
form={brandColorsFormMethods}
handleSubmit={(values) => {
mutation.mutate(values);
}}>
<div className="mt-6">
<SettingsToggle
toggleSwitchAtTheEnd={true}
title={t("custom_brand_colors")}
description={t("customize_your_brand_colors")}
checked={isCustomBrandColorChecked}
onCheckedChange={(checked) => {
setIsCustomBranColorChecked(checked);
if (!checked) {
mutation.mutate({
brandColor: DEFAULT_LIGHT_BRAND_COLOR,
darkBrandColor: DEFAULT_DARK_BRAND_COLOR,
});
}
}}
childrenClassName="lg:ml-0">
<div className="border-subtle flex flex-col gap-6 border-x p-6">
<Controller
name="brandColor"
control={brandColorsFormMethods.control}
defaultValue={DEFAULT_BRAND_COLOURS.light}
render={() => (
<div>
<p className="text-default mb-2 block text-sm font-medium">
{t("light_brand_color")}
</p>
<ColorPicker
defaultValue={DEFAULT_BRAND_COLOURS.light}
resetDefaultValue={DEFAULT_LIGHT_BRAND_COLOR}
onChange={(value) => {
if (checkWCAGContrastColor("#ffffff", value)) {
setLightModeError(false);
} else {
setLightModeError(true);
}
brandColorsFormMethods.setValue("brandColor", value, { shouldDirty: true });
}}
/>
{lightModeError ? (
<div className="mt-4">
<Alert severity="warning" message={t("light_theme_contrast_error")} />
</div>
) : null}
</div>
)}
/>
<Controller
name="darkBrandColor"
control={brandColorsFormMethods.control}
defaultValue={DEFAULT_BRAND_COLOURS.dark}
render={() => (
<div className="mt-6 sm:mt-0">
<p className="text-default mb-2 block text-sm font-medium">{t("dark_brand_color")}</p>
<ColorPicker
defaultValue={DEFAULT_BRAND_COLOURS.dark}
resetDefaultValue={DEFAULT_DARK_BRAND_COLOR}
onChange={(value) => {
if (checkWCAGContrastColor("#101010", value)) {
setDarkModeError(false);
} else {
setDarkModeError(true);
}
brandColorsFormMethods.setValue("darkBrandColor", value, { shouldDirty: true });
}}
/>
{darkModeError ? (
<div className="mt-4">
<Alert severity="warning" message={t("dark_theme_contrast_error")} />
</div>
) : null}
</div>
)}
/>
</div>
<SectionBottomActions align="end">
<Button
loading={mutation.isPending}
disabled={isBrandColorsFormSubmitting || !isBrandColorsFormDirty}
color="primary"
type="submit">
{t("update")}
</Button>
</SectionBottomActions>
</SettingsToggle>
</div>
</Form>
{/* TODO future PR to preview brandColors */}
{/* <Button
color="secondary"
EndIcon="external-link"
className="mt-6"
onClick={() => window.open(`${WEBAPP_URL}/${user.username}/${user.eventTypes[0].title}`, "_blank")}>
Preview
</Button> */}
<SettingsToggle
toggleSwitchAtTheEnd={true}
title={t("disable_cal_branding", { appName: APP_NAME })}
disabled={!hasPaidPlan || mutation?.isPending}
description={t("removes_cal_branding", { appName: APP_NAME })}
checked={hasPaidPlan ? hideBrandingValue : false}
Badge={<UpgradeTeamsBadge />}
onCheckedChange={(checked) => {
setHideBrandingValue(checked);
mutation.mutate({ hideBranding: checked });
}}
switchContainerClassName="mt-6"
/>
</>
)}
</div>
);
};
const AppearancePage = () => {
const { data: user, isPending } = trpc.viewer.me.useQuery();
const { isPending: isTeamPlanStatusLoading, hasPaidPlan } = useHasPaidPlan();
if (isPending || isTeamPlanStatusLoading || !user) return <SkeletonLoader />;
return <AppearanceView user={user} hasPaidPlan={hasPaidPlan} />;
};
export default AppearancePage;
@@ -0,0 +1,18 @@
"use client";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Button } from "@calcom/ui";
const AddCalendarButton = () => {
const { t } = useLocale();
return (
<>
<Button color="secondary" StartIcon="plus" href="/apps/categories/calendar">
{t("add_calendar")}
</Button>
</>
);
};
export default AddCalendarButton;
@@ -0,0 +1,101 @@
"use client";
import { useReducer } from "react";
import DisconnectIntegrationModal from "@calcom/features/apps/components/DisconnectIntegrationModal";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Button, EmptyScreen, SkeletonContainer, SkeletonText } from "@calcom/ui";
import { QueryCell } from "@lib/QueryCell";
import { AppList } from "@components/apps/AppList";
const SkeletonLoader = () => {
return (
<SkeletonContainer>
<div className="divide-subtle border-subtle space-y-6 rounded-b-lg border border-t-0 px-6 py-4">
<SkeletonText className="h-8 w-full" />
<SkeletonText className="h-8 w-full" />
</div>
</SkeletonContainer>
);
};
type ModalState = {
isOpen: boolean;
credentialId: null | number;
};
const ConferencingView = () => {
const { t } = useLocale();
const [modal, updateModal] = useReducer(
(data: ModalState, partialData: Partial<ModalState>) => ({ ...data, ...partialData }),
{
isOpen: false,
credentialId: null,
}
);
const query = trpc.viewer.integrations.useQuery({
variant: "conferencing",
onlyInstalled: true,
});
const handleModelClose = () => {
updateModal({ isOpen: false, credentialId: null });
};
const handleDisconnect = (credentialId: number) => {
updateModal({ isOpen: true, credentialId });
};
return (
<>
<div className="bg-default w-full sm:mx-0 xl:mt-0">
<QueryCell
query={query}
customLoader={<SkeletonLoader />}
success={({ data }) => {
console.log(data);
if (!data.items.length) {
return (
<EmptyScreen
Icon="calendar"
headline={t("no_category_apps", {
category: t("conferencing").toLowerCase(),
})}
description={t("no_category_apps_description_conferencing")}
buttonRaw={
<Button
color="secondary"
data-testid="connect-conferencing-apps"
href="/apps/categories/conferencing">
{t("connect_conference_apps")}
</Button>
}
/>
);
}
return (
<AppList
listClassName="rounded-lg rounded-t-none border-t-0 max-w-full"
handleDisconnect={handleDisconnect}
data={data}
variant="conferencing"
/>
);
}}
/>
</div>
<DisconnectIntegrationModal
handleModelClose={handleModelClose}
isOpen={modal.isOpen}
credentialId={modal.credentialId}
/>
</>
);
};
export default ConferencingView;
@@ -0,0 +1,378 @@
"use client";
import { useSession } from "next-auth/react";
import { useState } from "react";
import { Controller, useForm } from "react-hook-form";
import SectionBottomActions from "@calcom/features/settings/SectionBottomActions";
import { classNames } from "@calcom/lib";
import { formatLocalizedDateTime } from "@calcom/lib/date-fns";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { localeOptions } from "@calcom/lib/i18n";
import { nameOfDay } from "@calcom/lib/weekday";
import type { RouterOutputs } from "@calcom/trpc/react";
import { trpc } from "@calcom/trpc/react";
import {
Button,
Form,
Label,
Select,
showToast,
SkeletonButton,
SkeletonContainer,
SkeletonText,
TimezoneSelect,
SettingsToggle,
} from "@calcom/ui";
import TravelScheduleModal from "@components/settings/TravelScheduleModal";
export type FormValues = {
locale: {
value: string;
label: string;
};
timeZone: string;
timeFormat: {
value: number;
label: string | number;
};
weekStart: {
value: string;
label: string;
};
travelSchedules: {
id?: number;
startDate: Date;
endDate?: Date;
timeZone: string;
}[];
};
const SkeletonLoader = () => {
return (
<SkeletonContainer>
<div className="border-subtle space-y-6 rounded-b-xl border border-t-0 px-4 py-8 sm:px-6">
<SkeletonText className="h-8 w-full" />
<SkeletonText className="h-8 w-full" />
<SkeletonText className="h-8 w-full" />
<SkeletonText className="h-8 w-full" />
<SkeletonButton className="ml-auto h-8 w-20 rounded-md p-5" />
</div>
</SkeletonContainer>
);
};
interface GeneralViewProps {
localeProp: string;
user: RouterOutputs["viewer"]["me"];
travelSchedules: RouterOutputs["viewer"]["getTravelSchedules"];
}
const GeneralQueryView = () => {
const { t } = useLocale();
const { data: user, isPending } = trpc.viewer.me.useQuery();
const { data: travelSchedules, isPending: isPendingTravelSchedules } =
trpc.viewer.getTravelSchedules.useQuery();
if (isPending || isPendingTravelSchedules) return <SkeletonLoader />;
if (!user) {
throw new Error(t("something_went_wrong"));
}
return <GeneralView user={user} travelSchedules={travelSchedules || []} localeProp={user.locale} />;
};
const GeneralView = ({ localeProp, user, travelSchedules }: GeneralViewProps) => {
const utils = trpc.useContext();
const {
t,
i18n: { language },
} = useLocale();
const { update } = useSession();
const [isUpdateBtnLoading, setIsUpdateBtnLoading] = useState<boolean>(false);
const [isTZScheduleOpen, setIsTZScheduleOpen] = useState<boolean>(false);
const mutation = trpc.viewer.updateProfile.useMutation({
onSuccess: async (res) => {
await utils.viewer.me.invalidate();
reset(getValues());
showToast(t("settings_updated_successfully"), "success");
await update(res);
if (res.locale) {
window.calNewLocale = res.locale;
}
},
onError: () => {
showToast(t("error_updating_settings"), "error");
},
onSettled: async () => {
await utils.viewer.me.invalidate();
setIsUpdateBtnLoading(false);
},
});
const timeFormatOptions = [
{ value: 12, label: t("12_hour") },
{ value: 24, label: t("24_hour") },
];
const weekStartOptions = [
{ value: "Sunday", label: nameOfDay(localeProp, 0) },
{ value: "Monday", label: nameOfDay(localeProp, 1) },
{ value: "Tuesday", label: nameOfDay(localeProp, 2) },
{ value: "Wednesday", label: nameOfDay(localeProp, 3) },
{ value: "Thursday", label: nameOfDay(localeProp, 4) },
{ value: "Friday", label: nameOfDay(localeProp, 5) },
{ value: "Saturday", label: nameOfDay(localeProp, 6) },
];
const formMethods = useForm<FormValues>({
defaultValues: {
locale: {
value: localeProp || "",
label: localeOptions.find((option) => option.value === localeProp)?.label || "",
},
timeZone: user.timeZone || "",
timeFormat: {
value: user.timeFormat || 12,
label: timeFormatOptions.find((option) => option.value === user.timeFormat)?.label || 12,
},
weekStart: {
value: user.weekStart,
label: nameOfDay(localeProp, user.weekStart === "Sunday" ? 0 : 1),
},
travelSchedules:
travelSchedules.map((schedule) => {
return {
id: schedule.id,
startDate: schedule.startDate,
endDate: schedule.endDate ?? undefined,
timeZone: schedule.timeZone,
};
}) || [],
},
});
const {
formState: { isDirty, isSubmitting },
reset,
getValues,
} = formMethods;
const isDisabled = isSubmitting || !isDirty;
const [isAllowDynamicBookingChecked, setIsAllowDynamicBookingChecked] = useState(
!!user.allowDynamicBooking
);
const [isAllowSEOIndexingChecked, setIsAllowSEOIndexingChecked] = useState(!!user.allowSEOIndexing);
const [isReceiveMonthlyDigestEmailChecked, setIsReceiveMonthlyDigestEmailChecked] = useState(
!!user.receiveMonthlyDigestEmail
);
const watchedTzSchedules = formMethods.watch("travelSchedules");
return (
<div>
<Form
form={formMethods}
handleSubmit={(values) => {
setIsUpdateBtnLoading(true);
mutation.mutate({
...values,
locale: values.locale.value,
timeFormat: values.timeFormat.value,
weekStart: values.weekStart.value,
});
}}>
<div className="border-subtle border-x border-y-0 px-4 py-8 sm:px-6">
<Controller
name="locale"
render={({ field: { value, onChange } }) => (
<>
<Label className="text-emphasis">
<>{t("language")}</>
</Label>
<Select<{ label: string; value: string }>
className="capitalize"
options={localeOptions}
value={value}
onChange={onChange}
/>
</>
)}
/>
<Controller
name="timeZone"
control={formMethods.control}
render={({ field: { value } }) => (
<>
<Label className="text-emphasis mt-6">
<>{t("timezone")}</>
</Label>
<TimezoneSelect
id="timezone"
value={value}
onChange={(event) => {
if (event) formMethods.setValue("timeZone", event.value, { shouldDirty: true });
}}
/>
</>
)}
/>
{!watchedTzSchedules.length ? (
<Button color="minimal" className="mt-2" onClick={() => setIsTZScheduleOpen(true)}>
{t("schedule_timezone_change")}
</Button>
) : (
<div className="bg-muted border-subtle mt-2 rounded-md border p-4">
<Label>{t("travel_schedule")}</Label>
<div className="dark:bg-darkgray-100 border-subtle mt-4 rounded-md border bg-white text-sm">
{watchedTzSchedules.map((schedule, index) => {
return (
<div
className={classNames(
"flex items-center p-4",
index !== 0 ? "border-subtle border-t" : ""
)}
key={index}>
<div>
<div className="text-emphasis font-semibold">{`${formatLocalizedDateTime(
schedule.startDate,
{ day: "numeric", month: "long" },
language
)} ${
schedule.endDate
? `- ${formatLocalizedDateTime(
schedule.endDate,
{ day: "numeric", month: "long" },
language
)}`
: ``
}`}</div>
<div className="text-subtle">{schedule.timeZone.replace(/_/g, " ")}</div>
</div>
<Button
color="secondary"
className="ml-auto"
variant="icon"
StartIcon="trash-2"
onClick={() => {
const updatedSchedules = watchedTzSchedules.filter(
(s, filterIndex) => filterIndex !== index
);
formMethods.setValue("travelSchedules", updatedSchedules, { shouldDirty: true });
}}
/>
</div>
);
})}
</div>
<Button
StartIcon="plus"
color="secondary"
className="mt-4"
onClick={() => setIsTZScheduleOpen(true)}>
{t("add")}
</Button>
</div>
)}
<Controller
name="timeFormat"
control={formMethods.control}
render={({ field: { value } }) => (
<>
<Label className="text-emphasis mt-6">
<>{t("time_format")}</>
</Label>
<Select
value={value}
options={timeFormatOptions}
onChange={(event) => {
if (event) formMethods.setValue("timeFormat", { ...event }, { shouldDirty: true });
}}
/>
</>
)}
/>
<div className="text-gray text-default mt-2 flex items-center text-sm">
{t("timeformat_profile_hint")}
</div>
<Controller
name="weekStart"
control={formMethods.control}
render={({ field: { value } }) => (
<>
<Label className="text-emphasis mt-6">
<>{t("start_of_week")}</>
</Label>
<Select
value={value}
options={weekStartOptions}
onChange={(event) => {
if (event) formMethods.setValue("weekStart", { ...event }, { shouldDirty: true });
}}
/>
</>
)}
/>
</div>
<SectionBottomActions align="end">
<Button loading={isUpdateBtnLoading} disabled={isDisabled} color="primary" type="submit">
<>{t("update")}</>
</Button>
</SectionBottomActions>
</Form>
<SettingsToggle
toggleSwitchAtTheEnd={true}
title={t("dynamic_booking")}
description={t("allow_dynamic_booking")}
disabled={mutation.isPending}
checked={isAllowDynamicBookingChecked}
onCheckedChange={(checked) => {
setIsAllowDynamicBookingChecked(checked);
mutation.mutate({ allowDynamicBooking: checked });
}}
switchContainerClassName="mt-6"
/>
<SettingsToggle
toggleSwitchAtTheEnd={true}
title={t("seo_indexing")}
description={t("allow_seo_indexing")}
disabled={mutation.isPending}
checked={isAllowSEOIndexingChecked}
onCheckedChange={(checked) => {
setIsAllowSEOIndexingChecked(checked);
mutation.mutate({ allowSEOIndexing: checked });
}}
switchContainerClassName="mt-6"
/>
<SettingsToggle
toggleSwitchAtTheEnd={true}
title={t("monthly_digest_email")}
description={t("monthly_digest_email_for_teams")}
disabled={mutation.isPending}
checked={isReceiveMonthlyDigestEmailChecked}
onCheckedChange={(checked) => {
setIsReceiveMonthlyDigestEmailChecked(checked);
mutation.mutate({ receiveMonthlyDigestEmail: checked });
}}
switchContainerClassName="mt-6"
/>
<TravelScheduleModal
open={isTZScheduleOpen}
onOpenChange={() => setIsTZScheduleOpen(false)}
setValue={formMethods.setValue}
existingSchedules={formMethods.getValues("travelSchedules") ?? []}
/>
</div>
);
};
export default GeneralQueryView;
@@ -0,0 +1,730 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
// eslint-disable-next-line no-restricted-imports
import { get, pick } from "lodash";
import { signOut, useSession } from "next-auth/react";
import type { BaseSyntheticEvent } from "react";
import React, { useRef, useState } from "react";
import { Controller, useFieldArray, useForm } from "react-hook-form";
import { z } from "zod";
import { ErrorCode } from "@calcom/features/auth/lib/ErrorCode";
import SectionBottomActions from "@calcom/features/settings/SectionBottomActions";
import { APP_NAME, FULL_NAME_LENGTH_MAX_LIMIT } from "@calcom/lib/constants";
import { getUserAvatarUrl } from "@calcom/lib/getAvatarUrl";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { md } from "@calcom/lib/markdownIt";
import turndown from "@calcom/lib/turndownService";
import { IdentityProvider } from "@calcom/prisma/enums";
import type { TRPCClientErrorLike } from "@calcom/trpc/client";
import type { RouterOutputs } from "@calcom/trpc/react";
import { trpc } from "@calcom/trpc/react";
import type { AppRouter } from "@calcom/trpc/server/routers/_app";
import {
Alert,
Button,
Dialog,
DialogClose,
DialogContent,
DialogFooter,
DialogTrigger,
Editor,
Form,
ImageUploader,
Label,
PasswordField,
showToast,
SkeletonAvatar,
SkeletonButton,
SkeletonContainer,
SkeletonText,
TextField,
UserAvatar,
} from "@calcom/ui";
import TwoFactor from "@components/auth/TwoFactor";
import CustomEmailTextField from "@components/settings/CustomEmailTextField";
import SecondaryEmailConfirmModal from "@components/settings/SecondaryEmailConfirmModal";
import SecondaryEmailModal from "@components/settings/SecondaryEmailModal";
import { UsernameAvailabilityField } from "@components/ui/UsernameAvailability";
const SkeletonLoader = () => {
return (
<SkeletonContainer>
<div className="border-subtle space-y-6 rounded-b-lg border border-t-0 px-4 py-8">
<div className="flex items-center">
<SkeletonAvatar className="me-4 mt-0 h-16 w-16 px-4" />
<SkeletonButton className="h-6 w-32 rounded-md p-5" />
</div>
<SkeletonText className="h-8 w-full" />
<SkeletonText className="h-8 w-full" />
<SkeletonText className="h-8 w-full" />
<SkeletonButton className="mr-6 h-8 w-20 rounded-md p-5" />
</div>
</SkeletonContainer>
);
};
interface DeleteAccountValues {
totpCode: string;
}
type Email = {
id: number;
email: string;
emailVerified: string | null;
emailPrimary: boolean;
};
export type FormValues = {
username: string;
avatarUrl: string | null;
name: string;
email: string;
bio: string;
secondaryEmails: Email[];
};
const ProfileView = () => {
const { t } = useLocale();
const utils = trpc.useUtils();
const { update } = useSession();
const { data: user, isPending } = trpc.viewer.me.useQuery({ includePasswordAdded: true });
const updateProfileMutation = trpc.viewer.updateProfile.useMutation({
onSuccess: async (res) => {
await update(res);
utils.viewer.me.invalidate();
utils.viewer.shouldVerifyEmail.invalidate();
if (res.hasEmailBeenChanged && res.sendEmailVerification) {
showToast(t("change_of_email_toast", { email: tempFormValues?.email }), "success");
} else {
showToast(t("settings_updated_successfully"), "success");
}
setTempFormValues(null);
},
onError: (e) => {
switch (e.message) {
// TODO: Add error codes.
case "email_already_used":
{
showToast(t(e.message), "error");
}
return;
default:
showToast(t("error_updating_settings"), "error");
}
},
});
const unlinkConnectedAccountMutation = trpc.viewer.unlinkConnectedAccount.useMutation({
onSuccess: async (res) => {
showToast(t(res.message), "success");
utils.viewer.me.invalidate();
},
onError: (e) => {
showToast(t(e.message), "error");
},
});
const addSecondaryEmailMutation = trpc.viewer.addSecondaryEmail.useMutation({
onSuccess: (res) => {
setShowSecondaryEmailModalOpen(false);
setNewlyAddedSecondaryEmail(res?.data?.email);
utils.viewer.me.invalidate();
},
onError: (error) => {
setSecondaryEmailAddErrorMessage(error?.message || "");
},
});
const resendVerifyEmailMutation = trpc.viewer.auth.resendVerifyEmail.useMutation();
const [confirmPasswordOpen, setConfirmPasswordOpen] = useState(false);
const [tempFormValues, setTempFormValues] = useState<ExtendedFormValues | null>(null);
const [confirmPasswordErrorMessage, setConfirmPasswordDeleteErrorMessage] = useState("");
const [showCreateAccountPasswordDialog, setShowCreateAccountPasswordDialog] = useState(false);
const [showAccountDisconnectWarning, setShowAccountDisconnectWarning] = useState(false);
const [showSecondaryEmailModalOpen, setShowSecondaryEmailModalOpen] = useState(false);
const [secondaryEmailAddErrorMessage, setSecondaryEmailAddErrorMessage] = useState("");
const [newlyAddedSecondaryEmail, setNewlyAddedSecondaryEmail] = useState<undefined | string>(undefined);
const [deleteAccountOpen, setDeleteAccountOpen] = useState(false);
const [hasDeleteErrors, setHasDeleteErrors] = useState(false);
const [deleteErrorMessage, setDeleteErrorMessage] = useState("");
const form = useForm<DeleteAccountValues>();
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() {
if (tempFormValues) updateProfileMutation.mutate(tempFormValues);
setConfirmPasswordOpen(false);
},
onError() {
setConfirmPasswordDeleteErrorMessage(t("incorrect_password"));
},
});
const onDeleteMeErrorMutation = (error: TRPCClientErrorLike<AppRouter>) => {
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 isCALIdentityProvider = user?.identityProvider === IdentityProvider.CAL;
const onConfirmPassword = (e: Event | React.MouseEvent<HTMLElement, MouseEvent>) => {
e.preventDefault();
const password = passwordRef.current.value;
confirmPasswordMutation.mutate({ passwordInput: password });
};
const onConfirmButton = (e: Event | React.MouseEvent<HTMLElement, MouseEvent>) => {
e.preventDefault();
if (isCALIdentityProvider) {
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 (isCALIdentityProvider) {
const password = passwordRef.current.value;
deleteMeMutation.mutate({ password, totpCode });
} else {
deleteMeWithoutPasswordMutation.mutate();
}
};
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const passwordRef = useRef<HTMLInputElement>(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"),
};
if (isPending || !user) {
return <SkeletonLoader />;
}
const userEmail = user.email || "";
const defaultValues = {
username: user.username || "",
avatarUrl: user.avatarUrl,
name: user.name || "",
email: userEmail,
bio: user.bio || "",
// We add the primary email as the first item in the list
secondaryEmails: [
{
id: 0,
email: userEmail,
emailVerified: user.emailVerified?.toString() || null,
emailPrimary: true,
},
...(user.secondaryEmails || []).map((secondaryEmail) => ({
...secondaryEmail,
emailVerified: secondaryEmail.emailVerified?.toString() || null,
emailPrimary: false,
})),
],
};
return (
<>
<ProfileForm
key={JSON.stringify(defaultValues)}
defaultValues={defaultValues}
isPending={updateProfileMutation.isPending}
isFallbackImg={!user.avatarUrl}
user={user}
userOrganization={user.organization}
onSubmit={(values) => {
if (values.email !== user.email && isCALIdentityProvider) {
setTempFormValues(values);
setConfirmPasswordOpen(true);
} else {
updateProfileMutation.mutate(values);
}
}}
handleAddSecondaryEmail={() => setShowSecondaryEmailModalOpen(true)}
handleResendVerifyEmail={(email) => {
resendVerifyEmailMutation.mutate({ email });
showToast(t("email_sent"), "success");
}}
handleAccountDisconnect={(values) => {
if (isCALIdentityProvider) return;
if (user?.passwordAdded) {
setTempFormValues(values);
setShowAccountDisconnectWarning(true);
return;
}
setShowCreateAccountPasswordDialog(true);
}}
extraField={
<div className="mt-6">
<UsernameAvailabilityField
onSuccessMutation={async () => {
showToast(t("settings_updated_successfully"), "success");
await utils.viewer.me.invalidate();
}}
onErrorMutation={() => {
showToast(t("error_updating_settings"), "error");
}}
/>
</div>
}
isCALIdentityProvider={isCALIdentityProvider}
/>
<div className="border-subtle mt-6 rounded-lg rounded-b-none border border-b-0 p-6">
<Label className="mb-0 text-base font-semibold text-red-700">{t("danger_zone")}</Label>
<p className="text-subtle text-sm">{t("account_deletion_cannot_be_undone")}</p>
</div>
{/* Delete account Dialog */}
<Dialog open={deleteAccountOpen} onOpenChange={setDeleteAccountOpen}>
<SectionBottomActions align="end">
<DialogTrigger asChild>
<Button data-testid="delete-account" color="destructive" className="mt-1" StartIcon="trash-2">
{t("delete_account")}
</Button>
</DialogTrigger>
</SectionBottomActions>
<DialogContent
title={t("delete_account_modal_title")}
description={t("confirm_delete_account_modal", { appName: APP_NAME })}
type="creation"
Icon="triangle-alert">
<>
<div className="mb-10">
<p className="text-default mb-4">{t("delete_account_confirmation_message")}</p>
{isCALIdentityProvider && (
<PasswordField
data-testid="password"
name="password"
id="password"
autoComplete="current-password"
required
label="Password"
ref={passwordRef}
/>
)}
{user?.twoFactorEnabled && isCALIdentityProvider && (
<Form handleSubmit={onConfirm} className="pb-4" form={form}>
<TwoFactor center={false} />
</Form>
)}
{hasDeleteErrors && <Alert severity="error" title={deleteErrorMessage} />}
</div>
<DialogFooter showDivider>
<DialogClose />
<Button
color="primary"
data-testid="delete-account-confirm"
onClick={(e) => onConfirmButton(e)}>
{t("delete_my_account")}
</Button>
</DialogFooter>
</>
</DialogContent>
</Dialog>
{/* If changing email, confirm password */}
<Dialog open={confirmPasswordOpen} onOpenChange={setConfirmPasswordOpen}>
<DialogContent
title={t("confirm_password")}
description={t("confirm_password_change_email")}
type="creation"
Icon="triangle-alert">
<div className="mb-10">
<div className="mb-4 grid gap-2 md:grid-cols-2">
<div>
<span className="text-emphasis mb-2 block text-sm font-medium leading-none">
{t("old_email_address")}
</span>
<p className="text-subtle leading-none">{user.email}</p>
</div>
<div>
<span className="text-emphasis mb-2 block text-sm font-medium leading-none">
{t("new_email_address")}
</span>
<p className="text-subtle leading-none">{tempFormValues?.email}</p>
</div>
</div>
<PasswordField
data-testid="password"
name="password"
id="password"
autoComplete="current-password"
required
label="Password"
ref={passwordRef}
/>
{confirmPasswordErrorMessage && <Alert severity="error" title={confirmPasswordErrorMessage} />}
</div>
<DialogFooter showDivider>
<Button
data-testid="profile-update-email-submit-button"
color="primary"
loading={confirmPasswordMutation.isPending}
onClick={(e) => onConfirmPassword(e)}>
{t("confirm")}
</Button>
<DialogClose />
</DialogFooter>
</DialogContent>
</Dialog>
<Dialog open={showCreateAccountPasswordDialog} onOpenChange={setShowCreateAccountPasswordDialog}>
<DialogContent
title={t("create_account_password")}
description={t("create_account_password_hint")}
type="creation"
Icon="triangle-alert">
<DialogFooter>
<DialogClose />
</DialogFooter>
</DialogContent>
</Dialog>
<Dialog open={showAccountDisconnectWarning} onOpenChange={setShowAccountDisconnectWarning}>
<DialogContent
title={t("disconnect_account")}
description={t("disconnect_account_hint")}
type="creation"
Icon="triangle-alert">
<DialogFooter>
<Button
color="primary"
onClick={() => {
unlinkConnectedAccountMutation.mutate();
setShowAccountDisconnectWarning(false);
}}>
{t("confirm")}
</Button>
<DialogClose />
</DialogFooter>
</DialogContent>
</Dialog>
{showSecondaryEmailModalOpen && (
<SecondaryEmailModal
isLoading={addSecondaryEmailMutation.isPending}
errorMessage={secondaryEmailAddErrorMessage}
handleAddEmail={(values) => {
setSecondaryEmailAddErrorMessage("");
addSecondaryEmailMutation.mutate(values);
}}
onCancel={() => {
setSecondaryEmailAddErrorMessage("");
setShowSecondaryEmailModalOpen(false);
}}
clearErrorMessage={() => {
addSecondaryEmailMutation.reset();
setSecondaryEmailAddErrorMessage("");
}}
/>
)}
{!!newlyAddedSecondaryEmail && (
<SecondaryEmailConfirmModal
email={newlyAddedSecondaryEmail}
onCancel={() => setNewlyAddedSecondaryEmail(undefined)}
/>
)}
</>
);
};
type SecondaryEmailApiPayload = {
id: number;
email: string;
isDeleted: boolean;
};
type ExtendedFormValues = Omit<FormValues, "secondaryEmails"> & {
secondaryEmails: SecondaryEmailApiPayload[];
};
const ProfileForm = ({
defaultValues,
onSubmit,
handleAddSecondaryEmail,
handleResendVerifyEmail,
handleAccountDisconnect,
extraField,
isPending = false,
isFallbackImg,
user,
userOrganization,
isCALIdentityProvider,
}: {
defaultValues: FormValues;
onSubmit: (values: ExtendedFormValues) => void;
handleAddSecondaryEmail: () => void;
handleResendVerifyEmail: (email: string) => void;
handleAccountDisconnect: (values: ExtendedFormValues) => void;
extraField?: React.ReactNode;
isPending: boolean;
isFallbackImg: boolean;
user: RouterOutputs["viewer"]["me"];
userOrganization: RouterOutputs["viewer"]["me"]["organization"];
isCALIdentityProvider: boolean;
}) => {
const { t } = useLocale();
const [firstRender, setFirstRender] = useState(true);
const profileFormSchema = z.object({
username: z.string(),
avatarUrl: z.string().nullable(),
name: z
.string()
.trim()
.min(1, t("you_need_to_add_a_name"))
.max(FULL_NAME_LENGTH_MAX_LIMIT, {
message: t("max_limit_allowed_hint", { limit: FULL_NAME_LENGTH_MAX_LIMIT }),
}),
email: z.string().email(),
bio: z.string(),
secondaryEmails: z.array(
z.object({
id: z.number(),
email: z.string().email(),
emailVerified: z.union([z.string(), z.null()]).optional(),
emailPrimary: z.boolean().optional(),
})
),
});
const formMethods = useForm<FormValues>({
defaultValues,
resolver: zodResolver(profileFormSchema),
});
const {
fields: secondaryEmailFields,
remove: deleteSecondaryEmail,
replace: updateAllSecondaryEmailFields,
} = useFieldArray({
control: formMethods.control,
name: "secondaryEmails",
keyName: "itemId",
});
const getUpdatedFormValues = (values: FormValues) => {
const changedFields = formMethods.formState.dirtyFields?.secondaryEmails || [];
const updatedValues: FormValues = {
...values,
};
// If the primary email is changed, we will need to update
const primaryEmailIndex = updatedValues.secondaryEmails.findIndex(
(secondaryEmail) => secondaryEmail.emailPrimary
);
if (primaryEmailIndex >= 0) {
// Add the new updated value as primary email
updatedValues.email = updatedValues.secondaryEmails[primaryEmailIndex].email;
}
// We will only send the emails which have already changed
const updatedEmails: Email[] = [];
changedFields.map((field, index) => {
// If the email changed and if its only secondary email, we add it for updation, the first
// item in the list is always primary email
if (field?.email && updatedValues.secondaryEmails[index]?.id) {
updatedEmails.push(updatedValues.secondaryEmails[index]);
}
});
const deletedEmails = (user?.secondaryEmails || []).filter(
(secondaryEmail) => !updatedValues.secondaryEmails.find((val) => val.id && val.id === secondaryEmail.id)
);
const secondaryEmails = [
...updatedEmails.map((email) => ({ ...email, isDeleted: false })),
...deletedEmails.map((email) => ({ ...email, isDeleted: true })),
].map((secondaryEmail) => pick(secondaryEmail, ["id", "email", "isDeleted"]));
return {
...updatedValues,
secondaryEmails,
};
};
const handleFormSubmit = (values: FormValues) => {
onSubmit(getUpdatedFormValues(values));
};
const onDisconnect = () => {
handleAccountDisconnect(getUpdatedFormValues(formMethods.getValues()));
};
const {
formState: { isSubmitting, isDirty },
} = formMethods;
const isDisabled = isSubmitting || !isDirty;
return (
<Form form={formMethods} handleSubmit={handleFormSubmit}>
<div className="border-subtle border-x px-4 pb-10 pt-8 sm:px-6">
<div className="flex items-center">
<Controller
control={formMethods.control}
name="avatarUrl"
render={({ field: { value, onChange } }) => {
const showRemoveAvatarButton = value !== null;
return (
<>
<UserAvatar data-testid="profile-upload-avatar" previewSrc={value} size="lg" user={user} />
<div className="ms-4">
<h2 className="mb-2 text-sm font-medium">{t("profile_picture")}</h2>
<div className="flex gap-2">
<ImageUploader
target="avatar"
id="avatar-upload"
buttonMsg={t("upload_avatar")}
handleAvatarChange={(newAvatar) => {
onChange(newAvatar);
}}
imageSrc={getUserAvatarUrl({ avatarUrl: value })}
triggerButtonColor={showRemoveAvatarButton ? "secondary" : "primary"}
/>
{showRemoveAvatarButton && (
<Button
color="destructive"
onClick={() => {
onChange(null);
}}>
{t("remove")}
</Button>
)}
</div>
</div>
</>
);
}}
/>
</div>
{extraField}
<div className="mt-6">
<TextField label={t("full_name")} {...formMethods.register("name")} />
</div>
<div className="mt-6">
<Label>{t("email")}</Label>
{secondaryEmailFields.map((field, index) => (
<CustomEmailTextField
key={field.itemId}
formMethods={formMethods}
formMethodFieldName={`secondaryEmails.${index}.email` as keyof FormValues}
errorMessage={get(formMethods.formState.errors, `secondaryEmails.${index}.email.message`)}
emailVerified={Boolean(field.emailVerified)}
emailPrimary={field.emailPrimary}
dataTestId={`profile-form-email-${index}`}
handleChangePrimary={() => {
const fields = secondaryEmailFields.map((secondaryField, cIndex) => ({
...secondaryField,
emailPrimary: cIndex === index,
}));
updateAllSecondaryEmailFields(fields);
}}
handleVerifyEmail={() => handleResendVerifyEmail(field.email)}
handleItemDelete={() => deleteSecondaryEmail(index)}
/>
))}
<div className="text-default mt-2 flex items-center text-sm">{t("change_email_hint")}</div>
<Button
color="minimal"
StartIcon="plus"
className="mt-2"
onClick={() => handleAddSecondaryEmail()}
data-testid="add-secondary-email">
{t("add_email")}
</Button>
</div>
<div className="mt-6">
<Label>{t("about")}</Label>
<Editor
getText={() => md.render(formMethods.getValues("bio") || "")}
setText={(value: string) => {
formMethods.setValue("bio", turndown(value), { shouldDirty: true });
}}
excludedToolbarItems={["blockType"]}
disableLists
firstRender={firstRender}
setFirstRender={setFirstRender}
height="80px"
/>
</div>
{/* // For Non-Cal indentities, we merge the values from DB and the user logging in,
so essentially there is no point in allowing them to disconnect, since when they log in they will get logged into the same account */}
{!isCALIdentityProvider && user.email !== user.identityProviderEmail && (
<div className="mt-6">
<Label>Connected accounts</Label>
<div className="flex items-center">
<span className="text-default text-sm capitalize">{user.identityProvider.toLowerCase()}</span>
{user.identityProviderEmail && (
<span className="text-default ml-2 text-sm">{user.identityProviderEmail}</span>
)}
<div className="flex flex-1 justify-end">
<Button color="destructive" onClick={onDisconnect}>
{t("disconnect")}
</Button>
</div>
</div>
</div>
)}
</div>
<SectionBottomActions align="end">
<Button
loading={isPending}
disabled={isDisabled}
color="primary"
type="submit"
data-testid="profile-submit-button">
{t("update")}
</Button>
</SectionBottomActions>
</Form>
);
};
export default ProfileView;
@@ -0,0 +1,77 @@
"use client";
import { useState } from "react";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import type { RouterOutputs } from "@calcom/trpc/react";
import { showToast, SettingsToggle, SkeletonContainer, SkeletonText } from "@calcom/ui";
const SkeletonLoader = () => {
return (
<SkeletonContainer>
<div className="border-subtle space-y-6 border border-t-0 px-4 py-8 sm:px-6">
<SkeletonText className="h-8 w-full" />
</div>
</SkeletonContainer>
);
};
const ProfileImpersonationView = ({ user }: { user: RouterOutputs["viewer"]["me"] }) => {
const { t } = useLocale();
const utils = trpc.useUtils();
const [disableImpersonation, setDisableImpersonation] = useState<boolean | undefined>(
user?.disableImpersonation
);
const mutation = trpc.viewer.updateProfile.useMutation({
onSuccess: () => {
showToast(t("profile_updated_successfully"), "success");
},
onSettled: () => {
utils.viewer.me.invalidate();
},
onMutate: async ({ disableImpersonation }) => {
await utils.viewer.me.cancel();
const previousValue = utils.viewer.me.getData();
setDisableImpersonation(disableImpersonation);
return { previousValue };
},
onError: (error, variables, context) => {
if (context?.previousValue) {
utils.viewer.me.setData(undefined, context.previousValue);
setDisableImpersonation(context.previousValue?.disableImpersonation);
}
showToast(`${t("error")}, ${error.message}`, "error");
},
});
return (
<>
<div>
<SettingsToggle
toggleSwitchAtTheEnd={true}
title={t("user_impersonation_heading")}
description={t("user_impersonation_description")}
checked={!disableImpersonation}
onCheckedChange={(checked) => {
mutation.mutate({ disableImpersonation: !checked });
}}
switchContainerClassName="rounded-t-none border-t-0"
disabled={mutation.isPending}
/>
</div>
</>
);
};
const ProfileImpersonationViewWrapper = () => {
const { data: user, isPending } = trpc.viewer.me.useQuery();
if (isPending || !user) return <SkeletonLoader />;
return <ProfileImpersonationView user={user} />;
};
export default ProfileImpersonationViewWrapper;
@@ -0,0 +1,315 @@
"use client";
import { signOut, useSession } from "next-auth/react";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { identityProviderNameMap } from "@calcom/features/auth/lib/identityProviderNameMap";
import SectionBottomActions from "@calcom/features/settings/SectionBottomActions";
import { classNames } from "@calcom/lib";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { IdentityProvider } from "@calcom/prisma/enums";
import { userMetadata as userMetadataSchema } from "@calcom/prisma/zod-utils";
import type { RouterOutputs } from "@calcom/trpc/react";
import { trpc } from "@calcom/trpc/react";
import {
Alert,
Button,
Form,
PasswordField,
Select,
SettingsToggle,
showToast,
SkeletonButton,
SkeletonContainer,
SkeletonText,
} from "@calcom/ui";
type ChangePasswordSessionFormValues = {
oldPassword: string;
newPassword: string;
sessionTimeout?: number;
apiError: string;
};
interface PasswordViewProps {
user: RouterOutputs["viewer"]["me"];
}
const SkeletonLoader = () => {
return (
<SkeletonContainer>
<div className="border-subtle space-y-6 border-x px-4 py-8 sm:px-6">
<SkeletonText className="h-8 w-full" />
<SkeletonText className="h-8 w-full" />
<SkeletonText className="h-8 w-full" />
</div>
<div className="rounded-b-xl">
<SectionBottomActions align="end">
<SkeletonButton className="ml-auto h-8 w-20 rounded-md" />
</SectionBottomActions>
</div>
</SkeletonContainer>
);
};
const PasswordView = ({ user }: PasswordViewProps) => {
const { data } = useSession();
const { t } = useLocale();
const utils = trpc.useUtils();
const metadata = userMetadataSchema.safeParse(user?.metadata);
const initialSessionTimeout = metadata.success ? metadata.data?.sessionTimeout : undefined;
const [sessionTimeout, setSessionTimeout] = useState<number | undefined>(initialSessionTimeout);
const sessionMutation = trpc.viewer.updateProfile.useMutation({
onSuccess: (data) => {
showToast(t("session_timeout_changed"), "success");
formMethods.reset(formMethods.getValues());
setSessionTimeout(data.metadata?.sessionTimeout);
},
onSettled: () => {
utils.viewer.me.invalidate();
},
onMutate: async () => {
await utils.viewer.me.cancel();
const previousValue = await utils.viewer.me.getData();
const previousMetadata = userMetadataSchema.safeParse(previousValue?.metadata);
if (previousValue && sessionTimeout && previousMetadata.success) {
utils.viewer.me.setData(undefined, {
...previousValue,
metadata: { ...previousMetadata?.data, sessionTimeout: sessionTimeout },
});
return { previousValue };
}
},
onError: (error, _, context) => {
if (context?.previousValue) {
utils.viewer.me.setData(undefined, context.previousValue);
}
showToast(`${t("session_timeout_change_error")}, ${error.message}`, "error");
},
});
const passwordMutation = trpc.viewer.auth.changePassword.useMutation({
onSuccess: () => {
showToast(t("password_has_been_changed"), "success");
formMethods.resetField("oldPassword");
formMethods.resetField("newPassword");
if (data?.user.role === "INACTIVE_ADMIN") {
/*
AdminPasswordBanner component relies on the role returned from the session.
Next-Auth doesn't provide a way to revalidate the session cookie,
so this a workaround to hide the banner after updating the password.
discussion: https://github.com/nextauthjs/next-auth/discussions/4229
*/
signOut({ callbackUrl: "/auth/login" });
}
},
onError: (error) => {
showToast(`${t("error_updating_password")}, ${t(error.message)}`, "error");
formMethods.setError("apiError", {
message: t(error.message),
type: "custom",
});
},
});
const createAccountPasswordMutation = trpc.viewer.auth.createAccountPassword.useMutation({
onSuccess: () => {
showToast(t("password_reset_email", { email: user.email }), "success");
},
onError: (error) => {
showToast(`${t("error_creating_account_password")}, ${t(error.message)}`, "error");
},
});
const formMethods = useForm<ChangePasswordSessionFormValues>({
defaultValues: {
oldPassword: "",
newPassword: "",
},
});
const handleSubmit = (values: ChangePasswordSessionFormValues) => {
const { oldPassword, newPassword } = values;
if (!oldPassword.length) {
formMethods.setError(
"oldPassword",
{ type: "required", message: t("error_required_field") },
{ shouldFocus: true }
);
}
if (!newPassword.length) {
formMethods.setError(
"newPassword",
{ type: "required", message: t("error_required_field") },
{ shouldFocus: true }
);
}
if (oldPassword && newPassword) {
passwordMutation.mutate({ oldPassword, newPassword });
}
};
const timeoutOptions = [5, 10, 15].map((mins) => ({
label: t("multiple_duration_mins", { count: mins }),
value: mins,
}));
const isDisabled = formMethods.formState.isSubmitting || !formMethods.formState.isDirty;
const passwordMinLength = data?.user.role === "USER" ? 7 : 15;
const isUser = data?.user.role === "USER";
return (
<>
{user && user.identityProvider !== IdentityProvider.CAL && !user.passwordAdded ? (
<div className="border-subtle rounded-b-xl border border-t-0">
<div className="px-4 py-6 sm:px-6">
<h2 className="font-cal text-emphasis text-lg font-medium leading-6">
{t("account_managed_by_identity_provider", {
provider: identityProviderNameMap[user.identityProvider],
})}
</h2>
<p className="text-subtle mt-1 text-sm">
{t("account_managed_by_identity_provider_description", {
provider: identityProviderNameMap[user.identityProvider],
})}
</p>
<Button
className="mt-3"
onClick={() => createAccountPasswordMutation.mutate()}
loading={createAccountPasswordMutation.isPending}>
{t("create_account_password")}
</Button>
</div>
</div>
) : (
<Form form={formMethods} handleSubmit={handleSubmit}>
<div className="border-subtle border-x px-4 py-6 sm:px-6">
{formMethods.formState.errors.apiError && (
<div className="pb-6">
<Alert severity="error" message={formMethods.formState.errors.apiError?.message} />
</div>
)}
<div className="w-full sm:grid sm:grid-cols-2 sm:gap-x-6">
<div>
<PasswordField {...formMethods.register("oldPassword")} label={t("old_password")} />
</div>
<div>
<PasswordField
{...formMethods.register("newPassword", {
minLength: {
message: t(isUser ? "password_hint_min" : "password_hint_admin_min"),
value: passwordMinLength,
},
pattern: {
message: "Should contain a number, uppercase and lowercase letters",
value: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).*$/gm,
},
})}
label={t("new_password")}
/>
</div>
</div>
<p className="text-default mt-4 w-full text-sm">
{t("invalid_password_hint", { passwordLength: passwordMinLength })}
</p>
</div>
<SectionBottomActions align="end">
<Button
color="primary"
type="submit"
loading={passwordMutation.isPending}
onClick={() => formMethods.clearErrors("apiError")}
disabled={isDisabled || passwordMutation.isPending || sessionMutation.isPending}>
{t("update")}
</Button>
</SectionBottomActions>
<div className="mt-6">
<SettingsToggle
toggleSwitchAtTheEnd={true}
title={t("session_timeout")}
description={t("session_timeout_description")}
checked={sessionTimeout !== undefined}
data-testid="session-check"
onCheckedChange={(e) => {
if (!e) {
setSessionTimeout(undefined);
if (metadata.success) {
sessionMutation.mutate({
metadata: { ...metadata.data, sessionTimeout: undefined },
});
}
} else {
setSessionTimeout(10);
}
}}
childrenClassName="lg:ml-0"
switchContainerClassName={classNames(
"py-6 px-4 sm:px-6 border-subtle rounded-xl border",
!!sessionTimeout && "rounded-b-none"
)}>
<>
<div className="border-subtle border-x p-6 pb-8">
<div className="flex flex-col">
<p className="text-default mb-2 font-medium">{t("session_timeout_after")}</p>
<Select
options={timeoutOptions}
defaultValue={
sessionTimeout
? timeoutOptions.find((tmo) => tmo.value === sessionTimeout)
: timeoutOptions[1]
}
isSearchable={false}
className="block h-[36px] !w-auto min-w-0 flex-none rounded-md text-sm"
onChange={(event) => {
setSessionTimeout(event?.value);
}}
/>
</div>
</div>
<SectionBottomActions align="end">
<Button
color="primary"
loading={sessionMutation.isPending}
onClick={() => {
sessionMutation.mutate({
metadata: { ...metadata, sessionTimeout },
});
formMethods.clearErrors("apiError");
}}
disabled={
initialSessionTimeout === sessionTimeout ||
passwordMutation.isPending ||
sessionMutation.isPending
}>
{t("update")}
</Button>
</SectionBottomActions>
</>
</SettingsToggle>
</div>
</Form>
)}
</>
);
};
const PasswordViewWrapper = () => {
const { data: user, isPending } = trpc.viewer.me.useQuery({ includePasswordAdded: true });
const { t } = useLocale();
if (isPending || !user) return <SkeletonLoader />;
return <PasswordView user={user} />;
};
export default PasswordViewWrapper;
@@ -0,0 +1,86 @@
"use client";
import { useState } from "react";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Badge, SkeletonButton, SkeletonContainer, SkeletonText, Alert, SettingsToggle } from "@calcom/ui";
import DisableTwoFactorModal from "@components/settings/DisableTwoFactorModal";
import EnableTwoFactorModal from "@components/settings/EnableTwoFactorModal";
const SkeletonLoader = () => {
return (
<SkeletonContainer>
<div className="mb-8 mt-6 space-y-6">
<div className="flex items-center">
<SkeletonButton className="mr-6 h-8 w-20 rounded-md p-5" />
<SkeletonText className="h-8 w-full" />
</div>
</div>
</SkeletonContainer>
);
};
const TwoFactorAuthView = () => {
const utils = trpc.useUtils();
const { t } = useLocale();
const { data: user, isPending } = trpc.viewer.me.useQuery({ includePasswordAdded: true });
const [enableModalOpen, setEnableModalOpen] = useState<boolean>(false);
const [disableModalOpen, setDisableModalOpen] = useState<boolean>(false);
if (isPending) return <SkeletonLoader />;
const isCalProvider = user?.identityProvider === "CAL";
const canSetupTwoFactor = !isCalProvider && !user?.twoFactorEnabled && !user?.passwordAdded;
return (
<>
{canSetupTwoFactor && <Alert severity="neutral" message={t("2fa_disabled")} />}
<SettingsToggle
toggleSwitchAtTheEnd={true}
data-testid="two-factor-switch"
title={t("two_factor_auth")}
description={t("add_an_extra_layer_of_security")}
checked={user?.twoFactorEnabled ?? false}
onCheckedChange={() =>
user?.twoFactorEnabled ? setDisableModalOpen(true) : setEnableModalOpen(true)
}
Badge={
<Badge className="mx-2 text-xs" variant={user?.twoFactorEnabled ? "success" : "gray"}>
{user?.twoFactorEnabled ? t("enabled") : t("disabled")}
</Badge>
}
switchContainerClassName="rounded-t-none border-t-0"
/>
<EnableTwoFactorModal
open={enableModalOpen}
onOpenChange={() => setEnableModalOpen(!enableModalOpen)}
onEnable={() => {
setEnableModalOpen(false);
utils.viewer.me.invalidate();
}}
onCancel={() => {
setEnableModalOpen(false);
}}
/>
<DisableTwoFactorModal
open={disableModalOpen}
disablePassword={!isCalProvider}
onOpenChange={() => setDisableModalOpen(!disableModalOpen)}
onDisable={() => {
setDisableModalOpen(false);
utils.viewer.me.invalidate();
}}
onCancel={() => {
setDisableModalOpen(false);
}}
/>
</>
);
};
export default TwoFactorAuthView;