fix: Disallow changing username and email in case of Organization email invite (#12735)

Co-authored-by: Omar López <[email protected]>
This commit is contained in:
Hariom BalharaandOmar López authored and GitHub committed 2023-12-13 20:08:16 +00:00
1 parent 943c7a4c6c
commit 99e71365ab
9 files changed
+263 -69

No files matched your search

@@ -10,13 +10,17 @@ import { HttpError } from "@calcom/lib/http-error";
import { usernameHandler, type RequestWithUsernameStatus } from "@calcom/lib/server/username";
import { createWebUser as syncServicesCreateWebUser } from "@calcom/lib/sync/SyncServiceManager";
import { closeComUpsertTeamUser } from "@calcom/lib/sync/SyncServiceManager";
import { validateUsername } from "@calcom/lib/validateUsername";
import { validateAndGetCorrectedUsernameAndEmail } from "@calcom/lib/validateUsername";
import { prisma } from "@calcom/prisma";
import { IdentityProvider, MembershipRole } from "@calcom/prisma/enums";
import { signupSchema, teamMetadataSchema } from "@calcom/prisma/zod-utils";
import { joinAnyChildTeamOnOrgInvite } from "../utils/organization";
import { findTokenByToken, throwIfTokenExpired, validateUsernameForTeam } from "../utils/token";
import {
findTokenByToken,
throwIfTokenExpired,
validateAndGetCorrectedUsernameForTeam,
} from "../utils/token";
async function handler(req: RequestWithUsernameStatus, res: NextApiResponse) {
const {
@@ -52,15 +56,33 @@ async function handler(req: RequestWithUsernameStatus, res: NextApiResponse) {
if (token) {
foundToken = await findTokenByToken({ token });
throwIfTokenExpired(foundToken?.expires);
await validateUsernameForTeam({ username, email, teamId: foundToken?.teamId ?? null });
username = await validateAndGetCorrectedUsernameForTeam({
username,
email,
teamId: foundToken?.teamId ?? null,
isSignup: true,
});
} else {
const usernameAndEmailValidation = await validateUsername(username, email);
const usernameAndEmailValidation = await validateAndGetCorrectedUsernameAndEmail({
username,
email,
isSignup: true,
});
if (!usernameAndEmailValidation.isValid) {
throw new HttpError({
statusCode: 409,
message: "Username or email is already taken",
});
}
if (!usernameAndEmailValidation.username) {
throw new HttpError({
statusCode: 422,
message: "Invalid username",
});
}
username = usernameAndEmailValidation.username;
}
// Create the customer in Stripe
@@ -4,16 +4,21 @@ import { checkPremiumUsername } from "@calcom/ee/common/lib/checkPremiumUsername
import { hashPassword } from "@calcom/features/auth/lib/hashPassword";
import { sendEmailVerification } from "@calcom/features/auth/lib/verifyEmail";
import { IS_PREMIUM_USERNAME_ENABLED } from "@calcom/lib/constants";
import logger from "@calcom/lib/logger";
import slugify from "@calcom/lib/slugify";
import { closeComUpsertTeamUser } from "@calcom/lib/sync/SyncServiceManager";
import { validateUsername } from "@calcom/lib/validateUsername";
import { validateAndGetCorrectedUsernameAndEmail } from "@calcom/lib/validateUsername";
import prisma from "@calcom/prisma";
import { IdentityProvider, MembershipRole } from "@calcom/prisma/enums";
import { signupSchema } from "@calcom/prisma/zod-utils";
import { teamMetadataSchema } from "@calcom/prisma/zod-utils";
import { joinAnyChildTeamOnOrgInvite } from "../utils/organization";
import { findTokenByToken, throwIfTokenExpired, validateUsernameForTeam } from "../utils/token";
import {
findTokenByToken,
throwIfTokenExpired,
validateAndGetCorrectedUsernameForTeam,
} from "../utils/token";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const data = req.body;
@@ -28,15 +33,30 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
}
let foundToken: { id: number; teamId: number | null; expires: Date } | null = null;
let correctedUsername = username;
if (token) {
foundToken = await findTokenByToken({ token });
throwIfTokenExpired(foundToken?.expires);
await validateUsernameForTeam({ username, email: userEmail, teamId: foundToken?.teamId });
correctedUsername = await validateAndGetCorrectedUsernameForTeam({
username,
email: userEmail,
teamId: foundToken?.teamId,
isSignup: true,
});
} else {
const userValidation = await validateUsername(username, userEmail);
const userValidation = await validateAndGetCorrectedUsernameAndEmail({
username,
email: userEmail,
isSignup: true,
});
if (!userValidation.isValid) {
logger.error("User validation failed", { userValidation });
return res.status(409).json({ message: "Username or email is already taken" });
}
if (!userValidation.username) {
return res.status(422).json({ message: "Invalid username" });
}
correctedUsername = userValidation.username;
}
const hashedPassword = await hashPassword(password);
@@ -53,13 +73,13 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
const user = await prisma.user.upsert({
where: { email: userEmail },
update: {
username,
username: correctedUsername,
password: hashedPassword,
emailVerified: new Date(Date.now()),
identityProvider: IdentityProvider.CAL,
},
create: {
username,
username: correctedUsername,
email: userEmail,
password: hashedPassword,
identityProvider: IdentityProvider.CAL,
@@ -113,7 +133,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
});
} else {
if (IS_PREMIUM_USERNAME_ENABLED) {
const checkUsername = await checkPremiumUsername(username);
const checkUsername = await checkPremiumUsername(correctedUsername);
if (checkUsername.premium) {
res.status(422).json({
message: "Sign up from https://cal.com/signup to claim your premium username",
@@ -124,13 +144,13 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
await prisma.user.upsert({
where: { email: userEmail },
update: {
username,
username: correctedUsername,
password: hashedPassword,
emailVerified: new Date(Date.now()),
identityProvider: IdentityProvider.CAL,
},
create: {
username,
username: correctedUsername,
email: userEmail,
password: hashedPassword,
identityProvider: IdentityProvider.CAL,
@@ -138,7 +158,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
});
await sendEmailVerification({
email: userEmail,
username,
username: correctedUsername,
language,
});
}
@@ -0,0 +1,11 @@
import slugify from "@calcom/lib/slugify";
export const getOrgUsernameFromEmail = (email: string, autoAcceptEmailDomain: string) => {
const [emailUser, emailDomain = ""] = email.split("@");
const username =
emailDomain === autoAcceptEmailDomain
? slugify(emailUser)
: slugify(`${emailUser}-${emailDomain.split(".")[0]}`);
return username;
};
+14 -4
View File
@@ -1,6 +1,6 @@
import dayjs from "@calcom/dayjs";
import { HttpError } from "@calcom/lib/http-error";
import { validateUsernameInTeam } from "@calcom/lib/validateUsername";
import { validateAndGetCorrectedUsernameInTeam } from "@calcom/lib/validateUsername";
import { prisma } from "@calcom/prisma";
export async function findTokenByToken({ token }: { token: string }) {
@@ -35,21 +35,31 @@ export function throwIfTokenExpired(expires?: Date) {
}
}
export async function validateUsernameForTeam({
export async function validateAndGetCorrectedUsernameForTeam({
username,
email,
teamId,
isSignup,
}: {
username: string;
email: string;
teamId: number | null;
isSignup: boolean;
}) {
if (!teamId) return;
const teamUserValidation = await validateUsernameInTeam(username, email, teamId);
if (!teamId) return username;
const teamUserValidation = await validateAndGetCorrectedUsernameInTeam(username, email, teamId, isSignup);
if (!teamUserValidation.isValid) {
throw new HttpError({
statusCode: 409,
message: "Username or email is already taken",
});
}
if (!teamUserValidation.username) {
throw new HttpError({
statusCode: 422,
message: "Invalid username",
});
}
return teamUserValidation.username;
}