fix: Add email verification requirement for API v1 and v2 email updates (#24988)
* fix: Add email verification requirement for API v1 and v2 email updates
- API v2 (/v2/me): Implement email verification check when updating primary email
- Store new email in metadata as emailChangeWaitingForVerification when verification is required
- Send verification email using sendChangeOfEmailVerification
- Allow immediate email change if new email is already a verified secondary email
- Add hasEmailBeenChanged and sendEmailVerification flags to response
- Add tests to verify email verification behavior
- Add findVerifiedSecondaryEmail method to UsersRepository
- Add PrismaFeaturesRepository to MeModule providers
- API v1 (/v1/users/{userId}): Implement same email verification logic
- Check if email-verification feature flag is enabled
- Store new email in metadata when verification is required
- Send verification email for unverified email changes
- Allow immediate change for verified secondary emails
- Preserve existing API v1 response format
- Test fixtures: Add createSecondaryEmail method to UserRepositoryFixture
This fixes the vulnerability where users could update their primary email
without verification via API endpoints.
Co-Authored-By: [email protected] <[email protected]>
* update
* update
* refactor: Extract business logic to MeService and add platform-managed bypass
- Create MeService with all business logic extracted from MeController
- Update MeController to delegate to MeService (thin controller pattern)
- Add PrismaWorkerModule to MeModule imports to provide PrismaWriteService
- Add isPlatformManaged bypass: platform-managed users can update email without verification
- Fix test cleanup to use delete by ID instead of email to avoid failures when email changes
- Remove hasEmailBeenChanged and sendEmailVerification response flags per reviewer feedback
- Add comprehensive documentation to @ApiOperation describing email verification behavior
- Update tests to remove flag assertions
Addresses PR comments:
- supalarry: Extract logic to service layer
- supalarry: Allow platform-managed users to update email without verification
- supalarry: Remove response flags and document behavior in @ApiOperation instead
- cubic-dev-ai: Fix module dependency for PrismaFeaturesRepository
- cubic-dev-ai: Fix test cleanup issue
Co-Authored-By: [email protected] <[email protected]>
* docs: Simplify API operation description
Remove internal implementation details about metadata staging and shorten the description to focus on API consumer behavior.
Co-Authored-By: [email protected] <[email protected]>
* fix
* update
* update
* update
* remove comment
* addressed commit
* review addressed
* use repository
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
9 files changed
+336
-18
No files matched your search
@@ -1,5 +1,8 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { sendChangeOfEmailVerification } from "@calcom/features/auth/lib/verifyEmail";
|
||||
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
|
||||
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { uploadAvatar } from "@calcom/lib/server/avatar";
|
||||
import { defaultResponder } from "@calcom/lib/server/defaultResponder";
|
||||
@@ -130,10 +133,70 @@ export async function patchHandler(req: NextApiRequest) {
|
||||
});
|
||||
}
|
||||
|
||||
const userRepository = new UserRepository(prisma);
|
||||
const currentUser = await userRepository.findById({ id: query.userId });
|
||||
|
||||
if (!currentUser) {
|
||||
throw new HttpError({ statusCode: 404, message: "User not found" });
|
||||
}
|
||||
|
||||
const featuresRepository = new FeaturesRepository(prisma);
|
||||
const emailVerification = await featuresRepository.checkIfFeatureIsEnabledGlobally("email-verification");
|
||||
|
||||
const hasEmailBeenChanged = typeof body.email === "string" && currentUser.email !== body.email;
|
||||
const newEmail = typeof body.email === "string" ? body.email : undefined;
|
||||
|
||||
const prismaData: Prisma.UserUpdateInput = { ...body };
|
||||
|
||||
if (hasEmailBeenChanged && newEmail) {
|
||||
const secondaryEmail = await userRepository.findSecondaryEmailByUserIdAndEmail({
|
||||
userId: query.userId,
|
||||
email: newEmail,
|
||||
});
|
||||
|
||||
if (emailVerification) {
|
||||
if (secondaryEmail && secondaryEmail.emailVerified) {
|
||||
const data = await userRepository.swapPrimaryEmailWithSecondaryEmail({
|
||||
userId: query.userId,
|
||||
secondaryEmailId: secondaryEmail.id,
|
||||
oldPrimaryEmail: currentUser.email,
|
||||
oldPrimaryEmailVerified: currentUser.emailVerified,
|
||||
newPrimaryEmail: newEmail,
|
||||
userUpdateData: prismaData,
|
||||
});
|
||||
|
||||
const user = schemaUserReadPublic.parse(data);
|
||||
return { user };
|
||||
} else {
|
||||
prismaData.metadata = {
|
||||
...(currentUser.metadata as Prisma.JsonObject),
|
||||
...(typeof prismaData.metadata === "object" && prismaData.metadata ? prismaData.metadata : {}),
|
||||
emailChangeWaitingForVerification: newEmail.toLowerCase(),
|
||||
};
|
||||
|
||||
delete prismaData.email;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const data = await prisma.user.update({
|
||||
where: { id: query.userId },
|
||||
data: body,
|
||||
data: prismaData,
|
||||
});
|
||||
|
||||
const shouldSendEmailVerification =
|
||||
hasEmailBeenChanged && emailVerification && newEmail && !prismaData.email;
|
||||
|
||||
if (shouldSendEmailVerification) {
|
||||
await sendChangeOfEmailVerification({
|
||||
user: {
|
||||
username: data.username ?? "Nameless User",
|
||||
emailFrom: currentUser.email,
|
||||
emailTo: newEmail,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const user = schemaUserReadPublic.parse(data);
|
||||
return { user };
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user