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:
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;
|
||||
};
|
||||
@@ -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;
|
||||
}
|
||||
@@ -1,7 +1,45 @@
|
||||
import { getOrgUsernameFromEmail } from "@calcom/features/auth/signup/utils/getOrgUsernameFromEmail";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { teamMetadataSchema } from "@calcom/prisma/zod-utils";
|
||||
|
||||
export const validateUsername = async (username: string, email: string, organizationId?: number) => {
|
||||
export const getUsernameForOrgMember = async ({
|
||||
email,
|
||||
orgAutoAcceptEmail,
|
||||
isSignup,
|
||||
username,
|
||||
}: {
|
||||
username?: string;
|
||||
email: string;
|
||||
orgAutoAcceptEmail?: string;
|
||||
isSignup: boolean;
|
||||
}) => {
|
||||
if (isSignup) {
|
||||
// We ensure that the username is always derived from the email during signup.
|
||||
return getOrgUsernameFromEmail(email, orgAutoAcceptEmail || "");
|
||||
}
|
||||
if (!username) {
|
||||
throw new Error("Username is required");
|
||||
}
|
||||
// Right now it's not possible to change username in an org by the user but when that's allowed we would simply accept the provided username
|
||||
return username;
|
||||
};
|
||||
|
||||
export const validateAndGetCorrectedUsernameAndEmail = async ({
|
||||
username,
|
||||
email,
|
||||
organizationId,
|
||||
orgAutoAcceptEmail,
|
||||
isSignup,
|
||||
}: {
|
||||
username: string;
|
||||
email: string;
|
||||
organizationId?: number;
|
||||
orgAutoAcceptEmail?: string;
|
||||
isSignup: boolean;
|
||||
}) => {
|
||||
if (username.includes("+")) {
|
||||
return { isValid: false, username: undefined, email };
|
||||
}
|
||||
// There is an existingUser if, within an org context or not, the username matches
|
||||
// OR if the email matches AND either the email is verified
|
||||
// or both username and password are set
|
||||
@@ -31,10 +69,24 @@ export const validateUsername = async (username: string, email: string, organiza
|
||||
email: true,
|
||||
},
|
||||
});
|
||||
return { isValid: !existingUser, email: existingUser?.email };
|
||||
let validatedUsername = username;
|
||||
if (organizationId) {
|
||||
validatedUsername = await getUsernameForOrgMember({
|
||||
email,
|
||||
orgAutoAcceptEmail,
|
||||
isSignup,
|
||||
});
|
||||
}
|
||||
|
||||
return { isValid: !existingUser, username: validatedUsername, email: existingUser?.email };
|
||||
};
|
||||
|
||||
export const validateUsernameInTeam = async (username: string, email: string, teamId: number) => {
|
||||
export const validateAndGetCorrectedUsernameInTeam = async (
|
||||
username: string,
|
||||
email: string,
|
||||
teamId: number,
|
||||
isSignup: boolean
|
||||
) => {
|
||||
try {
|
||||
const team = await prisma.team.findFirst({
|
||||
where: {
|
||||
@@ -49,15 +101,22 @@ export const validateUsernameInTeam = async (username: string, email: string, te
|
||||
const teamData = { ...team, metadata: teamMetadataSchema.parse(team?.metadata) };
|
||||
|
||||
if (teamData.metadata?.isOrganization || teamData.parentId) {
|
||||
const orgMetadata = teamData.metadata;
|
||||
// Organization context -> org-context username check
|
||||
const orgId = teamData.parentId || teamId;
|
||||
return validateUsername(username, email, orgId);
|
||||
return validateAndGetCorrectedUsernameAndEmail({
|
||||
username,
|
||||
email,
|
||||
organizationId: orgId,
|
||||
orgAutoAcceptEmail: orgMetadata?.orgAutoAcceptEmail || "",
|
||||
isSignup,
|
||||
});
|
||||
} else {
|
||||
// Regular team context -> regular username check
|
||||
return validateUsername(username, email);
|
||||
return validateAndGetCorrectedUsernameAndEmail({ username, email, isSignup });
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return { isValid: false, email: undefined };
|
||||
return { isValid: false, username: undefined, email: undefined };
|
||||
}
|
||||
};
|
||||
@@ -610,9 +610,9 @@ export const emailSchemaRefinement = (value: string) => {
|
||||
};
|
||||
|
||||
export const signupSchema = z.object({
|
||||
username: z.string().refine((value) => !value.includes("+"), {
|
||||
message: "String should not contain a plus symbol (+).",
|
||||
}),
|
||||
// Username is marked optional here because it's requirement depends on if it's the Organization invite or a team invite which isn't easily done in zod
|
||||
// It's better handled beyond zod in `validateAndGetCorrectedUsernameAndEmail`
|
||||
username: z.string().optional(),
|
||||
email: z.string().email(),
|
||||
password: z.string().superRefine((data, ctx) => {
|
||||
const isStrict = false;
|
||||
|
||||
Reference in new issue
Block a user