feat: signup refactor (#11421)
Co-authored-by: alannnc <[email protected]> Co-authored-by: Alex van Andel <[email protected]> Co-authored-by: Peer Richelsen <[email protected]>
This commit is contained in:
29 files changed
+1801
-518
No files matched your search
@@ -0,0 +1,207 @@
|
||||
import type { NextApiResponse } from "next";
|
||||
|
||||
import stripe from "@calcom/app-store/stripepayment/lib/server";
|
||||
import { getPremiumMonthlyPlanPriceId } from "@calcom/app-store/stripepayment/lib/utils";
|
||||
import { hashPassword } from "@calcom/features/auth/lib/hashPassword";
|
||||
import { sendEmailVerification } from "@calcom/features/auth/lib/verifyEmail";
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { getLocaleFromRequest } from "@calcom/lib/getLocaleFromRequest";
|
||||
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 { 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";
|
||||
|
||||
async function handler(req: RequestWithUsernameStatus, res: NextApiResponse) {
|
||||
const {
|
||||
email: _email,
|
||||
password,
|
||||
token,
|
||||
} = signupSchema
|
||||
.pick({
|
||||
email: true,
|
||||
password: true,
|
||||
token: true,
|
||||
})
|
||||
.parse(req.body);
|
||||
let username: string | null = req.usernameStatus.requestedUserName;
|
||||
let checkoutSessionId: string | null = null;
|
||||
|
||||
// Check for premium username
|
||||
if (req.usernameStatus.statusCode === 418) {
|
||||
return res.status(req.usernameStatus.statusCode).json(req.usernameStatus.json);
|
||||
}
|
||||
|
||||
// Validate the user
|
||||
if (!username) {
|
||||
throw new HttpError({
|
||||
statusCode: 422,
|
||||
message: "Invalid username",
|
||||
});
|
||||
}
|
||||
|
||||
const email = _email.toLowerCase();
|
||||
|
||||
let foundToken: { id: number; teamId: number | null; expires: Date } | null = null;
|
||||
if (token) {
|
||||
foundToken = await findTokenByToken({ token });
|
||||
throwIfTokenExpired(foundToken?.expires);
|
||||
await validateUsernameForTeam({ username, email, teamId: foundToken?.teamId ?? null });
|
||||
} else {
|
||||
const usernameAndEmailValidation = await validateUsername(username, email);
|
||||
if (!usernameAndEmailValidation.isValid) {
|
||||
throw new HttpError({
|
||||
statusCode: 409,
|
||||
message: "Username or email is already taken",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Create the customer in Stripe
|
||||
const customer = await stripe.customers.create({
|
||||
email,
|
||||
metadata: {
|
||||
email /* Stripe customer email can be changed, so we add this to keep track of which email was used to signup */,
|
||||
username,
|
||||
},
|
||||
});
|
||||
|
||||
const returnUrl = `${WEBAPP_URL}/api/integrations/stripepayment/paymentCallback?checkoutSessionId={CHECKOUT_SESSION_ID}&callbackUrl=/auth/verify?sessionId={CHECKOUT_SESSION_ID}`;
|
||||
|
||||
// Pro username, must be purchased
|
||||
if (req.usernameStatus.statusCode === 402) {
|
||||
const checkoutSession = await stripe.checkout.sessions.create({
|
||||
mode: "subscription",
|
||||
payment_method_types: ["card"],
|
||||
customer: customer.id,
|
||||
line_items: [
|
||||
{
|
||||
price: getPremiumMonthlyPlanPriceId(),
|
||||
quantity: 1,
|
||||
},
|
||||
],
|
||||
success_url: returnUrl,
|
||||
cancel_url: returnUrl,
|
||||
allow_promotion_codes: true,
|
||||
});
|
||||
|
||||
/** We create a username-less user until he pays */
|
||||
checkoutSessionId = checkoutSession.id;
|
||||
username = null;
|
||||
}
|
||||
|
||||
// Hash the password
|
||||
const hashedPassword = await hashPassword(password);
|
||||
|
||||
if (foundToken && foundToken?.teamId) {
|
||||
const team = await prisma.team.findUnique({
|
||||
where: {
|
||||
id: foundToken.teamId,
|
||||
},
|
||||
});
|
||||
if (team) {
|
||||
const teamMetadata = teamMetadataSchema.parse(team?.metadata);
|
||||
|
||||
const user = await prisma.user.upsert({
|
||||
where: { email },
|
||||
update: {
|
||||
username,
|
||||
password: hashedPassword,
|
||||
emailVerified: new Date(Date.now()),
|
||||
identityProvider: IdentityProvider.CAL,
|
||||
},
|
||||
create: {
|
||||
username,
|
||||
email,
|
||||
password: hashedPassword,
|
||||
identityProvider: IdentityProvider.CAL,
|
||||
},
|
||||
});
|
||||
|
||||
// Wrapping in a transaction as if one fails we want to rollback the whole thing to preventa any data inconsistencies
|
||||
const membership = await prisma.$transaction(async (tx) => {
|
||||
if (teamMetadata?.isOrganization) {
|
||||
await tx.user.update({
|
||||
where: {
|
||||
id: user.id,
|
||||
},
|
||||
data: {
|
||||
organizationId: team.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
const membership = await tx.membership.upsert({
|
||||
where: {
|
||||
userId_teamId: { userId: user.id, teamId: team.id },
|
||||
},
|
||||
update: {
|
||||
accepted: true,
|
||||
},
|
||||
create: {
|
||||
userId: user.id,
|
||||
teamId: team.id,
|
||||
role: MembershipRole.MEMBER,
|
||||
accepted: true,
|
||||
},
|
||||
});
|
||||
return membership;
|
||||
});
|
||||
|
||||
closeComUpsertTeamUser(team, user, membership.role);
|
||||
|
||||
// Accept any child team invites for orgs.
|
||||
if (team.parentId) {
|
||||
await joinAnyChildTeamOnOrgInvite({
|
||||
userId: user.id,
|
||||
orgId: team.parentId,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Cleanup token after use
|
||||
await prisma.verificationToken.delete({
|
||||
where: {
|
||||
id: foundToken.id,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
// Create the user
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
username,
|
||||
email,
|
||||
password: hashedPassword,
|
||||
metadata: {
|
||||
stripeCustomerId: customer.id,
|
||||
checkoutSessionId,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
sendEmailVerification({
|
||||
email,
|
||||
language: await getLocaleFromRequest(req),
|
||||
username: username || "",
|
||||
});
|
||||
// Sync Services
|
||||
await syncServicesCreateWebUser(user);
|
||||
}
|
||||
|
||||
if (checkoutSessionId) {
|
||||
console.log("Created user but missing payment", checkoutSessionId);
|
||||
return res.status(402).json({
|
||||
message: "Created user but missing payment",
|
||||
checkoutSessionId,
|
||||
});
|
||||
}
|
||||
|
||||
return res.status(201).json({ message: "Created user", stripeCustomerId: customer.id });
|
||||
}
|
||||
|
||||
export default usernameHandler(handler);
|
||||
@@ -0,0 +1,147 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
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 slugify from "@calcom/lib/slugify";
|
||||
import { closeComUpsertTeamUser } from "@calcom/lib/sync/SyncServiceManager";
|
||||
import { validateUsername } 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";
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const data = req.body;
|
||||
const { email, password, language, token } = signupSchema.parse(data);
|
||||
|
||||
const username = slugify(data.username);
|
||||
const userEmail = email.toLowerCase();
|
||||
|
||||
if (!username) {
|
||||
res.status(422).json({ message: "Invalid username" });
|
||||
return;
|
||||
}
|
||||
|
||||
let foundToken: { id: number; teamId: number | null; expires: Date } | null = null;
|
||||
if (token) {
|
||||
foundToken = await findTokenByToken({ token });
|
||||
throwIfTokenExpired(foundToken?.expires);
|
||||
await validateUsernameForTeam({ username, email: userEmail, teamId: foundToken?.teamId });
|
||||
} else {
|
||||
const userValidation = await validateUsername(username, userEmail);
|
||||
if (!userValidation.isValid) {
|
||||
return res.status(409).json({ message: "Username or email is already taken" });
|
||||
}
|
||||
}
|
||||
|
||||
const hashedPassword = await hashPassword(password);
|
||||
|
||||
if (foundToken && foundToken?.teamId) {
|
||||
const team = await prisma.team.findUnique({
|
||||
where: {
|
||||
id: foundToken.teamId,
|
||||
},
|
||||
});
|
||||
if (team) {
|
||||
const teamMetadata = teamMetadataSchema.parse(team?.metadata);
|
||||
|
||||
const user = await prisma.user.upsert({
|
||||
where: { email: userEmail },
|
||||
update: {
|
||||
username,
|
||||
password: hashedPassword,
|
||||
emailVerified: new Date(Date.now()),
|
||||
identityProvider: IdentityProvider.CAL,
|
||||
},
|
||||
create: {
|
||||
username,
|
||||
email: userEmail,
|
||||
password: hashedPassword,
|
||||
identityProvider: IdentityProvider.CAL,
|
||||
},
|
||||
});
|
||||
|
||||
const membership = await prisma.$transaction(async (tx) => {
|
||||
if (teamMetadata?.isOrganization) {
|
||||
await tx.user.update({
|
||||
where: {
|
||||
id: user.id,
|
||||
},
|
||||
data: {
|
||||
organizationId: team.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
const membership = await tx.membership.upsert({
|
||||
where: {
|
||||
userId_teamId: { userId: user.id, teamId: team.id },
|
||||
},
|
||||
update: {
|
||||
accepted: true,
|
||||
},
|
||||
create: {
|
||||
userId: user.id,
|
||||
teamId: team.id,
|
||||
role: MembershipRole.MEMBER,
|
||||
accepted: true,
|
||||
},
|
||||
});
|
||||
return membership;
|
||||
});
|
||||
|
||||
closeComUpsertTeamUser(team, user, membership.role);
|
||||
|
||||
// Accept any child team invites for orgs.
|
||||
if (team.parentId) {
|
||||
await joinAnyChildTeamOnOrgInvite({
|
||||
userId: user.id,
|
||||
orgId: team.parentId,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Cleanup token after use
|
||||
await prisma.verificationToken.delete({
|
||||
where: {
|
||||
id: foundToken.id,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
if (IS_PREMIUM_USERNAME_ENABLED) {
|
||||
const checkUsername = await checkPremiumUsername(username);
|
||||
if (checkUsername.premium) {
|
||||
res.status(422).json({
|
||||
message: "Sign up from https://cal.com/signup to claim your premium username",
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
await prisma.user.upsert({
|
||||
where: { email: userEmail },
|
||||
update: {
|
||||
username,
|
||||
password: hashedPassword,
|
||||
emailVerified: new Date(Date.now()),
|
||||
identityProvider: IdentityProvider.CAL,
|
||||
},
|
||||
create: {
|
||||
username,
|
||||
email: userEmail,
|
||||
password: hashedPassword,
|
||||
identityProvider: IdentityProvider.CAL,
|
||||
},
|
||||
});
|
||||
await sendEmailVerification({
|
||||
email: userEmail,
|
||||
username,
|
||||
language,
|
||||
});
|
||||
}
|
||||
|
||||
res.status(201).json({ message: "Created user" });
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { z } from "zod";
|
||||
|
||||
import notEmpty from "@calcom/lib/notEmpty";
|
||||
import { isPremiumUserName, generateUsernameSuggestion } from "@calcom/lib/server/username";
|
||||
import slugify from "@calcom/lib/slugify";
|
||||
import prisma from "@calcom/prisma";
|
||||
|
||||
export type RequestWithUsernameStatus = NextApiRequest & {
|
||||
usernameStatus: {
|
||||
/**
|
||||
* ```text
|
||||
* 200: Username is available
|
||||
* 402: Pro username, must be purchased
|
||||
* 418: A user exists with that username
|
||||
* ```
|
||||
*/
|
||||
statusCode: 200 | 402 | 418;
|
||||
requestedUserName: string;
|
||||
json: {
|
||||
available: boolean;
|
||||
premium: boolean;
|
||||
message?: string;
|
||||
suggestion?: string;
|
||||
};
|
||||
};
|
||||
};
|
||||
export const usernameStatusSchema = z.object({
|
||||
statusCode: z.union([z.literal(200), z.literal(402), z.literal(418)]),
|
||||
requestedUserName: z.string(),
|
||||
json: z.object({
|
||||
available: z.boolean(),
|
||||
premium: z.boolean(),
|
||||
message: z.string().optional(),
|
||||
suggestion: z.string().optional(),
|
||||
}),
|
||||
});
|
||||
|
||||
type CustomNextApiHandler<T = unknown> = (
|
||||
req: RequestWithUsernameStatus,
|
||||
res: NextApiResponse<T>
|
||||
) => void | Promise<void>;
|
||||
|
||||
const usernameHandler =
|
||||
(handler: CustomNextApiHandler) =>
|
||||
async (req: RequestWithUsernameStatus, res: NextApiResponse): Promise<void> => {
|
||||
const username = slugify(req.body.username);
|
||||
const check = await usernameCheck(username);
|
||||
|
||||
req.usernameStatus = {
|
||||
statusCode: 200,
|
||||
requestedUserName: username,
|
||||
json: {
|
||||
available: true,
|
||||
premium: false,
|
||||
message: "Username is available",
|
||||
},
|
||||
};
|
||||
|
||||
if (check.premium) {
|
||||
req.usernameStatus.statusCode = 402;
|
||||
req.usernameStatus.json.premium = true;
|
||||
req.usernameStatus.json.message = "This is a premium username.";
|
||||
}
|
||||
|
||||
if (!check.available) {
|
||||
req.usernameStatus.statusCode = 418;
|
||||
req.usernameStatus.json.available = false;
|
||||
req.usernameStatus.json.message = "A user exists with that username";
|
||||
}
|
||||
|
||||
req.usernameStatus.json.suggestion = check.suggestedUsername;
|
||||
|
||||
return handler(req, res);
|
||||
};
|
||||
|
||||
const usernameCheck = async (usernameRaw: string) => {
|
||||
const response = {
|
||||
available: true,
|
||||
premium: false,
|
||||
suggestedUsername: "",
|
||||
};
|
||||
|
||||
const username = slugify(usernameRaw);
|
||||
|
||||
const user = await prisma.user.findFirst({
|
||||
where: { username, organizationId: null },
|
||||
select: {
|
||||
username: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (user) {
|
||||
response.available = false;
|
||||
}
|
||||
|
||||
if (await isPremiumUserName(username)) {
|
||||
response.premium = true;
|
||||
}
|
||||
|
||||
// get list of similar usernames in the db
|
||||
const users = await prisma.user.findMany({
|
||||
where: {
|
||||
username: {
|
||||
contains: username,
|
||||
},
|
||||
},
|
||||
select: {
|
||||
username: true,
|
||||
},
|
||||
});
|
||||
|
||||
// We only need suggestedUsername if the username is not available
|
||||
if (!response.available) {
|
||||
response.suggestedUsername = await generateUsernameSuggestion(
|
||||
users.map((user) => user.username).filter(notEmpty),
|
||||
username
|
||||
);
|
||||
}
|
||||
|
||||
return response;
|
||||
};
|
||||
|
||||
export { usernameHandler, usernameCheck };
|
||||
@@ -0,0 +1,55 @@
|
||||
import prisma from "@calcom/prisma";
|
||||
|
||||
export async function joinOrganization({
|
||||
organizationId,
|
||||
userId,
|
||||
}: {
|
||||
userId: number;
|
||||
organizationId: number;
|
||||
}) {
|
||||
return await prisma.user.update({
|
||||
where: {
|
||||
id: userId,
|
||||
},
|
||||
data: {
|
||||
organizationId: organizationId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function joinAnyChildTeamOnOrgInvite({ userId, orgId }: { userId: number; orgId: number }) {
|
||||
await prisma.$transaction([
|
||||
prisma.user.update({
|
||||
where: {
|
||||
id: userId,
|
||||
},
|
||||
data: {
|
||||
organizationId: orgId,
|
||||
},
|
||||
}),
|
||||
prisma.membership.updateMany({
|
||||
where: {
|
||||
userId,
|
||||
team: {
|
||||
id: orgId,
|
||||
},
|
||||
accepted: false,
|
||||
},
|
||||
data: {
|
||||
accepted: true,
|
||||
},
|
||||
}),
|
||||
prisma.membership.updateMany({
|
||||
where: {
|
||||
userId,
|
||||
team: {
|
||||
parentId: orgId,
|
||||
},
|
||||
accepted: false,
|
||||
},
|
||||
data: {
|
||||
accepted: true,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { validateUsernameInTeam } from "@calcom/lib/validateUsername";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
|
||||
export async function findTokenByToken({ token }: { token: string }) {
|
||||
const foundToken = await prisma.verificationToken.findFirst({
|
||||
where: {
|
||||
token,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
expires: true,
|
||||
teamId: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!foundToken) {
|
||||
throw new HttpError({
|
||||
statusCode: 401,
|
||||
message: "Invalid Token",
|
||||
});
|
||||
}
|
||||
|
||||
return foundToken;
|
||||
}
|
||||
|
||||
export function throwIfTokenExpired(expires?: Date) {
|
||||
if (!expires) return;
|
||||
if (dayjs(expires).isBefore(dayjs())) {
|
||||
throw new HttpError({
|
||||
statusCode: 401,
|
||||
message: "Token expired",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export async function validateUsernameForTeam({
|
||||
username,
|
||||
email,
|
||||
teamId,
|
||||
}: {
|
||||
username: string;
|
||||
email: string;
|
||||
teamId: number | null;
|
||||
}) {
|
||||
if (!teamId) return;
|
||||
const teamUserValidation = await validateUsernameInTeam(username, email, teamId);
|
||||
if (!teamUserValidation.isValid) {
|
||||
throw new HttpError({
|
||||
statusCode: 409,
|
||||
message: "Username or email is already taken",
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user