Feature: Verify login on signup with magic link. (#2122)

* manual migration to rename verificationtoken, maybe it could be dropped and create a new table instead if we're not using it, will consult @zomars

* feat: rename verificationRequest --> verificationToken in schema.prisma

* fix: rename verificationRequest -> verificationToken in the codebase

* feat: add default cookies for next-auth

* fix: moves @lib/serverConfig to @calcom/lib so it can be called by website too

* fix: make self-certificate work in dev env by not rejecting tls in serverConfig

* fix verificationTokenToken typo

Co-authored-by: Omar López <[email protected]>

* Adds domain: .cal.com if not dev env in cookies

* Adds default-cookies to apps/web, and nextauth_domain to turbo website build deps"a

* update NEXTAUTH_DOMAIN to NEXTAUTH_COOKIE_DOMAIN

* Updates website submodule

* Removes deprecated env vars

* Consolidates auth logic in one place

* Updates website module

* Signup fixes

* Build fixes

* Updates example

* Updates example

* Fixes

* Fix Email Verification

* fix: move csrf-token cookiePrefix from __Host -> __Secure

* Removes console log

* Fixes link in email template

* Removed irrelevant coment

* Testing with a 32 bit secret

* Fixes for cookien in E2E

* E2E fixes

* Fixes Stripe tests locally

* Temp fix for E2E

Co-authored-by: Agusti Fernandez Pardo <[email protected]>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
Co-authored-by: Omar López <[email protected]>
Co-authored-by: Hariom Balhara <[email protected]>
This commit is contained in:
authored and GitHub committed 2022-04-21 14:32:25 -06:00
1 parent 97e4cca252
commit 8bc5a75249
30 files changed
+957 -52

No files matched your search

+1 -1
View File
@@ -69,7 +69,7 @@ function useRedirectToLoginIfUnauthenticated(isPublic = false) {
router.replace({
pathname: "/auth/login",
query: {
callbackUrl: `${WEBAPP_URL}/${location.pathname}${location.search}`,
callbackUrl: `${WEBAPP_URL}${location.pathname}${location.search}`,
},
});
}
@@ -9,10 +9,9 @@ import nodemailer from "nodemailer";
import { getAppName } from "@calcom/app-store/utils";
import { getCancelLink, getRichDescription } from "@calcom/lib/CalEventParser";
import { getErrorFromUnknown } from "@calcom/lib/errors";
import { serverConfig } from "@calcom/lib/serverConfig";
import type { Person, CalendarEvent } from "@calcom/types/Calendar";
import { serverConfig } from "@lib/serverConfig";
import {
emailHead,
emailSchedulingBodyHeader,
@@ -0,0 +1,573 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!-- <head> -->
<title>${headerContent}</title>
<!--[if !mso]><!-->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!--<![endif]-->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--[if mso]>
<noscript>
<xml>
<o:OfficeDocumentSettings>
<o:AllowPNG/>
<o:PixelsPerInch>96</o:PixelsPerInch>
</o:OfficeDocumentSettings>
</xml>
</noscript>
<![endif]-->
<!--[if lte mso 11]>
<style type="text/css">
.mj-outlook-group-fix { width:100% !important; }
</style>
<![endif]-->
<!--[if !mso]><!-->
<link href="https://fonts.googleapis.com/css?family=Roboto:400,500,700" rel="stylesheet" type="text/css">
<style type="text/css">
@import url(https://fonts.googleapis.com/css?family=Roboto:400,500,700);
</style>
<!--<![endif]-->
<style type="text/css">
@media only screen and (min-width:480px) {
.mj-column-per-100 {
width: 100% !important;
max-width: 100%;
}
}
</style>
<style media="screen and (min-width:480px)">
.moz-text-html .mj-column-per-100 {
width: 100% !important;
max-width: 100%;
}
</style>
<style type="text/css">
@media only screen and (max-width:480px) {
table.mj-full-width-mobile {
width: 100% !important;
}
td.mj-full-width-mobile {
width: auto !important;
}
}
</style>
<!-- </head> -->
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="x-apple-disable-message-reformatting" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="color-scheme" content="light dark" />
<meta name="supported-color-schemes" content="light dark" />
<title></title>
<style type="text/css" rel="stylesheet" media="all">
/* Base ------------------------------ */
@import url('https://fonts.googleapis.com/css?family=Inter:400,700&display=swap');
#outlook a {
padding: 0;
}
body {
width: 100% !important;
height: 100%;
-webkit-text-size-adjust: none;
margin: 0;
padding: 0;
-webkit-text-size-adjust: 100%;
-ms-text-size-adjust: 100%;
}
table,
td {
border-collapse: collapse;
mso-table-lspace: 0pt;
mso-table-rspace: 0pt;
word-break: break-word;
}
img {
border: 0;
height: auto;
line-height: 100%;
outline: none;
text-decoration: none;
-ms-interpolation-mode: bicubic;
}
p {
display: block;
margin: 13px 0;
}
a {
color: #3b82f6;
}
a img {
border: none;
}
.preheader {
display: none !important;
visibility: hidden;
mso-hide: all;
font-size: 1px;
line-height: 1px;
max-height: 0;
max-width: 0;
opacity: 0;
overflow: hidden;
}
/* Type ------------------------------ */
body,
td,
th {
font-family: 'Roboto', Helvetica, Arial, sans-serif;
}
h1 {
margin-top: 0;
color: #333333;
font-size: 22px;
font-weight: bold;
text-align: left;
}
h2 {
margin-top: 0;
color: #333333;
font-size: 16px;
font-weight: bold;
text-align: left;
}
h3 {
margin-top: 0;
color: #333333;
font-size: 14px;
font-weight: bold;
text-align: left;
}
td,
th {
font-size: 16px;
}
p,
ul,
ol,
blockquote {
margin: 0.4em 0 1.1875em;
font-size: 16px;
line-height: 1.625;
}
p.sub {
font-size: 13px;
}
/* Utilities ------------------------------ */
.align-right {
text-align: right;
}
.align-left {
text-align: left;
}
.align-center {
text-align: center;
}
/* Buttons ------------------------------ */
.button {
background-color: #000;
border-top: 10px solid #000;
border-right: 18px solid #000;
border-bottom: 10px solid #000;
border-left: 18px solid #000;
display: inline-block;
color: #fff !important;
text-decoration: none;
border-radius: 0;
/* box-shadow: 0 2px 3px rgba(0, 0, 0, 0.16); */
-webkit-text-size-adjust: none;
box-sizing: border-box;
}
@media only screen and (max-width: 500px) {
.button {
width: 100% !important;
text-align: center !important;
}
}
/* Attribute list ------------------------------ */
.attributes {
margin: 0 0 21px;
}
.attributes_content {
background-color: #f4f4f7;
padding: 16px;
}
.attributes_item {
padding: 0;
}
/* Related Items ------------------------------ */
.related {
width: 100%;
margin: 0;
padding: 25px 0 0 0;
-premailer-width: 100%;
-premailer-cellpadding: 0;
-premailer-cellspacing: 0;
}
.related_item {
padding: 10px 0;
color: #cbcccf;
font-size: 15px;
line-height: 18px;
}
.related_item-title {
display: block;
margin: 0.5em 0 0;
}
.related_item-thumb {
display: block;
padding-bottom: 10px;
}
.related_heading {
border-top: 1px solid #cbcccf;
text-align: center;
padding: 25px 0 10px;
}
/* Data table ------------------------------ */
body {
background-color: #f2f4f6;
color: #51545e;
}
p {
color: #51545e;
}
.email-wrapper {
width: 100%;
margin: 0;
padding: 0;
-premailer-width: 100%;
-premailer-cellpadding: 0;
-premailer-cellspacing: 0;
background-color: #f2f4f6;
}
.email-content {
width: 100%;
margin: 0;
padding: 0;
-premailer-width: 100%;
-premailer-cellpadding: 0;
-premailer-cellspacing: 0;
}
/* Masthead ----------------------- */
.email-masthead {
padding: 25px 0;
text-align: center;
}
.email-masthead_logo {
width: 94px;
}
.email-masthead_name {
font-size: 16px;
font-weight: bold;
color: #a8aaaf;
text-decoration: none;
text-shadow: 0 1px 0 white;
}
/* Body ------------------------------ */
.email-body {
width: 100%;
margin: 0;
padding: 0;
-premailer-width: 100%;
-premailer-cellpadding: 0;
-premailer-cellspacing: 0;
}
.email-body_inner {
width: 570px;
margin: 0 auto;
padding: 0;
-premailer-width: 570px;
-premailer-cellpadding: 0;
-premailer-cellspacing: 0;
background-color: #ffffff;
}
.email-footer {
width: 570px;
margin: 0 auto;
padding: 0;
-premailer-width: 570px;
-premailer-cellpadding: 0;
-premailer-cellspacing: 0;
text-align: center;
}
.email-footer p {
color: #a8aaaf;
}
.body-action {
width: 100%;
margin: 30px auto;
padding: 0;
-premailer-width: 100%;
-premailer-cellpadding: 0;
-premailer-cellspacing: 0;
text-align: center;
}
.body-sub {
margin-top: 25px;
padding-top: 25px;
border-top: 1px solid #eaeaec;
}
.content-cell {
padding: 45px;
}
/*Media Queries ------------------------------ */
@media only screen and (max-width: 600px) {
.email-body_inner,
.email-footer {
width: 100% !important;
}
}
@media (prefers-color-scheme: dark) {
body,
.email-body,
.email-body_inner,
.email-content,
.email-wrapper,
.email-masthead,
.email-footer {
background-color: #333333 !important;
color: #fff !important;
}
p,
ul,
ol,
blockquote,
h1,
h2,
h3,
span,
.purchase_item {
color: #fff !important;
}
.attributes_content {
background-color: #222 !important;
}
.email-masthead_name {
text-shadow: none !important;
}
}
:root {
color-scheme: light dark;
supported-color-schemes: light dark;
}
</style>
<!--[if mso]>
<style type="text/css">
.f-fallback {
font-family: Arial, sans-serif;
}
</style>
<![endif]-->
</head>
<body>
<span class="preheader">This link will expire in 10 min.</span>
<table
class="email-wrapper"
width="100%"
cellpadding="0"
cellspacing="0"
role="presentation"
>
<tr>
<td align="center">
<table
class="email-content"
width="100%"
cellpadding="0"
cellspacing="0"
role="presentation"
>
<!-- <tr>
<td class="email-masthead">
<a href="{{base_url}}" class="f-fallback email-masthead_name">
Cal.com
</a>
</td>
</tr> -->
<!--[if mso | IE]></td></tr></table><table align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600" ><tr><td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;"><![endif]-->
<div style="margin:0px auto;max-width:600px;">
<table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">
<tbody>
<tr>
<td style="direction:ltr;font-size:0px;padding:0px;text-align:center;">
<!--[if mso | IE]><table role="presentation" border="0" cellpadding="0" cellspacing="0"><tr><td class="" style="vertical-align:top;width:600px;" ><![endif]-->
<div class="mj-column-per-100 mj-outlook-group-fix" style="font-size:0px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;">
<table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:top;" width="100%">
<tbody>
<tr>
<td align="center" style="font-size:0px;padding:10px 25px;padding-top:32px;word-break:break-word;">
<table border="0" cellpadding="0" cellspacing="0" role="presentation" style="border-collapse:collapse;border-spacing:0px;">
<tbody>
<tr>
<td style="width:89px;">
<a href="{{base_url}}" target="_blank">
<img height="19" src="https://app.cal.com/emails/[email protected]" style="border:0;display:block;outline:none;text-decoration:none;height:19px;width:100%;font-size:13px;" width="89" />
</a>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
<!--[if mso | IE]></td></tr></table><![endif]-->
</td>
</tr>
</tbody>
</table>
</div>
<!-- Email Body -->
<tr>
<td
class="email-body"
width="570"
cellpadding="0"
cellspacing="0"
>
<table
class="email-body_inner"
align="center"
width="570"
cellpadding="0"
cellspacing="0"
role="presentation"
>
<!-- Body content -->
<tr>
<td class="content-cell">
<div class="f-fallback">
<p>
Click the button below to log in to Cal.com<br />
This link will expire in 10 minutes.
</p>
<!-- Action -->
<table
class="body-action"
align="center"
width="100%"
cellpadding="0"
cellspacing="0"
role="presentation"
>
<tr>
<td align="center">
<!-- Border based button
https://litmus.com/blog/a-guide-to-bulletproof-buttons-in-email-design -->
<table
width="100%"
border="0"
cellspacing="0"
cellpadding="0"
role="presentation"
>
<tr>
<td>
<a
href="{{signin_url}}"
class="f-fallback button"
target="_blank"
>Log into Cal.com</a
>
</td>
</tr>
</table>
</td>
</tr>
</table>
<p>
Confirming this request will securely log you in using
{{email}}.
</p>
<p>Enjoy your new scheduling soultion by,<br />The Cal.com Team</p>
<!-- Sub copy -->
<table class="body-sub" role="presentation">
<tr>
<td>
<p class="f-fallback sub">
If you’re having trouble with the button above,
copy and paste the URL below into your web
browser.
</p>
<p class="f-fallback sub">{{signin_url}}</p>
</td>
</tr>
</table>
</div>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table
class="email-footer"
align="center"
width="570"
cellpadding="0"
cellspacing="0"
role="presentation"
>
<tr>
<td class="content-cell" align="center">
<p class="f-fallback sub align-center">
&copy; 2022 Cal.com. All rights reserved.
</p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
@@ -2,8 +2,7 @@ import { TFunction } from "next-i18next";
import nodemailer from "nodemailer";
import { getErrorFromUnknown } from "@calcom/lib/errors";
import { serverConfig } from "@lib/serverConfig";
import { serverConfig } from "@calcom/lib/serverConfig";
import { emailHead, linkIcon, emailBodyLogo } from "./common";
@@ -9,10 +9,9 @@ import nodemailer from "nodemailer";
import { getAppName } from "@calcom/app-store/utils";
import { getCancelLink, getRichDescription } from "@calcom/lib/CalEventParser";
import { getErrorFromUnknown } from "@calcom/lib/errors";
import { serverConfig } from "@calcom/lib/serverConfig";
import type { CalendarEvent } from "@calcom/types/Calendar";
import { serverConfig } from "@lib/serverConfig";
import {
emailHead,
emailSchedulingBodyHeader,
@@ -2,8 +2,7 @@ import { TFunction } from "next-i18next";
import nodemailer from "nodemailer";
import { getErrorFromUnknown } from "@calcom/lib/errors";
import { serverConfig } from "@lib/serverConfig";
import { serverConfig } from "@calcom/lib/serverConfig";
import { emailHead, linkIcon, emailBodyLogo } from "./common";
-34
View File
@@ -1,34 +0,0 @@
import SendmailTransport from "nodemailer/lib/sendmail-transport";
import SMTPConnection from "nodemailer/lib/smtp-connection";
function detectTransport(): SendmailTransport.Options | SMTPConnection.Options | string {
if (process.env.EMAIL_SERVER) {
return process.env.EMAIL_SERVER;
}
if (process.env.EMAIL_SERVER_HOST) {
const port = parseInt(process.env.EMAIL_SERVER_PORT!);
const transport = {
host: process.env.EMAIL_SERVER_HOST,
port,
auth: {
user: process.env.EMAIL_SERVER_USER,
pass: process.env.EMAIL_SERVER_PASSWORD,
},
secure: port === 465,
};
return transport;
}
return {
sendmail: true,
newline: "unix",
path: "/usr/sbin/sendmail",
};
}
export const serverConfig = {
transport: detectTransport(),
from: process.env.EMAIL_FROM,
};
+3 -2
View File
@@ -37,11 +37,12 @@
"@calcom/ui": "*",
"@daily-co/daily-js": "^0.21.0",
"@glidejs/glide": "^3.5.2",
"@heroicons/react": "^1.0.5",
"@heroicons/react": "^1.0.6",
"@hookform/error-message": "^2.0.0",
"@hookform/resolvers": "^2.8.5",
"@jitsu/sdk-js": "^2.2.4",
"@metamask/providers": "^8.1.1",
"@next-auth/prisma-adapter": "^1.0.3",
"@next/bundle-analyzer": "12.1.0",
"@radix-ui/react-avatar": "^0.1.0",
"@radix-ui/react-collapsible": "^0.1.0",
@@ -76,7 +77,7 @@
"micro": "^9.3.4",
"mime-types": "^2.1.35",
"next": "^12.1.0",
"next-auth": "^4.0.6",
"next-auth": "^4.3.3",
"next-i18next": "^8.9.0",
"next-mdx-remote": "^4.0.2",
"next-seo": "^4.26.0",
+55 -3
View File
@@ -1,20 +1,33 @@
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { IdentityProvider } from "@prisma/client";
import { readFileSync } from "fs";
import Handlebars from "handlebars";
import NextAuth, { Session } from "next-auth";
import { Provider } from "next-auth/providers";
import CredentialsProvider from "next-auth/providers/credentials";
import EmailProvider from "next-auth/providers/email";
import GoogleProvider from "next-auth/providers/google";
import nodemailer, { TransportOptions } from "nodemailer";
import { authenticator } from "otplib";
import path from "path";
import { WEBSITE_URL } from "@calcom/lib/constants";
import { symmetricDecrypt } from "@calcom/lib/crypto";
import { defaultCookies } from "@calcom/lib/default-cookies";
import { serverConfig } from "@calcom/lib/serverConfig";
import { ErrorCode, verifyPassword } from "@lib/auth";
import prisma from "@lib/prisma";
import { randomString } from "@lib/random";
import { isSAMLLoginEnabled, samlLoginUrl, hostedCal } from "@lib/saml";
import { hostedCal, isSAMLLoginEnabled, samlLoginUrl } from "@lib/saml";
import slugify from "@lib/slugify";
import { GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, IS_GOOGLE_LOGIN_ENABLED } from "@server/lib/constants";
const transporter = nodemailer.createTransport<TransportOptions>({
...(serverConfig.transport as TransportOptions),
} as TransportOptions);
const usernameSlug = (username: string) => slugify(username) + "-" + randomString(6).toLowerCase();
const providers: Provider[] = [
@@ -141,15 +154,50 @@ if (isSAMLLoginEnabled) {
});
}
if (true) {
const emailsDir = path.resolve(process.cwd(), "lib", "emails", "templates");
providers.push(
EmailProvider({
maxAge: 10 * 60 * 60, // Magic links are valid for 10 min only
// Here we setup the sendVerificationRequest that calls the email template with the identifier (email) and token to verify.
sendVerificationRequest: ({ identifier, url }) => {
// Here we add /new endpoint to the callback URL by adding it before &token=.
// This is not elegant but it works. We should probably use a different approach when we can.
url = url.includes("/auth/new") ? url : url.replace("&token", "/auth/new&token");
const emailFile = readFileSync(path.join(emailsDir, "confirm-email.html"), {
encoding: "utf8",
});
const emailTemplate = Handlebars.compile(emailFile);
transporter.sendMail({
from: `${process.env.EMAIL_FROM}` || "Cal.com",
to: identifier,
subject: "Your sign-in link for Cal.com",
html: emailTemplate({
base_url: WEBSITE_URL,
signin_url: url,
email: identifier,
}),
});
},
})
);
}
export default NextAuth({
adapter: PrismaAdapter(prisma),
session: {
strategy: "jwt",
},
secret: process.env.JWT_SECRET,
/** @deprecated remove once PR#2122 is merged */
jwt: {
secret: process.env.JWT_SECRET || process.env.NEXTAUTH_SECRET,
},
cookies: defaultCookies(WEBSITE_URL?.startsWith("https://")),
pages: {
signIn: "/auth/login",
signOut: "/auth/logout",
error: "/auth/error", // Error code passed in query string as ?error=
newUser: "/auth/new", // New users will be directed here on first sign in (leave the property out if not of interest)
},
providers,
callbacks: {
@@ -235,7 +283,11 @@ export default NextAuth({
};
return calendsoSession;
},
async signIn({ user, account, profile }) {
async signIn(params) {
const { user, account, profile } = params;
if (account.provider === "email") {
return true;
}
// In this case we've already verified the credentials in the authorize
// callback so we can sign the user in.
if (account.type === "credentials") {
+1 -1
View File
@@ -76,7 +76,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
const token: string = randomBytes(32).toString("hex");
await prisma.verificationRequest.create({
await prisma.verificationToken.create({
data: {
identifier: usernameOrEmail,
token,
+6
View File
@@ -0,0 +1,6 @@
export default function NewUserPage() {
if (typeof window !== "undefined") {
window.location.assign(process.env.NEXT_PUBLIC_WEBAPP_URL || "https://app.cal.com");
}
return null;
}
+5 -5
View File
@@ -153,14 +153,14 @@ export const getServerSideProps = async (ctx: GetServerSidePropsContext) => {
notFound: true,
};
}
const verificationRequest = await prisma.verificationRequest.findUnique({
const verificationToken = await prisma.verificationToken.findUnique({
where: {
token,
},
});
// for now, disable if no verificationRequestToken given or token expired
if (!verificationRequest || verificationRequest.expires < new Date()) {
// for now, disable if no verificationToken given or token expired
if (!verificationToken || verificationToken.expires < new Date()) {
return {
notFound: true,
};
@@ -170,7 +170,7 @@ export const getServerSideProps = async (ctx: GetServerSidePropsContext) => {
where: {
AND: [
{
email: verificationRequest.identifier,
email: verificationToken.identifier,
},
{
emailVerified: {
@@ -194,7 +194,7 @@ export const getServerSideProps = async (ctx: GetServerSidePropsContext) => {
props: {
isGoogleLoginEnabled: IS_GOOGLE_LOGIN_ENABLED,
isSAMLLoginEnabled,
email: verificationRequest.identifier,
email: verificationToken.identifier,
trpcState: ssr.dehydrate(),
},
};
+2 -2
View File
@@ -35,7 +35,7 @@ test.describe("Can signup from a team invite", async () => {
// Wait for the invite to be sent
await page.waitForSelector(`[data-testid="member-email"][data-email="${testUser.email}"]`);
const tokenObj = await prisma.verificationRequest.findFirst({
const tokenObj = await prisma.verificationToken.findFirst({
where: { identifier: testUser.email },
select: { token: true },
});
@@ -49,7 +49,7 @@ test.describe("Can signup from a team invite", async () => {
where: { email: testUser.email },
});
// Delete verification request
await prisma.verificationRequest.delete({
await prisma.verificationToken.delete({
where: { token },
});
});
+1 -1
View File
@@ -247,7 +247,7 @@ export const viewerTeamsRouter = createProtectedRouter()
const token: string = randomBytes(32).toString("hex");
await ctx.prisma.verificationRequest.create({
await ctx.prisma.verificationToken.create({
data: {
identifier: input.usernameOrEmail,
token,