feat: email verification (#9081)
* Verify - inital email commit * Add token type - api redirect - migration * Redirect and valid api callback route * Update email design * Change signup URL to redirect to verify-email * Add feature flag - add a11y text to email - add top banner * Shell shouldnt redirect to onboarding if the user needs to verify account * Move flag check to server * Cleanup * Rate limit * Fix redirects * Remove api signup mess * Double negation for forced bool * Fix props * Update packages/emails/templates/account-verify-email.ts * Enable migration by default * Fix typos * Fix google verify issue * Update packages/features/auth/lib/verifyEmail.ts Co-authored-by: Hariom Balhara <[email protected]> * NITS: @harioms addressed * Remove schema changes * Fix NITs+ improvments * Update apps/web/pages/api/auth/verify-email.ts Co-authored-by: Omar López <[email protected]> * Update packages/features/ee/common/components/LicenseRequired.tsx Co-authored-by: Omar López <[email protected]> * Update apps/web/pages/api/auth/verify-email.ts Co-authored-by: Omar López <[email protected]> * Always preloads feature flags * Update verifyEmail.ts * Update schema.prisma * Type fix --------- Co-authored-by: Hariom Balhara <[email protected]> Co-authored-by: Omar López <[email protected]>
This commit is contained in:
23 files changed
+493
-21
No files matched your search
@@ -1,11 +1,20 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { z } from "zod";
|
||||
|
||||
import { hashPassword } from "@calcom/features/auth/lib/hashPassword";
|
||||
import { sendEmailVerification } from "@calcom/features/auth/lib/verifyEmail";
|
||||
import slugify from "@calcom/lib/slugify";
|
||||
import { closeComUpsertTeamUser } from "@calcom/lib/sync/SyncServiceManager";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { IdentityProvider } from "@calcom/prisma/enums";
|
||||
|
||||
const signupSchema = z.object({
|
||||
username: z.string(),
|
||||
email: z.string().email(),
|
||||
password: z.string().min(7),
|
||||
language: z.string().optional(),
|
||||
});
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method !== "POST") {
|
||||
return;
|
||||
@@ -17,7 +26,8 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
|
||||
}
|
||||
|
||||
const data = req.body;
|
||||
const { email, password } = data;
|
||||
const { email, password, language } = signupSchema.parse(data);
|
||||
|
||||
const username = slugify(data.username);
|
||||
const userEmail = email.toLowerCase();
|
||||
|
||||
@@ -26,16 +36,6 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
|
||||
return;
|
||||
}
|
||||
|
||||
if (!userEmail || !userEmail.includes("@")) {
|
||||
res.status(422).json({ message: "Invalid email" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!password || password.trim().length < 7) {
|
||||
res.status(422).json({ message: "Invalid input - password should be at least 7 characters long." });
|
||||
return;
|
||||
}
|
||||
|
||||
// There is an existingUser if the username matches
|
||||
// OR if the email matches AND either the email is verified
|
||||
// or both username and password are set
|
||||
@@ -106,5 +106,11 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
|
||||
}
|
||||
}
|
||||
|
||||
await sendEmailVerification({
|
||||
email: userEmail,
|
||||
username,
|
||||
language,
|
||||
});
|
||||
|
||||
res.status(201).json({ message: "Created user" });
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { z } from "zod";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
|
||||
const verifySchema = z.object({
|
||||
token: z.string(),
|
||||
});
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const { token } = verifySchema.parse(req.query);
|
||||
|
||||
const foundToken = await prisma.verificationToken.findFirst({
|
||||
where: {
|
||||
token,
|
||||
},
|
||||
});
|
||||
|
||||
if (!foundToken) {
|
||||
return res.status(401).json({ message: "No token found" });
|
||||
}
|
||||
|
||||
if (dayjs(foundToken?.expires).isBefore(dayjs())) {
|
||||
return res.status(401).json({ message: "Token expired" });
|
||||
}
|
||||
|
||||
const user = await prisma.user.update({
|
||||
where: {
|
||||
email: foundToken?.identifier,
|
||||
},
|
||||
data: {
|
||||
emailVerified: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
// Delete token from DB after it has been used
|
||||
await prisma.verificationToken.delete({
|
||||
where: {
|
||||
id: foundToken?.id,
|
||||
},
|
||||
});
|
||||
|
||||
const hasCompletedOnboarding = user.completedOnboarding;
|
||||
|
||||
res.redirect(`${WEBAPP_URL}/${hasCompletedOnboarding ? "/event-types" : "/getting-started"}`);
|
||||
}
|
||||
@@ -60,9 +60,14 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
res.setHeader("Content-Type", "text/html");
|
||||
res.setHeader("Cache-Control", "no-cache, no-store, private, must-revalidate");
|
||||
res.write(
|
||||
renderEmail("OrganizerRequestEmail", {
|
||||
calEvent: evt,
|
||||
attendee: evt.organizer,
|
||||
renderEmail("VerifyAccountEmail", {
|
||||
language: t,
|
||||
user: {
|
||||
name: "Pro Example",
|
||||
email: "[email protected]",
|
||||
},
|
||||
verificationEmailLink:
|
||||
"http://localhost:3000/api/auth/verify-email?token=b91af0eee5a9a24a8d83a3d3d6a58c1606496e94ced589441649273c66100f5b",
|
||||
})
|
||||
);
|
||||
res.end();
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { MailOpenIcon } from "lucide-react";
|
||||
import { useSession } from "next-auth/react";
|
||||
import { useRouter } from "next/router";
|
||||
import { useEffect } from "react";
|
||||
|
||||
import { APP_NAME } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc";
|
||||
import useEmailVerifyCheck from "@calcom/trpc/react/hooks/useEmailVerifyCheck";
|
||||
import { Button, EmptyScreen, showToast } from "@calcom/ui";
|
||||
|
||||
import PageWrapper from "@components/PageWrapper";
|
||||
|
||||
function VerifyEmailPage() {
|
||||
const { data } = useEmailVerifyCheck();
|
||||
const { data: session } = useSession();
|
||||
const router = useRouter();
|
||||
const { t } = useLocale();
|
||||
const mutation = trpc.viewer.auth.resendVerifyEmail.useMutation();
|
||||
|
||||
useEffect(() => {
|
||||
if (data?.isVerified) {
|
||||
router.replace("/getting-started");
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [data?.isVerified]);
|
||||
|
||||
return (
|
||||
<div className="h-[100vh] w-full ">
|
||||
<div className="flex h-full w-full flex-col items-center justify-center">
|
||||
<div className="max-w-3xl">
|
||||
<EmptyScreen
|
||||
border
|
||||
dashedBorder={false}
|
||||
Icon={MailOpenIcon}
|
||||
headline={t("check_your_email")}
|
||||
description={t("verify_email_page_body", { email: session?.user?.email, appName: APP_NAME })}
|
||||
className="bg-default"
|
||||
buttonRaw={
|
||||
<Button
|
||||
color="minimal"
|
||||
className="underline"
|
||||
loading={mutation.isLoading}
|
||||
onClick={() => {
|
||||
showToast("Send email", "success");
|
||||
mutation.mutate();
|
||||
}}>
|
||||
Resend Email
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default VerifyEmailPage;
|
||||
|
||||
VerifyEmailPage.PageWrapper = PageWrapper;
|
||||
@@ -9,6 +9,7 @@ import { z } from "zod";
|
||||
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
|
||||
import { checkPremiumUsername } from "@calcom/features/ee/common/lib/checkPremiumUsername";
|
||||
import { isSAMLLoginEnabled } from "@calcom/features/ee/sso/lib/saml";
|
||||
import { useFlagMap } from "@calcom/features/flags/context/provider";
|
||||
import { getFeatureFlagMap } from "@calcom/features/flags/server/utils";
|
||||
import { IS_SELF_HOSTED, WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
@@ -29,10 +30,10 @@ type FormValues = {
|
||||
};
|
||||
|
||||
export default function Signup({ prepopulateFormValues, token }: inferSSRProps<typeof getServerSideProps>) {
|
||||
const { t } = useLocale();
|
||||
const { t, i18n } = useLocale();
|
||||
const router = useRouter();
|
||||
const flags = useFlagMap();
|
||||
const telemetry = useTelemetry();
|
||||
|
||||
const methods = useForm<FormValues>({
|
||||
defaultValues: prepopulateFormValues,
|
||||
});
|
||||
@@ -52,6 +53,7 @@ export default function Signup({ prepopulateFormValues, token }: inferSSRProps<t
|
||||
await fetch("/api/auth/signup", {
|
||||
body: JSON.stringify({
|
||||
...data,
|
||||
language: i18n.language,
|
||||
}),
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
@@ -61,11 +63,12 @@ export default function Signup({ prepopulateFormValues, token }: inferSSRProps<t
|
||||
.then(handleErrors)
|
||||
.then(async () => {
|
||||
telemetry.event(telemetryEventTypes.signup, collectPageParameters());
|
||||
const verifyOrGettingStarted = flags["email-verification"] ? "auth/verify-email" : "getting-started";
|
||||
await signIn<"credentials">("credentials", {
|
||||
...data,
|
||||
callbackUrl: router.query.callbackUrl
|
||||
? `${WEBAPP_URL}/${router.query.callbackUrl}`
|
||||
: `${WEBAPP_URL}/getting-started`,
|
||||
: `${WEBAPP_URL}/${verifyOrGettingStarted}`,
|
||||
});
|
||||
})
|
||||
.catch((err) => {
|
||||
|
||||
@@ -11,6 +11,16 @@
|
||||
"calcom_explained_new_user": "Finish setting up your {{appName}} account! You’re just a few steps away from solving all your scheduling problems.",
|
||||
"have_any_questions": "Have questions? We're here to help.",
|
||||
"reset_password_subject": "{{appName}}: Reset password instructions",
|
||||
"verify_email_subject": "{{appName}}: Verify your account",
|
||||
"check_your_email": "Check your email",
|
||||
"verify_email_page_body": "We've sent an email to {{email}}. It is important to verify your email address to guarantee the best email and calendar deliverability from {{appName}}.",
|
||||
"verify_email_banner_body": "Please verify your email adress to guarantee the best email and calendar deliverability from {{appName}}.",
|
||||
"verify_email_banner_button": "Send email",
|
||||
"verify_email_email_header": "Verify your email address",
|
||||
"verify_email_email_button": "Verify email",
|
||||
"verify_email_email_body": "Please verify your email address by clicking the button below.",
|
||||
"verify_email_email_link_text": "Here's the link incase you don't like clicking buttons:",
|
||||
"email_sent": "Email sent successfully",
|
||||
"event_declined_subject": "Declined: {{title}} at {{date}}",
|
||||
"event_cancelled_subject": "Cancelled: {{title}} at {{date}}",
|
||||
"event_request_declined": "Your event request has been declined",
|
||||
|
||||
Reference in new issue
Block a user