fix: Organization Migration - Prevent the redirected username from being claimed by others. (#13675)

* Check for migrated username

* Add e2e for reserved username due to migration

* Add username change test

* Update username.ts

* fixed type checks

* Refactor to use isOrganization

* Typing

* Typing

* Removed the isOrganization function

---------

Co-authored-by: Joe Au-Yeung <[email protected]>
Co-authored-by: Keith Williams <[email protected]>
This commit is contained in:
authored and GitHub committed 2024-03-05 17:08:44 +00:00
1 parent d8cee20d0c
commit a677d0d2c4
18 files changed
+216 -45

No files matched your search

@@ -8,6 +8,7 @@ import { createOrUpdateMemberships } from "@calcom/features/auth/signup/utils/cr
import { WEBAPP_URL } from "@calcom/lib/constants";
import { getLocaleFromRequest } from "@calcom/lib/getLocaleFromRequest";
import { HttpError } from "@calcom/lib/http-error";
import logger from "@calcom/lib/logger";
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";
@@ -23,6 +24,8 @@ import {
validateAndGetCorrectedUsernameForTeam,
} from "../utils/token";
const log = logger.getSubLogger({ prefix: ["signupCalcomHandler"] });
async function handler(req: RequestWithUsernameStatus, res: NextApiResponse) {
const {
email: _email,
@@ -35,6 +38,9 @@ async function handler(req: RequestWithUsernameStatus, res: NextApiResponse) {
token: true,
})
.parse(req.body);
log.debug("handler", { email: _email });
let username: string | null = req.usernameStatus.requestedUserName;
let checkoutSessionId: string | null = null;
@@ -6,6 +6,7 @@ import { sendEmailVerification } from "@calcom/features/auth/lib/verifyEmail";
import { createOrUpdateMemberships } from "@calcom/features/auth/signup/utils/createOrUpdateMemberships";
import { IS_PREMIUM_USERNAME_ENABLED } from "@calcom/lib/constants";
import logger from "@calcom/lib/logger";
import { isUsernameReservedDueToMigration } from "@calcom/lib/server/username";
import slugify from "@calcom/lib/slugify";
import { closeComUpsertTeamUser } from "@calcom/lib/sync/SyncServiceManager";
import { validateAndGetCorrectedUsernameAndEmail } from "@calcom/lib/validateUsername";
@@ -78,7 +79,19 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
organizationSettings: true,
},
});
if (team) {
const isInviteForATeamInOrganization = !!team.parent;
const isCheckingUsernameInGlobalNamespace = !team.isOrganization && !isInviteForATeamInOrganization;
if (isCheckingUsernameInGlobalNamespace) {
const isUsernameAvailable = !(await isUsernameReservedDueToMigration(correctedUsername));
if (!isUsernameAvailable) {
res.status(409).json({ message: "A user exists with that username" });
return;
}
}
const user = await prisma.user.upsert({
where: { email: userEmail },
update: {
@@ -123,6 +136,11 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
},
});
} else {
const isUsernameAvailable = !(await isUsernameReservedDueToMigration(correctedUsername));
if (!isUsernameAvailable) {
res.status(409).json({ message: "A user exists with that username" });
return;
}
if (IS_PREMIUM_USERNAME_ENABLED) {
const checkUsername = await checkPremiumUsername(correctedUsername);
if (checkUsername.premium) {
@@ -6,7 +6,6 @@ import InviteLinkSettingsModal from "@calcom/ee/teams/components/InviteLinkSetti
import MemberInvitationModal from "@calcom/ee/teams/components/MemberInvitationModal";
import classNames from "@calcom/lib/classNames";
import { getPlaceholderAvatar } from "@calcom/lib/defaultAvatarImage";
import { isOrganization } from "@calcom/lib/entityPermissionUtils";
import { getTeamUrlSync } from "@calcom/lib/getBookerUrl/client";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useLocale } from "@calcom/lib/hooks/useLocale";
@@ -77,7 +76,7 @@ export default function TeamListItem(props: Props) {
utils.viewer.teams.listInvites.invalidate();
const userOrganizationId = user?.profile?.organization?.id;
const isSubTeamOfDifferentOrg = team.parentId ? team.parentId != userOrganizationId : false;
const isDifferentOrg = isOrganization({ team }) && team.id !== userOrganizationId;
const isDifferentOrg = team.isOrganization && team.id !== userOrganizationId;
// If the user team being accepted is a sub-team of different organization or the different organization itself then page must be reloaded to let the session change reflect reliably everywhere.
if (variables.accept && (isSubTeamOfDifferentOrg || isDifferentOrg)) {
window.location.reload();
@@ -101,7 +100,7 @@ export default function TeamListItem(props: Props) {
const { hideDropdown, setHideDropdown } = props;
if (!team) return <></>;
const teamUrl = isOrganization({ team })
const teamUrl = team.isOrganization
? getTeamUrlSync({ orgSlug: team.slug, teamSlug: null })
: getTeamUrlSync({ orgSlug: team.parent ? team.parent.slug : null, teamSlug: team.slug });
const teamInfo = (
@@ -2,7 +2,6 @@ import { useRouter } from "next/navigation";
import { useEffect, useMemo, useState } from "react";
import { APP_NAME, WEBAPP_URL } from "@calcom/lib/constants";
import { isOrganization } from "@calcom/lib/entityPermissionUtils";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
@@ -46,14 +45,11 @@ export function TeamsListing() {
},
});
const teams = useMemo(() => data?.filter((m) => m.accepted && !isOrganization({ team: m })) || [], [data]);
const teams = useMemo(() => data?.filter((m) => m.accepted && !m.isOrganization) || [], [data]);
const teamInvites = useMemo(
() => data?.filter((m) => !m.accepted && !isOrganization({ team: m })) || [],
[data]
);
const teamInvites = useMemo(() => data?.filter((m) => !m.accepted && !m.isOrganization) || [], [data]);
const organizationInvites = (data?.filter((m) => !m.accepted && isOrganization({ team: m })) || []).filter(
const organizationInvites = (data?.filter((m) => !m.accepted && m.isOrganization) || []).filter(
(orgInvite) => {
const isThereASubTeamOfTheOrganizationInInvites = teamInvites.find(
(teamInvite) => teamInvite.parentId === orgInvite.id
+1 -2
View File
@@ -4,7 +4,6 @@ import { getStripeCustomerIdFromUserId } from "@calcom/app-store/stripepayment/l
import stripe from "@calcom/app-store/stripepayment/lib/server";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { ORGANIZATION_MIN_SEATS } from "@calcom/lib/constants";
import { isOrganization } from "@calcom/lib/entityPermissionUtils";
import prisma from "@calcom/prisma";
import { teamMetadataSchema } from "@calcom/prisma/zod-utils";
@@ -157,7 +156,7 @@ export const updateQuantitySubscriptionFromStripe = async (teamId: number) => {
)?.quantity;
if (!subscriptionQuantity) throw new Error("Subscription not found");
if (!!isOrganization({ team }) && membershipCount < ORGANIZATION_MIN_SEATS) {
if (team.isOrganization && membershipCount < ORGANIZATION_MIN_SEATS) {
console.info(
`Org ${teamId} has less members than the min ${ORGANIZATION_MIN_SEATS}, skipping updating subscription.`
);