feat: Implement secondary email (#13678)
* Implement secondary email * Fix already existing tests failing * Added tests for secondary email feature * Skip email verification if user is changing the primary email to a verified secondary email * Fix type errors in tests * Fix email becoming unverified when switched between primary and secondary email * Added a check to prevent prisma error from throwing up due to duplicate records * Improved error handling when adding a secondary email * Add test for resend verification email flow for secondary emails and validation of invite link * Add a new column to link secondary emails with verification tokens * Fix failing to update email to an unverified secondary email of the same user * Fix failing tests * Change text of resend verification email * Add ability to use the verified secondary emails to get the event details to * Fix type errors * Fix failing e2e tests * Fix failing unit tests * Fix failing type checks * Fix secondary verification email subject * Fix failing e2e tests --------- Co-authored-by: Joe Au-Yeung <[email protected]> Co-authored-by: Peer Richelsen <[email protected]>
This commit is contained in:
36 files changed
+1160
-73
No files matched your search
@@ -2,7 +2,7 @@
|
||||
"name": "ICS Feed",
|
||||
"title": "ICS Feed",
|
||||
"slug": "ics-feed",
|
||||
"dirName":"ics-feedcalendar",
|
||||
"dirName": "ics-feedcalendar",
|
||||
"type": "ics-feed_calendar",
|
||||
"logo": "icon.svg",
|
||||
"variant": "calendar",
|
||||
|
||||
@@ -12,6 +12,7 @@ export type EmailVerifyLink = {
|
||||
email: string;
|
||||
};
|
||||
verificationEmailLink: string;
|
||||
isSecondaryEmailVerification?: boolean;
|
||||
};
|
||||
|
||||
export default class AccountVerifyEmail extends BaseEmail {
|
||||
@@ -24,10 +25,13 @@ export default class AccountVerifyEmail extends BaseEmail {
|
||||
}
|
||||
|
||||
protected async getNodeMailerPayload(): Promise<Record<string, unknown>> {
|
||||
const emailSubjectKey = this.verifyAccountInput.isSecondaryEmailVerification
|
||||
? "verify_email_email_header"
|
||||
: "verify_email_subject";
|
||||
return {
|
||||
to: `${this.verifyAccountInput.user.name} <${this.verifyAccountInput.user.email}>`,
|
||||
from: `${APP_NAME} <${this.getMailerOptions().from}>`,
|
||||
subject: this.verifyAccountInput.language("verify_email_subject", {
|
||||
subject: this.verifyAccountInput.language(emailSubjectKey, {
|
||||
appName: APP_NAME,
|
||||
}),
|
||||
html: await renderEmail("VerifyAccountEmail", this.verifyAccountInput),
|
||||
|
||||
@@ -19,9 +19,15 @@ interface VerifyEmailType {
|
||||
username?: string;
|
||||
email: string;
|
||||
language?: string;
|
||||
secondaryEmailId?: number;
|
||||
}
|
||||
|
||||
export const sendEmailVerification = async ({ email, language, username }: VerifyEmailType) => {
|
||||
export const sendEmailVerification = async ({
|
||||
email,
|
||||
language,
|
||||
username,
|
||||
secondaryEmailId,
|
||||
}: VerifyEmailType) => {
|
||||
const token = randomBytes(32).toString("hex");
|
||||
const translation = await getTranslation(language ?? "en", "common");
|
||||
const emailVerification = await getFeatureFlag(prisma, "email-verification");
|
||||
@@ -41,6 +47,7 @@ export const sendEmailVerification = async ({ email, language, username }: Verif
|
||||
identifier: email,
|
||||
token,
|
||||
expires: new Date(Date.now() + 24 * 3600 * 1000), // +1 day
|
||||
secondaryEmailId: secondaryEmailId || null,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -55,6 +62,7 @@ export const sendEmailVerification = async ({ email, language, username }: Verif
|
||||
email,
|
||||
name: username,
|
||||
},
|
||||
isSecondaryEmailVerification: !!secondaryEmailId,
|
||||
});
|
||||
|
||||
return { ok: true, skipped: false };
|
||||
|
||||
@@ -251,6 +251,13 @@ export const getEventTypesFromDB = async (eventTypeId: number) => {
|
||||
days: true,
|
||||
},
|
||||
},
|
||||
secondaryEmailId: true,
|
||||
secondaryEmail: {
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1452,6 +1459,13 @@ async function handler(
|
||||
? [organizerUser.destinationCalendar]
|
||||
: null;
|
||||
|
||||
let organizerEmail = organizerUser.email || "Email-less";
|
||||
if (eventType.useEventTypeDestinationCalendarEmail && destinationCalendar?.[0]?.primaryEmail) {
|
||||
organizerEmail = destinationCalendar[0].primaryEmail;
|
||||
} else if (eventType.secondaryEmailId && eventType.secondaryEmail?.email) {
|
||||
organizerEmail = eventType.secondaryEmail.email;
|
||||
}
|
||||
|
||||
let evt: CalendarEvent = {
|
||||
bookerUrl,
|
||||
type: eventType.slug,
|
||||
@@ -1464,10 +1478,7 @@ async function handler(
|
||||
organizer: {
|
||||
id: organizerUser.id,
|
||||
name: organizerUser.name || "Nameless",
|
||||
email:
|
||||
eventType.useEventTypeDestinationCalendarEmail && destinationCalendar?.[0]?.primaryEmail
|
||||
? destinationCalendar[0].primaryEmail
|
||||
: organizerUser.email || "Email-less",
|
||||
email: organizerEmail,
|
||||
username: organizerUser.username || undefined,
|
||||
timeZone: organizerUser.timeZone,
|
||||
language: { translate: tOrganizer, locale: organizerUser.locale ?? "en" },
|
||||
|
||||
@@ -102,6 +102,8 @@ const commons = {
|
||||
bookingFields: [],
|
||||
assignAllTeamMembers: false,
|
||||
useEventTypeDestinationCalendarEmail: false,
|
||||
secondaryEmailId: null,
|
||||
secondaryEmail: null,
|
||||
};
|
||||
|
||||
const dynamicEvent = {
|
||||
|
||||
@@ -235,6 +235,7 @@ export default async function getEventTypeById({
|
||||
},
|
||||
},
|
||||
},
|
||||
secondaryEmailId: true,
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -117,6 +117,7 @@ export const buildEventType = (eventType?: Partial<EventType>): EventType => {
|
||||
bookingFields: [],
|
||||
parentId: null,
|
||||
profileId: null,
|
||||
secondaryEmailId: null,
|
||||
...eventType,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "SecondaryEmail" (
|
||||
"id" SERIAL NOT NULL,
|
||||
"userId" INTEGER NOT NULL,
|
||||
"email" TEXT NOT NULL,
|
||||
"emailVerified" TIMESTAMP(3),
|
||||
|
||||
CONSTRAINT "SecondaryEmail_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "SecondaryEmail_userId_idx" ON "SecondaryEmail"("userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "SecondaryEmail_email_key" ON "SecondaryEmail"("email");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "SecondaryEmail_userId_email_key" ON "SecondaryEmail"("userId", "email");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "SecondaryEmail" ADD CONSTRAINT "SecondaryEmail_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "VerificationToken" ADD COLUMN "secondaryEmailId" INTEGER;
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "VerificationToken_secondaryEmailId_idx" ON "VerificationToken"("secondaryEmailId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "VerificationToken" ADD CONSTRAINT "VerificationToken_secondaryEmailId_fkey" FOREIGN KEY ("secondaryEmailId") REFERENCES "SecondaryEmail"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "EventType" ADD COLUMN "secondaryEmailId" INTEGER;
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "EventType_secondaryEmailId_idx" ON "EventType"("secondaryEmailId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "EventType" ADD CONSTRAINT "EventType_secondaryEmailId_fkey" FOREIGN KEY ("secondaryEmailId") REFERENCES "SecondaryEmail"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -128,12 +128,16 @@ model EventType {
|
||||
assignAllTeamMembers Boolean @default(false)
|
||||
useEventTypeDestinationCalendarEmail Boolean @default(false)
|
||||
|
||||
secondaryEmailId Int?
|
||||
secondaryEmail SecondaryEmail? @relation(fields: [secondaryEmailId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([userId, slug])
|
||||
@@unique([teamId, slug])
|
||||
@@unique([userId, parentId])
|
||||
@@index([userId])
|
||||
@@index([teamId])
|
||||
@@index([scheduleId])
|
||||
@@index([secondaryEmailId])
|
||||
}
|
||||
|
||||
model Credential {
|
||||
@@ -281,10 +285,11 @@ model User {
|
||||
bookingRedirectsTo OutOfOfficeEntry[] @relation(name: "toUser")
|
||||
|
||||
// Used to lock the user account
|
||||
locked Boolean @default(false)
|
||||
locked Boolean @default(false)
|
||||
profiles Profile[]
|
||||
movedToProfileId Int?
|
||||
movedToProfile Profile? @relation("moved_to_profile", fields: [movedToProfileId], references: [id], onDelete: SetNull)
|
||||
movedToProfile Profile? @relation("moved_to_profile", fields: [movedToProfileId], references: [id], onDelete: SetNull)
|
||||
secondaryEmails SecondaryEmail[]
|
||||
|
||||
@@unique([email])
|
||||
@@unique([email, username])
|
||||
@@ -396,19 +401,22 @@ model Membership {
|
||||
}
|
||||
|
||||
model VerificationToken {
|
||||
id Int @id @default(autoincrement())
|
||||
identifier String
|
||||
token String @unique
|
||||
expires DateTime
|
||||
expiresInDays Int?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
teamId Int?
|
||||
team Team? @relation(fields: [teamId], references: [id])
|
||||
id Int @id @default(autoincrement())
|
||||
identifier String
|
||||
token String @unique
|
||||
expires DateTime
|
||||
expiresInDays Int?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
teamId Int?
|
||||
team Team? @relation(fields: [teamId], references: [id])
|
||||
secondaryEmailId Int?
|
||||
secondaryEmail SecondaryEmail? @relation(fields: [secondaryEmailId], references: [id])
|
||||
|
||||
@@unique([identifier, token])
|
||||
@@index([token])
|
||||
@@index([teamId])
|
||||
@@index([secondaryEmailId])
|
||||
}
|
||||
|
||||
model InstantMeetingToken {
|
||||
@@ -1135,3 +1143,17 @@ model OutOfOfficeEntry {
|
||||
@@index([toUserId])
|
||||
@@index([start, end])
|
||||
}
|
||||
|
||||
model SecondaryEmail {
|
||||
id Int @id @default(autoincrement())
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
userId Int
|
||||
email String
|
||||
emailVerified DateTime?
|
||||
verificationTokens VerificationToken[]
|
||||
eventTypes EventType[]
|
||||
|
||||
@@unique([email])
|
||||
@@unique([userId, email])
|
||||
@@index([userId])
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import authedProcedure from "../../procedures/authedProcedure";
|
||||
import { router } from "../../trpc";
|
||||
import { ZAddSecondaryEmailInputSchema } from "./addSecondaryEmail.schema";
|
||||
import { ZAppByIdInputSchema } from "./appById.schema";
|
||||
import { ZAppCredentialsByTypeInputSchema } from "./appCredentialsByType.schema";
|
||||
import { ZAwayInputSchema } from "./away.schema";
|
||||
@@ -53,6 +54,7 @@ type AppsRouterHandlerCache = {
|
||||
outOfOfficeCreate?: typeof import("./outOfOffice.handler").outOfOfficeCreate;
|
||||
outOfOfficeEntriesList?: typeof import("./outOfOffice.handler").outOfOfficeEntriesList;
|
||||
outOfOfficeEntryDelete?: typeof import("./outOfOffice.handler").outOfOfficeEntryDelete;
|
||||
addSecondaryEmail?: typeof import("./addSecondaryEmail.handler").addSecondaryEmailHandler;
|
||||
};
|
||||
|
||||
const UNSTABLE_HANDLER_CACHE: AppsRouterHandlerCache = {};
|
||||
@@ -468,4 +470,18 @@ export const loggedInViewerRouter = router({
|
||||
|
||||
return UNSTABLE_HANDLER_CACHE.outOfOfficeEntryDelete({ ctx, input });
|
||||
}),
|
||||
addSecondaryEmail: authedProcedure.input(ZAddSecondaryEmailInputSchema).mutation(async ({ ctx, input }) => {
|
||||
if (!UNSTABLE_HANDLER_CACHE.addSecondaryEmail) {
|
||||
UNSTABLE_HANDLER_CACHE.addSecondaryEmail = (
|
||||
await import("./addSecondaryEmail.handler")
|
||||
).addSecondaryEmailHandler;
|
||||
}
|
||||
|
||||
// Unreachable code but required for type safety
|
||||
if (!UNSTABLE_HANDLER_CACHE.addSecondaryEmail) {
|
||||
throw new Error("Failed to load handler");
|
||||
}
|
||||
|
||||
return UNSTABLE_HANDLER_CACHE.addSecondaryEmail({ ctx, input });
|
||||
}),
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
import type { GetServerSidePropsContext, NextApiResponse } from "next";
|
||||
|
||||
import { sendEmailVerification } from "@calcom/features/auth/lib/verifyEmail";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import type { TAddSecondaryEmailInputSchema } from "./addSecondaryEmail.schema";
|
||||
|
||||
type AddSecondaryEmailOptions = {
|
||||
ctx: {
|
||||
user: NonNullable<TrpcSessionUser>;
|
||||
res?: NextApiResponse | GetServerSidePropsContext["res"];
|
||||
};
|
||||
input: TAddSecondaryEmailInputSchema;
|
||||
};
|
||||
|
||||
export const addSecondaryEmailHandler = async ({ ctx, input }: AddSecondaryEmailOptions) => {
|
||||
const { user } = ctx;
|
||||
|
||||
const existingPrimaryEmail = await prisma.user.findUnique({
|
||||
where: {
|
||||
email: input.email,
|
||||
},
|
||||
});
|
||||
|
||||
if (existingPrimaryEmail) {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Email already taken" });
|
||||
}
|
||||
|
||||
const existingSecondaryEmail = await prisma.secondaryEmail.findUnique({
|
||||
where: {
|
||||
email: input.email,
|
||||
},
|
||||
});
|
||||
|
||||
if (existingSecondaryEmail) {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Email already taken" });
|
||||
}
|
||||
|
||||
const updatedData = await prisma.secondaryEmail.create({
|
||||
data: { ...input, userId: user.id },
|
||||
});
|
||||
|
||||
await sendEmailVerification({
|
||||
email: updatedData.email,
|
||||
username: user?.username ?? undefined,
|
||||
language: user.locale,
|
||||
secondaryEmailId: updatedData.id,
|
||||
});
|
||||
|
||||
return {
|
||||
data: updatedData,
|
||||
message: "Secondary email added successfully",
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,7 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const ZAddSecondaryEmailInputSchema = z.object({
|
||||
email: z.string(),
|
||||
});
|
||||
|
||||
export type TAddSecondaryEmailInputSchema = z.infer<typeof ZAddSecondaryEmailInputSchema>;
|
||||
@@ -3,6 +3,7 @@ import type { Session } from "next-auth";
|
||||
import { getUserAvatarUrl } from "@calcom/lib/getAvatarUrl";
|
||||
import { ProfileRepository } from "@calcom/lib/server/repository/profile";
|
||||
import { UserRepository } from "@calcom/lib/server/repository/user";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
|
||||
|
||||
type MeOptions = {
|
||||
@@ -26,6 +27,17 @@ export const meHandler = async ({ ctx }: MeOptions) => {
|
||||
upId: session.upId,
|
||||
});
|
||||
|
||||
const secondaryEmails = await prisma.secondaryEmail.findMany({
|
||||
where: {
|
||||
userId: user.id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
emailVerified: true,
|
||||
},
|
||||
});
|
||||
|
||||
// Destructuring here only makes it more illegible
|
||||
// pick only the part we want to expose in the API
|
||||
return {
|
||||
@@ -33,6 +45,7 @@ export const meHandler = async ({ ctx }: MeOptions) => {
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
emailMd5: crypto.createHash("md5").update(user.email).digest("hex"),
|
||||
emailVerified: user.emailVerified,
|
||||
startTime: user.startTime,
|
||||
endTime: user.endTime,
|
||||
bufferTime: user.bufferTime,
|
||||
@@ -66,5 +79,6 @@ export const meHandler = async ({ ctx }: MeOptions) => {
|
||||
username: user.profile?.username ?? user.username ?? null,
|
||||
profile: user.profile ?? null,
|
||||
profiles: allUserEnrichedProfiles,
|
||||
secondaryEmails,
|
||||
};
|
||||
};
|
||||
@@ -1,4 +1,6 @@
|
||||
import { Prisma } from "@prisma/client";
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { keyBy } from "lodash";
|
||||
import type { GetServerSidePropsContext, NextApiResponse } from "next";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
@@ -65,11 +67,15 @@ export const updateProfileHandler = async ({ ctx, input }: UpdateProfileOptions)
|
||||
const locale = input.locale || user.locale;
|
||||
const emailVerification = await getFeatureFlag(prisma, "email-verification");
|
||||
|
||||
const secondaryEmails = input?.secondaryEmails || [];
|
||||
delete input.secondaryEmails;
|
||||
|
||||
const data: Prisma.UserUpdateInput = {
|
||||
...input,
|
||||
// DO NOT OVERWRITE AVATAR.
|
||||
avatar: undefined,
|
||||
metadata: userMetadata,
|
||||
secondaryEmails: undefined,
|
||||
};
|
||||
|
||||
// some actions can invalidate a user session.
|
||||
@@ -135,17 +141,39 @@ export const updateProfileHandler = async ({ ctx, input }: UpdateProfileOptions)
|
||||
hasEmailBeenChanged && user.identityProvider !== IdentityProvider.CAL;
|
||||
const hasEmailChangedOnCalProvider = hasEmailBeenChanged && user.identityProvider === IdentityProvider.CAL;
|
||||
|
||||
let secondaryEmail:
|
||||
| {
|
||||
id: number;
|
||||
emailVerified: Date | null;
|
||||
}
|
||||
| null
|
||||
| undefined;
|
||||
const primaryEmailVerified = user.emailVerified;
|
||||
if (hasEmailBeenChanged) {
|
||||
secondaryEmail = await prisma.secondaryEmail.findUnique({
|
||||
where: {
|
||||
email: input.email,
|
||||
userId: user.id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
emailVerified: true,
|
||||
},
|
||||
});
|
||||
if (emailVerification && hasEmailChangedOnCalProvider) {
|
||||
// Set metadata of the user so we can set it to this updated email once it is confirmed
|
||||
data.metadata = {
|
||||
...userMetadata,
|
||||
emailChangeWaitingForVerification: input.email,
|
||||
};
|
||||
if (secondaryEmail?.emailVerified) {
|
||||
data.emailVerified = secondaryEmail.emailVerified;
|
||||
} else {
|
||||
// Set metadata of the user so we can set it to this updated email once it is confirmed
|
||||
data.metadata = {
|
||||
...userMetadata,
|
||||
emailChangeWaitingForVerification: input.email,
|
||||
};
|
||||
|
||||
// Check to ensure this email isnt in use
|
||||
// Don't include email in the data payload if we need to verify
|
||||
delete data.email;
|
||||
// Check to ensure this email isnt in use
|
||||
// Don't include email in the data payload if we need to verify
|
||||
delete data.email;
|
||||
}
|
||||
} else {
|
||||
log.warn("Profile Update - Email verification is disabled - Skipping");
|
||||
data.emailVerified = null;
|
||||
@@ -266,28 +294,92 @@ export const updateProfileHandler = async ({ ctx, input }: UpdateProfileOptions)
|
||||
}
|
||||
|
||||
if (updatedUser && hasEmailChangedOnCalProvider) {
|
||||
await sendChangeOfEmailVerification({
|
||||
user: {
|
||||
username: updatedUser.username ?? "Nameless User",
|
||||
emailFrom: user.email,
|
||||
// We know email has been changed here so we can use input
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
emailTo: input.email!,
|
||||
},
|
||||
});
|
||||
// Skip sending verification email when user tries to change his primary email to a verified secondary email
|
||||
if (secondaryEmail?.emailVerified) {
|
||||
secondaryEmails.push({
|
||||
id: secondaryEmail.id,
|
||||
email: user.email,
|
||||
isDeleted: false,
|
||||
});
|
||||
} else {
|
||||
await sendChangeOfEmailVerification({
|
||||
user: {
|
||||
username: updatedUser.username ?? "Nameless User",
|
||||
emailFrom: user.email,
|
||||
// We know email has been changed here so we can use input
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
emailTo: input.email!,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// don't return avatar, we don't need it anymore.
|
||||
delete input.avatar;
|
||||
|
||||
if (secondaryEmails.length) {
|
||||
const recordsToDelete = secondaryEmails
|
||||
.filter((secondaryEmail) => secondaryEmail.isDeleted)
|
||||
.map((secondaryEmail) => secondaryEmail.id);
|
||||
if (recordsToDelete.length) {
|
||||
await prisma.secondaryEmail.deleteMany({
|
||||
where: {
|
||||
id: {
|
||||
in: recordsToDelete,
|
||||
},
|
||||
userId: updatedUser.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const modifiedRecords = secondaryEmails.filter((secondaryEmail) => !secondaryEmail.isDeleted);
|
||||
if (modifiedRecords.length) {
|
||||
const secondaryEmailsFromDB = await prisma.secondaryEmail.findMany({
|
||||
where: {
|
||||
id: {
|
||||
in: secondaryEmails.map((secondaryEmail) => secondaryEmail.id),
|
||||
},
|
||||
userId: updatedUser.id,
|
||||
},
|
||||
});
|
||||
|
||||
const keyedSecondaryEmailsFromDB = keyBy(secondaryEmailsFromDB, "id");
|
||||
|
||||
const recordsToModifyQueue = modifiedRecords.map((updated) => {
|
||||
let emailVerified = keyedSecondaryEmailsFromDB[updated.id].emailVerified;
|
||||
if (secondaryEmail?.id === updated.id) {
|
||||
emailVerified = primaryEmailVerified;
|
||||
} else if (updated.email !== keyedSecondaryEmailsFromDB[updated.id].email) {
|
||||
emailVerified = null;
|
||||
}
|
||||
|
||||
return prisma.secondaryEmail.update({
|
||||
where: {
|
||||
id: updated.id,
|
||||
userId: updatedUser.id,
|
||||
},
|
||||
data: {
|
||||
email: updated.email,
|
||||
emailVerified,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
await prisma.$transaction(recordsToModifyQueue);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
...input,
|
||||
email: emailVerification && hasEmailChangedOnCalProvider ? user.email : input.email,
|
||||
email:
|
||||
emailVerification && hasEmailChangedOnCalProvider && !secondaryEmail?.emailVerified
|
||||
? user.email
|
||||
: input.email,
|
||||
signOutUser,
|
||||
passwordReset,
|
||||
avatarUrl: updatedUser.avatarUrl,
|
||||
hasEmailBeenChanged,
|
||||
sendEmailVerification: emailVerification,
|
||||
sendEmailVerification: emailVerification && !secondaryEmail?.emailVerified,
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -29,6 +29,15 @@ export const ZUpdateProfileInputSchema = z.object({
|
||||
timeFormat: z.number().optional(),
|
||||
disableImpersonation: z.boolean().optional(),
|
||||
metadata: userMetadata.optional(),
|
||||
secondaryEmails: z
|
||||
.array(
|
||||
z.object({
|
||||
id: z.number(),
|
||||
email: z.string(),
|
||||
isDeleted: z.boolean().default(false),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export type TUpdateProfileInputSchema = z.infer<typeof ZUpdateProfileInputSchema>;
|
||||
@@ -4,6 +4,7 @@ import authedProcedure from "../../../procedures/authedProcedure";
|
||||
import publicProcedure from "../../../procedures/publicProcedure";
|
||||
import { router } from "../../../trpc";
|
||||
import { ZChangePasswordInputSchema } from "./changePassword.schema";
|
||||
import { ZResendVerifyEmailSchema } from "./resendVerifyEmail.schema";
|
||||
import { ZSendVerifyEmailCodeSchema } from "./sendVerifyEmailCode.schema";
|
||||
import { ZVerifyPasswordInputSchema } from "./verifyPassword.schema";
|
||||
|
||||
@@ -13,6 +14,7 @@ type AuthRouterHandlerCache = {
|
||||
verifyCodeUnAuthenticated?: typeof import("./verifyCodeUnAuthenticated.handler").verifyCodeUnAuthenticatedHandler;
|
||||
resendVerifyEmail?: typeof import("./resendVerifyEmail.handler").resendVerifyEmail;
|
||||
sendVerifyEmailCode?: typeof import("./sendVerifyEmailCode.handler").sendVerifyEmailCodeHandler;
|
||||
resendVerifySecondaryEmail?: typeof import("./resendVerifyEmail.handler").resendVerifyEmail;
|
||||
};
|
||||
|
||||
const UNSTABLE_HANDLER_CACHE: AuthRouterHandlerCache = {};
|
||||
@@ -89,7 +91,7 @@ export const authRouter = router({
|
||||
});
|
||||
}),
|
||||
|
||||
resendVerifyEmail: authedProcedure.mutation(async ({ ctx }) => {
|
||||
resendVerifyEmail: authedProcedure.input(ZResendVerifyEmailSchema).mutation(async ({ input, ctx }) => {
|
||||
if (!UNSTABLE_HANDLER_CACHE.resendVerifyEmail) {
|
||||
UNSTABLE_HANDLER_CACHE.resendVerifyEmail = await import("./resendVerifyEmail.handler").then(
|
||||
(mod) => mod.resendVerifyEmail
|
||||
@@ -101,6 +103,7 @@ export const authRouter = router({
|
||||
}
|
||||
|
||||
return UNSTABLE_HANDLER_CACHE.resendVerifyEmail({
|
||||
input,
|
||||
ctx,
|
||||
});
|
||||
}),
|
||||
|
||||
@@ -1,18 +1,45 @@
|
||||
import { sendEmailVerification } from "@calcom/features/auth/lib/verifyEmail";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import { TRPCError } from "@calcom/trpc/server";
|
||||
|
||||
import type { TrpcSessionUser } from "../../../trpc";
|
||||
import type { TResendVerifyEmailSchema } from "./resendVerifyEmail.schema";
|
||||
|
||||
type ResendEmailOptions = {
|
||||
ctx: {
|
||||
user: NonNullable<TrpcSessionUser>;
|
||||
};
|
||||
input: TResendVerifyEmailSchema;
|
||||
};
|
||||
|
||||
const log = logger.getSubLogger({ prefix: [`[[Auth] `] });
|
||||
|
||||
export const resendVerifyEmail = async ({ ctx }: ResendEmailOptions) => {
|
||||
if (ctx.user.emailVerified) {
|
||||
export const resendVerifyEmail = async ({ input, ctx }: ResendEmailOptions) => {
|
||||
let emailToVerify = ctx.user.email;
|
||||
let emailVerified = Boolean(ctx.user.emailVerified);
|
||||
let secondaryEmail;
|
||||
// If the input which is coming is not the current user's email, it could be a secondary email
|
||||
if (input?.email && input?.email !== ctx.user.email) {
|
||||
secondaryEmail = await prisma.secondaryEmail.findUnique({
|
||||
where: {
|
||||
email: input.email,
|
||||
userId: ctx.user.id,
|
||||
},
|
||||
});
|
||||
|
||||
if (!secondaryEmail) {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Email not found" });
|
||||
}
|
||||
|
||||
if (secondaryEmail.emailVerified) {
|
||||
emailVerified = true;
|
||||
} else {
|
||||
emailToVerify = input.email;
|
||||
emailVerified = false;
|
||||
}
|
||||
}
|
||||
if (emailVerified) {
|
||||
log.info(`User ${ctx.user.id} already verified email`);
|
||||
return {
|
||||
ok: true,
|
||||
@@ -21,9 +48,10 @@ export const resendVerifyEmail = async ({ ctx }: ResendEmailOptions) => {
|
||||
}
|
||||
|
||||
const email = await sendEmailVerification({
|
||||
email: ctx.user.email,
|
||||
email: emailToVerify,
|
||||
username: ctx.user?.username ?? undefined,
|
||||
language: ctx.user.locale,
|
||||
secondaryEmailId: secondaryEmail?.id,
|
||||
});
|
||||
|
||||
return email;
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const ZResendVerifyEmailSchema = z
|
||||
.object({
|
||||
email: z.string().email(),
|
||||
})
|
||||
.optional();
|
||||
|
||||
export type TResendVerifyEmailSchema = z.infer<typeof ZResendVerifyEmailSchema>;
|
||||
@@ -48,6 +48,7 @@ export const updateHandler = async ({ ctx, input }: UpdateOptions) => {
|
||||
userId,
|
||||
bookingFields,
|
||||
offsetStart,
|
||||
secondaryEmailId,
|
||||
...rest
|
||||
} = input;
|
||||
|
||||
@@ -321,6 +322,29 @@ export const updateHandler = async ({ ctx, input }: UpdateOptions) => {
|
||||
|
||||
data.assignAllTeamMembers = assignAllTeamMembers ?? false;
|
||||
|
||||
// Validate the secondary email
|
||||
if (secondaryEmailId) {
|
||||
const secondaryEmail = await ctx.prisma.secondaryEmail.findUnique({
|
||||
where: {
|
||||
id: secondaryEmailId,
|
||||
userId: ctx.user.id,
|
||||
},
|
||||
});
|
||||
// Make sure the secondary email id belongs to the current user and its a verified one
|
||||
if (secondaryEmail && secondaryEmail.emailVerified) {
|
||||
data.secondaryEmail = {
|
||||
connect: {
|
||||
id: secondaryEmailId,
|
||||
},
|
||||
};
|
||||
// Delete the data if the user selected his original email to send the events to, which means the value coming will be -1
|
||||
} else if (secondaryEmailId === -1) {
|
||||
data.secondaryEmail = {
|
||||
disconnect: true,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const updatedEventTypeSelect = Prisma.validator<Prisma.EventTypeSelect>()({
|
||||
slug: true,
|
||||
schedulingType: true,
|
||||
|
||||
@@ -17,6 +17,7 @@ export {
|
||||
export { InputFieldWithSelect } from "./inputs/InputFieldWithSelect";
|
||||
|
||||
export { InputField, Input, TextField } from "./inputs/TextField";
|
||||
export { InputError } from "./inputs/InputError";
|
||||
export { Form } from "./inputs/Form";
|
||||
export { Label } from "./inputs/Label";
|
||||
export { Select, SelectField, SelectWithValidation, getReactSelectProps } from "./select";
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import type { FieldValues } from "react-hook-form";
|
||||
import { useFormContext } from "react-hook-form";
|
||||
|
||||
import { Check, Circle, Info, X } from "../../icon";
|
||||
import { Check, Circle, X } from "../../icon";
|
||||
import { InputError } from "./InputError";
|
||||
|
||||
type hintsOrErrorsProps = {
|
||||
hintErrors?: string[];
|
||||
@@ -74,16 +75,7 @@ export function HintsOrErrors<T extends FieldValues = FieldValues>({
|
||||
|
||||
// errors exist, not custom ones, just show them as is
|
||||
if (fieldErrors) {
|
||||
return (
|
||||
<div
|
||||
data-testid="field-error"
|
||||
className="text-gray mt-2 flex items-center gap-x-2 text-sm text-red-700">
|
||||
<div>
|
||||
<Info className="h-3 w-3" />
|
||||
</div>
|
||||
<p>{fieldErrors.message}</p>
|
||||
</div>
|
||||
);
|
||||
return <InputError message={fieldErrors.message} />;
|
||||
}
|
||||
|
||||
if (!hintErrors) return null;
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Info } from "../../icon";
|
||||
|
||||
type InputErrorProp = {
|
||||
message: string;
|
||||
};
|
||||
|
||||
export const InputError = ({ message }: InputErrorProp) => (
|
||||
<div data-testid="field-error" className="text-gray mt-2 flex items-center gap-x-2 text-sm text-red-700">
|
||||
<div>
|
||||
<Info className="h-3 w-3" />
|
||||
</div>
|
||||
<p>{message}</p>
|
||||
</div>
|
||||
);
|
||||
@@ -66,6 +66,7 @@ export {
|
||||
Stepper,
|
||||
Switch,
|
||||
NumberInput,
|
||||
InputError,
|
||||
} from "./components/form";
|
||||
export type { ITimezone, ITimezoneOption } from "./components/form";
|
||||
export {
|
||||
|
||||
Reference in new issue
Block a user