* Remove auto adding users to an org * Update tests * Fix tests * fix: Update organization invitation E2E tests to not expect auto-accept before signup - Changed isMemberShipAccepted expectations from true to false before signup - Users with emails matching orgAutoAcceptEmail are no longer auto-accepted - They must explicitly accept the invitation after signup - Fixed lint warnings for unused parameters Co-Authored-By: [email protected] <[email protected]> * fix: Update E2E tests to expect pending membership after signup without auto-accept Since auto-accept functionality was removed, users with emails matching orgAutoAcceptEmail are no longer automatically accepted into organizations after signup. They remain in pending state until explicitly accepted. Updated assertions in: - 'nonexisting user is invited to Org' test - 'nonexisting user is invited to a team inside organization' test Both tests now correctly expect isMemberShipAccepted: false after signup. Co-Authored-By: [email protected] <[email protected]> * Restore `verify-email` and tests from `main` * Add `orgAutoJoinOnSignup` to `organizationSettings` * Update `OrganizationRepository.findUniqueNonPlatformOrgsByMatchingAutoAcceptEmail` to find orgs where `orgAutoJoinOnSignup` is true * `organization.update` lint fix * `organization.update` to handle `orgAutoJoinOnSignup` * Create toggle for `orgAutoJoinOnSignup` * test: Add comprehensive tests for orgAutoJoinOnSignup functionality - Update existing test to expect null instead of error when multiple orgs match - Add test for when orgAutoJoinOnSignup is false (should return null) - Add test for when orgAutoJoinOnSignup is true (should return org) - Add test for default behavior (orgAutoJoinOnSignup defaults to true) These tests verify that the new orgAutoJoinOnSignup setting correctly controls whether users are automatically added to organizations during email verification. Co-Authored-By: [email protected] <[email protected]> * Type fix * e2e: invited users should be accepted after signup (address cubic r2511916791) Reverted post-signup isMemberShipAccepted assertions from false to true for explicit invite scenarios. When users are explicitly invited to an org/team and complete signup via invite link, their membership should be accepted. This is distinct from auto-join by domain (controlled by orgAutoJoinOnSignup), which only affects users who sign up without an invite but match the org's email domain. Backend sets membership.accepted = true on invite completion in: packages/features/auth/signup/utils/createOrUpdateMemberships.ts:61,67,77,83 Co-Authored-By: [email protected] <[email protected]> * Fix API V2 build --------- Co-authored-by: Alex van Andel <[email protected]> Co-authored-by: Anik Dhabal Babu <[email protected]> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
190 lines
5.4 KiB
TypeScript
190 lines
5.4 KiB
TypeScript
import type { NextApiRequest, NextApiResponse } from "next";
|
|
import { z } from "zod";
|
|
|
|
import dayjs from "@calcom/dayjs";
|
|
import { StripeBillingService } from "@calcom/features/ee/billing/stripe-billing-service";
|
|
import { getOrganizationRepository } from "@calcom/features/ee/organizations/di/OrganizationRepository.container";
|
|
import { OnboardingPathService } from "@calcom/features/onboarding/lib/onboarding-path.service";
|
|
import { WEBAPP_URL } from "@calcom/lib/constants";
|
|
import { IS_STRIPE_ENABLED } from "@calcom/lib/constants";
|
|
import { prisma } from "@calcom/prisma";
|
|
import { MembershipRole } from "@calcom/prisma/enums";
|
|
import { CreationSource } from "@calcom/prisma/enums";
|
|
import { userMetadata } from "@calcom/prisma/zod-utils";
|
|
import { inviteMembersWithNoInviterPermissionCheck } from "@calcom/trpc/server/routers/viewer/teams/inviteMember/inviteMember.handler";
|
|
|
|
const verifySchema = z.object({
|
|
token: z.string(),
|
|
});
|
|
|
|
const USER_ALREADY_EXISTING_MESSAGE = "A User already exists with this email";
|
|
|
|
// TODO: To be unit tested
|
|
export async function moveUserToMatchingOrg({ email }: { email: string }) {
|
|
const organizationRepository = getOrganizationRepository();
|
|
const org = await organizationRepository.findUniqueNonPlatformOrgsByMatchingAutoAcceptEmail({ email });
|
|
|
|
if (!org) {
|
|
return;
|
|
}
|
|
|
|
await inviteMembersWithNoInviterPermissionCheck({
|
|
inviterName: null,
|
|
teamId: org.id,
|
|
language: "en",
|
|
creationSource: CreationSource.WEBAPP,
|
|
invitations: [
|
|
{
|
|
usernameOrEmail: email,
|
|
role: MembershipRole.MEMBER,
|
|
},
|
|
],
|
|
orgSlug: org.slug || org.requestedSlug,
|
|
});
|
|
}
|
|
|
|
export async function handler(req: NextApiRequest, res: NextApiResponse) {
|
|
const { token } = verifySchema.parse(req.query);
|
|
const billingService = new StripeBillingService();
|
|
|
|
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" });
|
|
}
|
|
|
|
// The user is verifying the secondary email
|
|
if (foundToken?.secondaryEmailId) {
|
|
await prisma.secondaryEmail.update({
|
|
where: {
|
|
id: foundToken.secondaryEmailId,
|
|
email: foundToken?.identifier,
|
|
},
|
|
data: {
|
|
emailVerified: new Date(),
|
|
},
|
|
});
|
|
|
|
await cleanUpVerificationTokens(foundToken.id);
|
|
|
|
return res.redirect(`${WEBAPP_URL}/settings/my-account/profile`);
|
|
}
|
|
|
|
const user = await prisma.user.findFirst({
|
|
where: {
|
|
email: foundToken?.identifier,
|
|
},
|
|
});
|
|
|
|
if (!user) {
|
|
return res.status(401).json({ message: "Cannot find a user attached to this token" });
|
|
}
|
|
|
|
const userMetadataParsed = userMetadata.parse(user.metadata);
|
|
// Attach the new email and verify
|
|
if (userMetadataParsed?.emailChangeWaitingForVerification) {
|
|
// Ensure this email isn't in use
|
|
const existingUser = await prisma.user.findUnique({
|
|
where: { email: userMetadataParsed?.emailChangeWaitingForVerification },
|
|
select: {
|
|
id: true,
|
|
},
|
|
});
|
|
if (existingUser) {
|
|
return res.status(401).json({ message: USER_ALREADY_EXISTING_MESSAGE });
|
|
}
|
|
|
|
// Ensure this email isn't being added by another user as secondary email
|
|
const existingSecondaryUser = await prisma.secondaryEmail.findUnique({
|
|
where: {
|
|
email: userMetadataParsed?.emailChangeWaitingForVerification,
|
|
},
|
|
select: {
|
|
id: true,
|
|
userId: true,
|
|
},
|
|
});
|
|
|
|
if (existingSecondaryUser && existingSecondaryUser.userId !== user.id) {
|
|
return res.status(401).json({ message: USER_ALREADY_EXISTING_MESSAGE });
|
|
}
|
|
|
|
const oldEmail = user.email;
|
|
const updatedEmail = userMetadataParsed.emailChangeWaitingForVerification;
|
|
delete userMetadataParsed.emailChangeWaitingForVerification;
|
|
|
|
// Update and re-verify
|
|
await prisma.user.update({
|
|
where: {
|
|
id: user.id,
|
|
},
|
|
data: {
|
|
email: updatedEmail,
|
|
metadata: userMetadataParsed,
|
|
},
|
|
});
|
|
|
|
if (IS_STRIPE_ENABLED && userMetadataParsed.stripeCustomerId) {
|
|
await billingService.updateCustomer({
|
|
customerId: userMetadataParsed.stripeCustomerId,
|
|
email: updatedEmail,
|
|
});
|
|
}
|
|
|
|
// The user is trying to update the email to an already existing unverified secondary email of his
|
|
// so we swap the emails and its verified status
|
|
if (existingSecondaryUser?.userId === user.id) {
|
|
await prisma.secondaryEmail.update({
|
|
where: {
|
|
id: existingSecondaryUser.id,
|
|
userId: user.id,
|
|
},
|
|
data: {
|
|
email: oldEmail,
|
|
emailVerified: user.emailVerified,
|
|
},
|
|
});
|
|
}
|
|
|
|
await cleanUpVerificationTokens(foundToken.id);
|
|
|
|
return res.status(200).json({
|
|
updatedEmail,
|
|
});
|
|
}
|
|
|
|
await prisma.user.update({
|
|
where: {
|
|
id: user.id,
|
|
},
|
|
data: {
|
|
emailVerified: new Date(),
|
|
},
|
|
});
|
|
|
|
const hasCompletedOnboarding = user.completedOnboarding;
|
|
|
|
await moveUserToMatchingOrg({ email: user.email });
|
|
|
|
const gettingStartedPath = await OnboardingPathService.getGettingStartedPath(prisma);
|
|
|
|
return res.redirect(`${WEBAPP_URL}${hasCompletedOnboarding ? "/event-types" : gettingStartedPath}`);
|
|
}
|
|
|
|
export async function cleanUpVerificationTokens(id: number) {
|
|
// Delete token from DB after it has been used
|
|
await prisma.verificationToken.delete({
|
|
where: {
|
|
id,
|
|
},
|
|
});
|
|
}
|