feat: Verify email of people setting a meeting with you (#10317)

* booker email verification changes

* name type fix

* use totp and code

* prisma schema styling

* refactor: code

Signed-off-by: Udit Takkar <[email protected]>

* fix: book event form

Signed-off-by: Udit Takkar <[email protected]>

* fix: type error

Signed-off-by: Udit Takkar <[email protected]>

* fix: type errors

Signed-off-by: Udit Takkar <[email protected]>

* fix: unit tests

Signed-off-by: Udit Takkar <[email protected]>

* refactor: move verifycodedialog from ui and to features/bookings

* fix: type error

---------

Signed-off-by: Udit Takkar <[email protected]>
Co-authored-by: rkreddy99 <[email protected]>
Co-authored-by: Udit Takkar <[email protected]>
This commit is contained in:
authored and GitHub committed 2023-07-31 17:51:11 +00:00
1 parent fcd8de43d6
commit 5a430df5d9
31 files changed
+546 -190

No files matched your search

+1
View File
@@ -8,6 +8,7 @@ export enum ErrorCode {
TwoFactorSetupRequired = "two-factor-setup-required",
SecondFactorRequired = "second-factor-required",
IncorrectTwoFactorCode = "incorrect-two-factor-code",
IncorrectEmailVerificationCode = "incorrect_email_verification_code",
InternalServerError = "internal-server-error",
NewPasswordMatchesOld = "new-password-matches-old",
ThirdPartyIdentityProviderEnabled = "third-party-identity-provider-enabled",
+24 -2
View File
@@ -1,6 +1,7 @@
import { randomBytes } from "crypto";
import { randomBytes, createHash } from "crypto";
import { totp } from "otplib";
import { sendEmailVerificationLink } from "@calcom/emails/email-manager";
import { sendEmailVerificationCode, sendEmailVerificationLink } from "@calcom/emails/email-manager";
import { getFeatureFlagMap } from "@calcom/features/flags/server/utils";
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
import { WEBAPP_URL } from "@calcom/lib/constants";
@@ -54,3 +55,24 @@ export const sendEmailVerification = async ({ email, language, username }: Verif
return { ok: true, skipped: false };
};
export const sendEmailVerificationByCode = async ({ email, language, username }: VerifyEmailType) => {
const translation = await getTranslation(language ?? "en", "common");
const secret = createHash("md5")
.update(email + process.env.CALENDSO_ENCRYPTION_KEY)
.digest("hex");
totp.options = { step: 900 };
const code = totp.generate(secret);
await sendEmailVerificationCode({
language: translation,
verificationEmailCode: code,
user: {
email,
name: username,
},
});
return { ok: true, skipped: false };
};
@@ -4,7 +4,7 @@ import { useMutation } from "@tanstack/react-query";
import { useSession } from "next-auth/react";
import type { TFunction } from "next-i18next";
import { useRouter } from "next/router";
import { useEffect, useMemo, useRef } from "react";
import { useEffect, useMemo, useRef, useState } from "react";
import type { FieldError } from "react-hook-form";
import { useForm } from "react-hook-form";
import { z } from "zod";
@@ -12,6 +12,7 @@ import { z } from "zod";
import type { EventLocationType } from "@calcom/app-store/locations";
import { createPaymentLink } from "@calcom/app-store/stripepayment/lib/client";
import dayjs from "@calcom/dayjs";
import { VerifyCodeDialog } from "@calcom/features/bookings/components/VerifyCodeDialog";
import {
useTimePreferences,
mapBookingToMutationInput,
@@ -29,7 +30,7 @@ import { MINUTES_TO_BOOK } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { HttpError } from "@calcom/lib/http-error";
import { trpc } from "@calcom/trpc";
import { Form, Button, Alert, EmptyScreen } from "@calcom/ui";
import { Form, Button, Alert, EmptyScreen, showToast } from "@calcom/ui";
import { Calendar } from "@calcom/ui/components/icon";
import { useBookerStore } from "../../store";
@@ -63,6 +64,8 @@ export const BookEventForm = ({ onCancel }: BookEventFormProps) => {
const formValues = useBookerStore((state) => state.formValues);
const setFormValues = useBookerStore((state) => state.setFormValues);
const seatedEventData = useBookerStore((state) => state.seatedEventData);
const verifiedEmail = useBookerStore((state) => state.verifiedEmail);
const setVerifiedEmail = useBookerStore((state) => state.setVerifiedEmail);
const isRescheduling = !!rescheduleUid && !!bookingData;
const event = useEvent();
const eventType = event.data;
@@ -269,6 +272,37 @@ export const BookEventForm = ({ onCancel }: BookEventFormProps) => {
},
});
const [isEmailVerificationModalVisible, setEmailVerificationModalVisible] = useState(false);
const email = bookingForm.watch("responses.email");
const sendEmailVerificationByCodeMutation = trpc.viewer.auth.sendVerifyEmailCode.useMutation({
onSuccess() {
showToast(t("email_sent"), "success");
},
onError() {
showToast(t("email_not_sent"), "error");
},
});
const verifyEmail = () => {
bookingForm.clearErrors();
// It shouldn't be possible that this method is fired without having event data,
// but since in theory (looking at the types) it is possible, we still handle that case.
if (!event?.data) {
bookingForm.setError("globalError", { message: t("error_booking_event") });
return;
}
const name = bookingForm.getValues("responses.name");
sendEmailVerificationByCodeMutation.mutate({
email,
username: typeof name === "string" ? name : name.firstName,
});
setEmailVerificationModalVisible(true);
};
if (event.isError) return <Alert severity="warning" message={t("error_booking_event")} />;
if (event.isLoading || !event.data) return <FormSkeleton />;
if (!timeslot)
@@ -338,6 +372,9 @@ export const BookEventForm = ({ onCancel }: BookEventFormProps) => {
return <Alert severity="warning" message={t("error_booking_event")} />;
}
const renderConfirmNotVerifyEmailButtonCond =
!eventType?.requiresBookerEmailVerification || (email && verifiedEmail && verifiedEmail === email);
return (
<div className="flex h-full flex-col">
<Form
@@ -350,7 +387,7 @@ export const BookEventForm = ({ onCancel }: BookEventFormProps) => {
setFormValues(values);
}}
form={bookingForm}
handleSubmit={bookEvent}
handleSubmit={renderConfirmNotVerifyEmailButtonCond ? bookEvent : verifyEmail}
noValidate>
<BookingFields
isDynamicGroupBooking={!!(username && username.indexOf("+") > -1)}
@@ -387,10 +424,24 @@ export const BookEventForm = ({ onCancel }: BookEventFormProps) => {
color="primary"
loading={createBookingMutation.isLoading || createRecurringBookingMutation.isLoading}
data-testid={rescheduleUid ? "confirm-reschedule-button" : "confirm-book-button"}>
{rescheduleUid ? t("reschedule") : t("confirm")}
{rescheduleUid
? t("reschedule")
: renderConfirmNotVerifyEmailButtonCond
? t("confirm")
: t("verify_email_email_button")}
</Button>
</div>
</Form>
<VerifyCodeDialog
isOpenDialog={isEmailVerificationModalVisible}
setIsOpenDialog={setEmailVerificationModalVisible}
email={email}
onSuccess={() => {
setVerifiedEmail(email);
setEmailVerificationModalVisible(false);
}}
isUserSessionRequiredToVerify={false}
/>
</div>
);
};
@@ -22,6 +22,7 @@ type StoreInitializeType = {
bookingUid?: string | null;
isTeamEvent?: boolean;
bookingData?: GetBookingType | null | undefined;
verifiedEmail?: string | null;
rescheduleUid?: string | null;
seatReferenceUid?: string;
org?: string | null;
@@ -41,6 +42,12 @@ export type BookerStore = {
username: string | null;
eventSlug: string | null;
eventId: number | null;
/**
* Verified booker email.
* Needed in case user turns on Requires Booker Email Verification for an event
*/
verifiedEmail: string | null;
setVerifiedEmail: (email: string | null) => void;
/**
* Current month being viewed. Format is YYYY-MM.
*/
@@ -173,6 +180,10 @@ export const useBookerStore = create<BookerStore>((set, get) => ({
username: null,
eventSlug: null,
eventId: null,
verifiedEmail: null,
setVerifiedEmail: (email: string | null) => {
set({ verifiedEmail: email });
},
month: getQueryParam("month") || getQueryParam("date") || dayjs().format("YYYY-MM"),
setMonth: (month: string | null) => {
set({ month, selectedTimeslot: null });
@@ -268,6 +279,7 @@ export const useInitializeBookerStore = ({
eventId,
rescheduleUid = null,
bookingData = null,
verifiedEmail = null,
layout,
isTeamEvent,
org,
@@ -284,6 +296,7 @@ export const useInitializeBookerStore = ({
layout,
isTeamEvent,
org,
verifiedEmail,
});
}, [
initializeStore,
@@ -296,5 +309,6 @@ export const useInitializeBookerStore = ({
bookingData,
layout,
isTeamEvent,
verifiedEmail,
]);
};
@@ -0,0 +1,143 @@
import type { Dispatch, SetStateAction } from "react";
import { useState, useEffect } from "react";
import useDigitInput from "react-digit-input";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import {
Button,
Dialog,
DialogClose,
DialogContent,
DialogFooter,
DialogHeader,
Label,
Input,
} from "@calcom/ui";
import { Info } from "@calcom/ui/components/icon";
export const VerifyCodeDialog = ({
isOpenDialog,
setIsOpenDialog,
email,
onSuccess,
isUserSessionRequiredToVerify = true,
}: {
isOpenDialog: boolean;
setIsOpenDialog: Dispatch<SetStateAction<boolean>>;
email: string;
onSuccess: (isVerified: boolean) => void;
isUserSessionRequiredToVerify?: boolean;
}) => {
const { t } = useLocale();
// Not using the mutation isLoading flag because after verifying we submit the underlying org creation form
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState("");
const [value, onChange] = useState("");
const digits = useDigitInput({
acceptedCharacters: /^[0-9]$/,
length: 6,
value,
onChange,
});
const verifyCodeMutationUserSessionRequired = trpc.viewer.organizations.verifyCode.useMutation({
onSuccess: (data) => {
setIsLoading(false);
onSuccess(data);
},
onError: (err) => {
setIsLoading(false);
if (err.message === "invalid_code") {
setError(t("code_provided_invalid"));
}
},
});
const verifyCodeMutationUserSessionNotRequired = trpc.viewer.auth.verifyCodeUnAuthenticated.useMutation({
onSuccess: (data) => {
setIsLoading(false);
onSuccess(data);
},
onError: (err) => {
setIsLoading(false);
if (err.message === "invalid_code") {
setError(t("code_provided_invalid"));
}
},
});
useEffect(() => onChange(""), [isOpenDialog]);
const digitClassName = "h-12 w-12 !text-xl text-center";
return (
<Dialog
open={isOpenDialog}
onOpenChange={(open) => {
onChange("");
setError("");
setIsOpenDialog(open);
}}>
<DialogContent className="sm:max-w-md">
<div className="flex flex-row">
<div className="w-full">
<DialogHeader title={t("verify_your_email")} subtitle={t("enter_digit_code", { email })} />
<Label htmlFor="code">{t("code")}</Label>
<div className="flex flex-row justify-between">
<Input
className={digitClassName}
name="2fa1"
inputMode="decimal"
{...digits[0]}
autoFocus
autoComplete="one-time-code"
/>
<Input className={digitClassName} name="2fa2" inputMode="decimal" {...digits[1]} />
<Input className={digitClassName} name="2fa3" inputMode="decimal" {...digits[2]} />
<Input className={digitClassName} name="2fa4" inputMode="decimal" {...digits[3]} />
<Input className={digitClassName} name="2fa5" inputMode="decimal" {...digits[4]} />
<Input className={digitClassName} name="2fa6" inputMode="decimal" {...digits[5]} />
</div>
{error && (
<div className="mt-2 flex items-center gap-x-2 text-sm text-red-700">
<div>
<Info className="h-3 w-3" />
</div>
<p>{error}</p>
</div>
)}
<DialogFooter>
<DialogClose />
<Button
loading={isLoading}
disabled={isLoading}
onClick={() => {
setError("");
if (value === "") {
setError("The code is a required field");
} else {
setIsLoading(true);
if (isUserSessionRequiredToVerify) {
verifyCodeMutationUserSessionRequired.mutate({
code: value,
email,
});
} else {
verifyCodeMutationUserSessionNotRequired.mutate({
code: value,
email,
});
}
}
}}>
{t("verify")}
</Button>
</DialogFooter>
</div>
</div>
</DialogContent>
</Dialog>
);
};
@@ -259,6 +259,7 @@ const getEventTypesFromDB = async (eventTypeId: number) => {
periodDays: true,
periodCountCalendarDays: true,
requiresConfirmation: true,
requiresBookerEmailVerification: true,
userId: true,
price: true,
currency: true,
@@ -2384,6 +2385,7 @@ const findBookingQuery = async (bookingId: number) => {
currency: true,
length: true,
requiresConfirmation: true,
requiresBookerEmailVerification: true,
price: true,
},
},
@@ -1,29 +1,16 @@
import { signIn } from "next-auth/react";
import { useRouter } from "next/router";
import type { Dispatch, SetStateAction } from "react";
import { useState } from "react";
import useDigitInput from "react-digit-input";
import { Controller, useForm } from "react-hook-form";
import { VerifyCodeDialog } from "@calcom/features/bookings/components/VerifyCodeDialog";
import { subdomainSuffix } from "@calcom/features/ee/organizations/lib/orgDomains";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import slugify from "@calcom/lib/slugify";
import { telemetryEventTypes, useTelemetry } from "@calcom/lib/telemetry";
import { trpc } from "@calcom/trpc/react";
import {
Button,
Form,
TextField,
Alert,
Dialog,
DialogClose,
DialogContent,
DialogFooter,
DialogHeader,
Label,
Input,
} from "@calcom/ui";
import { ArrowRight, Info } from "@calcom/ui/components/icon";
import { Button, Form, TextField, Alert } from "@calcom/ui";
import { ArrowRight } from "@calcom/ui/components/icon";
function extractDomainFromEmail(email: string) {
let out = "";
@@ -34,107 +21,6 @@ function extractDomainFromEmail(email: string) {
return out.split(".")[0];
}
export const VerifyCodeDialog = ({
isOpenDialog,
setIsOpenDialog,
email,
onSuccess,
}: {
isOpenDialog: boolean;
setIsOpenDialog: Dispatch<SetStateAction<boolean>>;
email: string;
onSuccess: (isVerified: boolean) => void;
}) => {
const { t } = useLocale();
// Not using the mutation isLoading flag because after verifying we submit the underlying org creation form
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState("");
const [value, onChange] = useState("");
const digits = useDigitInput({
acceptedCharacters: /^[0-9]$/,
length: 6,
value,
onChange,
});
const verifyCodeMutation = trpc.viewer.organizations.verifyCode.useMutation({
onSuccess: (data) => {
setIsLoading(false);
onSuccess(data);
},
onError: (err) => {
setIsLoading(false);
if (err.message === "invalid_code") {
setError(t("code_provided_invalid"));
}
},
});
const digitClassName = "h-12 w-12 !text-xl text-center";
return (
<Dialog
open={isOpenDialog}
onOpenChange={(open) => {
onChange("");
setError("");
setIsOpenDialog(open);
}}>
<DialogContent className="sm:max-w-md">
<div className="flex flex-row">
<div className="w-full">
<DialogHeader title={t("verify_your_email")} subtitle={t("enter_digit_code", { email })} />
<Label htmlFor="code">{t("code")}</Label>
<div className="flex flex-row justify-between">
<Input
className={digitClassName}
name="2fa1"
inputMode="decimal"
{...digits[0]}
autoFocus
autoComplete="one-time-code"
/>
<Input className={digitClassName} name="2fa2" inputMode="decimal" {...digits[1]} />
<Input className={digitClassName} name="2fa3" inputMode="decimal" {...digits[2]} />
<Input className={digitClassName} name="2fa4" inputMode="decimal" {...digits[3]} />
<Input className={digitClassName} name="2fa5" inputMode="decimal" {...digits[4]} />
<Input className={digitClassName} name="2fa6" inputMode="decimal" {...digits[5]} />
</div>
{error && (
<div className="mt-2 flex items-center gap-x-2 text-sm text-red-700">
<div>
<Info className="h-3 w-3" />
</div>
<p>{error}</p>
</div>
)}
<DialogFooter>
<DialogClose />
<Button
disabled={isLoading}
onClick={() => {
setError("");
if (value === "") {
setError("The code is a required field");
} else {
setIsLoading(true);
verifyCodeMutation.mutate({
code: value,
email,
});
}
}}>
{t("verify")}
</Button>
</DialogFooter>
</div>
</div>
</DialogContent>
</Dialog>
);
};
export const CreateANewOrganizationForm = ({ slug }: { slug?: string }) => {
const { t, i18n } = useLocale();
const router = useRouter();
@@ -32,6 +32,7 @@ const publicEventSelect = Prisma.validator<Prisma.EventTypeSelect>()({
disableGuests: true,
metadata: true,
requiresConfirmation: true,
requiresBookerEmailVerification: true,
recurringEvent: true,
price: true,
currency: true,