Skip to content

Scheduling infrastructure for absolutely everyone.

refactor: use userRepository class methods for signup handlers (#29561)

Anirban Singhadcd0da831f01
diff --git a/apps/web/app/api/auth/signup/handlers/calcomSignupHandler.ts b/apps/web/app/api/auth/signup/handlers/calcomSignupHandler.ts
index a31bbfaee0a..2423b5c45cc 100644
--- a/apps/web/app/api/auth/signup/handlers/calcomSignupHandler.ts
+++ b/apps/web/app/api/auth/signup/handlers/calcomSignupHandler.ts
@@ -13,7 +13,7 @@ import {
} from "@calcom/features/auth/signup/utils/token";
import { validateAndGetCorrectedUsernameAndEmail } from "@calcom/features/auth/signup/utils/validateUsername";
import { getFeatureRepository } from "@calcom/features/di/containers/FeatureRepository";
-import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
+import { getUserRepository } from "@calcom/features/di/containers/UserRepository";
import { GlobalWatchlistRepository } from "@calcom/features/watchlist/lib/repository/GlobalWatchlistRepository";
import { sentrySpan } from "@calcom/features/watchlist/lib/telemetry";
import { normalizeEmail } from "@calcom/features/watchlist/lib/utils/normalization";
@@ -26,7 +26,7 @@ import { isPrismaError } from "@calcom/lib/server/getServerErrorFromUnknown";
import type { CustomNextApiHandler } from "@calcom/lib/server/username";
import { usernameHandler } from "@calcom/lib/server/username";
import { getTrackingFromCookies } from "@calcom/lib/tracking";
-import prisma from "@calcom/prisma";
+import { prisma } from "@calcom/prisma";
import {
CreationSource,
IdentityProvider,
@@ -65,6 +65,8 @@ const handler: CustomNextApiHandler = async (body, usernameStatus, query) => {
})
.parse(body);
+ const userRepository = getUserRepository();
+
const shouldLockByDefault = await checkIfEmailIsBlockedInWatchlistController({
email: _email,
organizationId: null,
@@ -103,10 +105,8 @@ const handler: CustomNextApiHandler = async (body, usernameStatus, query) => {
});
if (foundToken?.teamId) {
- const existingUser = await prisma.user.findUnique({
- where: { email },
- select: { invitedTo: true },
- });
+ const existingUser = await userRepository.findByEmailWithInvitedTo({email})
+
if (existingUser && existingUser.invitedTo !== foundToken.teamId) {
return NextResponse.json({ message: SIGNUP_ERROR_CODES.USER_ALREADY_EXISTS }, { status: 409 });
}
@@ -197,14 +197,11 @@ const handler: CustomNextApiHandler = async (body, usernameStatus, query) => {
const organizationId = team.isOrganization ? team.id : (team.parent?.id ?? null);
if (username) {
- const existingUserByUsername = await prisma.user.findFirst({
- where: {
- username,
- organizationId,
- NOT: { email },
- },
- select: { id: true },
- });
+ const existingUserByUsername = await userRepository.findByUsernameAndOrganizationId({
+ username,
+ organizationId,
+ excludeEmail: email
+ })
if (existingUserByUsername) {
return NextResponse.json({ message: SIGNUP_ERROR_CODES.USER_ALREADY_EXISTS }, { status: 409 });
}
@@ -212,30 +209,14 @@ const handler: CustomNextApiHandler = async (body, usernameStatus, query) => {
let user: { id: number };
try {
- user = await prisma.user.upsert({
- where: { email },
- update: {
- username,
- emailVerified: new Date(Date.now()),
- identityProvider: IdentityProvider.CAL,
- password: {
- upsert: {
- create: { hash: hashedPassword },
- update: { hash: hashedPassword },
- },
- },
- organizationId,
- },
- create: {
- username,
- email,
- emailVerified: new Date(Date.now()),
- identityProvider: IdentityProvider.CAL,
- password: { create: { hash: hashedPassword } },
- organizationId,
- },
- select: { id: true },
- });
+ user = await userRepository.upsertForSignup({
+ email,
+ username,
+ hashedPassword,
+ organizationId,
+ emailVerified: new Date(),
+ identityProvider: IdentityProvider.CAL
+ })
} catch (error) {
if (isPrismaError(error) && error.code === "P2002") {
const target = String(error.meta?.target ?? "");
@@ -269,19 +250,19 @@ const handler: CustomNextApiHandler = async (body, usernameStatus, query) => {
} else {
// Create the user
try {
- await prisma.user.create({
- data: {
- username,
- email,
- locked: shouldLockByDefault,
- password: { create: { hash: hashedPassword } },
- metadata: {
- stripeCustomerId: customer.stripeCustomerId,
- checkoutSessionId,
- },
- creationSource: CreationSource.WEBAPP,
- },
- });
+ await userRepository.create({
+ username,
+ email,
+ hashedPassword,
+ organizationId: null,
+ creationSource: CreationSource.WEBAPP,
+ locked: shouldLockByDefault,
+ identityProvider: IdentityProvider.CAL,
+ metadata: {
+ stripeCustomerId: customer.stripeCustomerId,
+ checkoutSessionId,
+ }
+ })
} catch (error) {
// Fallback for race conditions where user was created between our check and create
if (isPrismaError(error) && error.code === "P2002") {
@@ -316,7 +297,6 @@ const handler: CustomNextApiHandler = async (body, usernameStatus, query) => {
});
}
- const userRepository = new UserRepository(prisma);
await userRepository.lockByEmail({ email });
return NextResponse.json(
diff --git a/apps/web/app/api/auth/signup/handlers/selfHostedHandler.ts b/apps/web/app/api/auth/signup/handlers/selfHostedHandler.ts
index 9bea17ef643..e484e87b75a 100644
--- a/apps/web/app/api/auth/signup/handlers/selfHostedHandler.ts
+++ b/apps/web/app/api/auth/signup/handlers/selfHostedHandler.ts
@@ -16,14 +16,18 @@ import logger from "@calcom/lib/logger";
import { isPrismaError } from "@calcom/lib/server/getServerErrorFromUnknown";
import { isUsernameReservedDueToMigration } from "@calcom/lib/server/username";
import slugify from "@calcom/lib/slugify";
-import prisma from "@calcom/prisma";
+import { prisma } from "@calcom/prisma";
import { IdentityProvider } from "@calcom/prisma/enums";
import { signupSchema } from "@calcom/prisma/zod-utils";
import { NextResponse } from "next/server";
+import { getUserRepository } from "@calcom/features/di/containers/UserRepository";
+import { CreationSource } from "@calcom/prisma/enums";
export default async function handler(body: Record<string, string>) {
const { email, password, language, token } = signupSchema.parse(body);
+ const userRepository = getUserRepository()
+
const username = slugify(body.username);
const userEmail = email.toLowerCase();
@@ -44,10 +48,10 @@ export default async function handler(body: Record<string, string>) {
});
if (foundToken?.teamId) {
- const existingUser = await prisma.user.findUnique({
- where: { email: userEmail },
- select: { invitedTo: true },
- });
+ const existingUser = await userRepository.findByEmailWithInvitedTo({
+ email: userEmail
+ })
+
if (existingUser && existingUser.invitedTo !== foundToken.teamId) {
return NextResponse.json({ message: SIGNUP_ERROR_CODES.USER_ALREADY_EXISTS }, { status: 409 });
}
@@ -100,44 +104,26 @@ export default async function handler(body: Record<string, string>) {
const organizationId = team.isOrganization ? team.id : (team.parent?.id ?? null);
- const existingUserByUsername = await prisma.user.findFirst({
- where: {
- username: correctedUsername,
- organizationId,
- NOT: { email: userEmail },
- },
- select: { id: true },
- });
+ const existingUserByUsername = await userRepository.findByUsernameAndOrganizationId({
+ username: correctedUsername,
+ organizationId,
+ excludeEmail: userEmail
+ })
+
if (existingUserByUsername) {
return NextResponse.json({ message: SIGNUP_ERROR_CODES.USER_ALREADY_EXISTS }, { status: 409 });
}
let user: { id: number };
try {
- user = await prisma.user.upsert({
- where: { email: userEmail },
- update: {
- username: correctedUsername,
- emailVerified: new Date(Date.now()),
- identityProvider: IdentityProvider.CAL,
- password: {
- upsert: {
- create: { hash: hashedPassword },
- update: { hash: hashedPassword },
- },
- },
- organizationId,
- },
- create: {
- username: correctedUsername,
- email: userEmail,
- emailVerified: new Date(Date.now()),
- identityProvider: IdentityProvider.CAL,
- password: { create: { hash: hashedPassword } },
- organizationId,
- },
- select: { id: true },
- });
+ user = await userRepository.upsertForSignup({
+ email: userEmail,
+ username: correctedUsername,
+ hashedPassword,
+ organizationId,
+ emailVerified: new Date(Date.now()),
+ identityProvider: IdentityProvider.CAL
+ })
} catch (error) {
if (isPrismaError(error) && error.code === "P2002") {
const target = String(error.meta?.target ?? "");
@@ -174,15 +160,15 @@ export default async function handler(body: Record<string, string>) {
return NextResponse.json({ message: "A user exists with that username" }, { status: 409 });
}
try {
- await prisma.user.create({
- data: {
- username: correctedUsername,
- email: userEmail,
- password: { create: { hash: hashedPassword } },
- identityProvider: IdentityProvider.CAL,
- },
- select: { id: true },
- });
+ await userRepository.create({
+ username: correctedUsername,
+ email: userEmail,
+ hashedPassword,
+ organizationId: null,
+ creationSource: CreationSource.WEBAPP,
+ identityProvider: IdentityProvider.CAL,
+ locked: false
+ })
} catch (error) {
// Fallback for race conditions where user was created between our check and create
if (isPrismaError(error) && error.code === "P2002") {
diff --git a/packages/features/di/containers/UserRepository.ts b/packages/features/di/containers/UserRepository.ts
new file mode 100644
index 00000000000..ff3b38f98f9
--- /dev/null
+++ b/packages/features/di/containers/UserRepository.ts
@@ -0,0 +1,10 @@
+import { createContainer } from "@calcom/features/di/di";
+import { moduleLoader as userRepositoryModuleLoader } from "@calcom/features/di/modules/User";
+import type { UserRepository } from "@calcom/features/users/repositories/UserRepository";
+
+const userRepositoryContainer = createContainer();
+
+export function getUserRepository(): UserRepository {
+ userRepositoryModuleLoader.loadModule(userRepositoryContainer);
+ return userRepositoryContainer.get<UserRepository>(userRepositoryModuleLoader.token);
+}
diff --git a/packages/features/users/repositories/UserRepository.integration-test.ts b/packages/features/users/repositories/UserRepository.integration-test.ts
new file mode 100644
index 00000000000..3b09577b9e3
--- /dev/null
+++ b/packages/features/users/repositories/UserRepository.integration-test.ts
@@ -0,0 +1,236 @@
+import { afterEach, beforeAll, describe, expect, it } from "vitest";
+import { UserRepository } from "./UserRepository";
+import { getUserRepository } from "@calcom/features/di/containers/UserRepository";
+import { IdentityProvider } from "@calcom/prisma/enums";
+import bcrypt from "bcryptjs";
+
+const testRunId = `${Date.now()}-${Math.random().toString(36).substring(2, 8)}`;
+const createdUserIds: number[] = [];
+
+describe("UserRepository Integration Tests - Signup Methods", () => {
+ let userRepository: UserRepository;
+
+ async function cleanupTestUsers() {
+ if (createdUserIds.length > 0) {
+ await userRepository.deleteMany({ userIds: createdUserIds })
+ createdUserIds.length = 0
+ }
+ }
+
+ beforeAll(async () => {
+ userRepository = getUserRepository();
+ });
+
+ afterEach(async () => {
+ await cleanupTestUsers();
+ });
+
+ describe("upsertForSignup", () => {
+ it("should create a new user when email doesn't exist", async () => {
+ const testEmail = `signup-new-${testRunId}@example.com`;
+ const hashedPassword = await bcrypt.hash("password123", 10);
+
+ const result = await userRepository.upsertForSignup({
+ email: testEmail,
+ username: `signupuser-${testRunId}`,
+ hashedPassword,
+ organizationId: null,
+ emailVerified: new Date(Date.now()),
+ identityProvider: IdentityProvider.CAL,
+ });
+
+ expect(result).not.toBeNull();
+ expect(result.id).toBeDefined();
+ createdUserIds.push(result.id);
+
+ const createdUser = await userRepository.findByEmail({ email: testEmail});
+
+ expect(createdUser).not.toBeNull();
+ expect(createdUser?.email).toBe(testEmail);
+ expect(createdUser?.emailVerified).not.toBeNull();
+ });
+
+ it("should update existing user's credentials on upsert", async () => {
+ const testEmail = `signup-update-${testRunId}@example.com`;
+ const hashedPassword1 = await bcrypt.hash("password123", 10);
+ const hashedPassword2 = await bcrypt.hash("newpassword456", 10);
+
+ const user1 = await userRepository.upsertForSignup({
+ email: testEmail,
+ username: `user-${testRunId}`,
+ hashedPassword: hashedPassword1,
+ organizationId: null,
+ emailVerified: new Date(Date.now() - 86400000),
+ identityProvider: IdentityProvider.CAL,
+ });
+ createdUserIds.push(user1.id);
+
+ const user2 = await userRepository.upsertForSignup({
+ email: testEmail,
+ username: `user-${testRunId}-updated`,
+ hashedPassword: hashedPassword2,
+ organizationId: null,
+ emailVerified: new Date(),
+ identityProvider: IdentityProvider.CAL,
+ });
+
+ expect(user2.id).toBe(user1.id);
+
+ const updatedUser = await userRepository.findByEmailAndIncludeProfilesAndPassword({ email: testEmail});
+
+ expect(updatedUser?.username).toBe(`user-${testRunId}-updated`);
+ expect(updatedUser?.password?.hash).toBe(hashedPassword2);
+ });
+
+ it("should preserve user ID on upsert", async () => {
+ const testEmail = `signup-preserve-${testRunId}@example.com`;
+ const hashedPassword = await bcrypt.hash("password123", 10);
+
+ const user1 = await userRepository.upsertForSignup({
+ email: testEmail,
+ username: `user-${testRunId}-p1`,
+ hashedPassword,
+ organizationId: null,
+ emailVerified: new Date(),
+ identityProvider: IdentityProvider.CAL,
+ });
+ createdUserIds.push(user1.id);
+ const initialId = user1.id;
+
+ const user2 = await userRepository.upsertForSignup({
+ email: testEmail,
+ username: `user-${testRunId}-p2`,
+ hashedPassword,
+ organizationId: null,
+ emailVerified: new Date(),
+ identityProvider: IdentityProvider.CAL,
+ });
+
+ expect(user2.id).toBe(initialId);
+ });
+
+ it("should set email as verified on signup", async () => {
+ const testEmail = `signup-verified-${testRunId}@example.com`;
+ const hashedPassword = await bcrypt.hash("password123", 10);
+ const verificationDate = new Date();
+
+ const result = await userRepository.upsertForSignup({
+ email: testEmail,
+ username: `user-${testRunId}-v1`,
+ hashedPassword,
+ organizationId: null,
+ emailVerified: verificationDate,
+ identityProvider: IdentityProvider.CAL,
+ });
+ createdUserIds.push(result.id);
+
+ const user = await userRepository.findByEmail({ email: testEmail });
+
+ if (!user) {
+ throw new Error("User was not found after signup");
+ }
+
+ expect(user?.emailVerified).not.toBeNull();
+ expect(user?.emailVerified?.getTime()).toBe(verificationDate.getTime());
+ });
+
+ it("should create password record for new user", async () => {
+ const testEmail = `signup-pwd-${testRunId}@example.com`;
+ const hashedPassword = await bcrypt.hash("password123", 10);
+
+ const result = await userRepository.upsertForSignup({
+ email: testEmail,
+ username: `user-${testRunId}-pwd`,
+ hashedPassword,
+ organizationId: null,
+ emailVerified: new Date(),
+ identityProvider: IdentityProvider.CAL,
+ });
+ createdUserIds.push(result.id);
+
+ const userWithPassword = await userRepository.findByEmailAndIncludeProfilesAndPassword({ email: testEmail })
+
+ if (!userWithPassword) {
+ throw new Error("User was not found after signup");
+ }
+
+ expect(userWithPassword?.password).not.toBeNull();
+ expect(userWithPassword?.password?.hash).toBe(hashedPassword);
+ expect(userWithPassword?.password?.userId).toBe(result.id);
+ });
+
+ it("should throw error on duplicate unique constraint if username exists", async () => {
+ const testEmail1 = `signup-dup1-${testRunId}@example.com`;
+ const testEmail2 = `signup-dup2-${testRunId}@example.com`;
+ const duplicateUsername = `dupuser-${testRunId}`;
+ const hashedPassword = await bcrypt.hash("password123", 10);
+
+ const user1 = await userRepository.upsertForSignup({
+ email: testEmail1,
+ username: duplicateUsername,
+ hashedPassword,
+ organizationId: null,
+ emailVerified: new Date(),
+ identityProvider: IdentityProvider.CAL,
+ });
+ createdUserIds.push(user1.id);
+
+ await expect(
+ userRepository.upsertForSignup({
+ email: testEmail2,
+ username: duplicateUsername,
+ hashedPassword,
+ organizationId: null,
+ emailVerified: new Date(),
+ identityProvider: IdentityProvider.CAL,
+ })
+ ).rejects.toThrow();
+ });
+ });
+
+ describe("Integration: Individual Signup flow", () => {
+ it("should complete full individual signup flow: check email, check username, then upsert", async () => {
+ const testEmail = `flow-${testRunId}@example.com`;
+ const testUsername = `flowuser-${testRunId}`;
+ const hashedPassword = await bcrypt.hash("password123", 10);
+
+ const existingUser = await userRepository.findByEmail({
+ email: testEmail,
+ });
+ expect(existingUser).toBeNull();
+
+ const usersWithUsername = await userRepository.findUsersByUsername({
+ orgSlug: null,
+ usernameList: [testUsername],
+ });
+ const usernameTaken = usersWithUsername.length > 0 ? usersWithUsername[0] : null;
+ expect(usernameTaken).toBeNull();
+
+ const signupResult = await userRepository.upsertForSignup({
+ email: testEmail,
+ username: testUsername,
+ hashedPassword,
+ organizationId: null,
+ emailVerified: new Date(Date.now()),
+ identityProvider: IdentityProvider.CAL,
+ });
+ createdUserIds.push(signupResult.id);
+
+ expect(signupResult.id).toBeDefined();
+
+ const userWithPassword = await userRepository.findByEmailAndIncludeProfilesAndPassword({ email: testEmail })
+
+ if (!userWithPassword) {
+ throw new Error("User was not found after signup");
+ }
+
+ expect(userWithPassword?.email).toBe(testEmail);
+ expect(userWithPassword?.username).toBe(testUsername);
+ expect(userWithPassword?.password).not.toBeNull();
+
+ const userWithOrganizationId = await userRepository.getUserOrganizationAndTeams({ userId: userWithPassword.id});
+
+ expect(userWithOrganizationId?.organizationId).toBeNull();
+ });
+});
+});
diff --git a/packages/features/users/repositories/UserRepository.ts b/packages/features/users/repositories/UserRepository.ts
index 24878a56846..d5c26676d8f 100644
--- a/packages/features/users/repositories/UserRepository.ts
+++ b/packages/features/users/repositories/UserRepository.ts
@@ -9,6 +9,7 @@ import type { PrismaClient } from "@calcom/prisma";
import { availabilityUserSelect } from "@calcom/prisma";
import type { DestinationCalendar, SelectedCalendar, User as UserType } from "@calcom/prisma/client";
import { Prisma } from "@calcom/prisma/client";
+import type { IdentityProvider } from "@calcom/prisma/enums";
import type { CreationSource } from "@calcom/prisma/enums";
import { BookingStatus, MembershipRole } from "@calcom/prisma/enums";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
@@ -896,20 +897,19 @@ export class UserRepository {
async create(
data: Omit<Prisma.UserCreateInput, "password" | "organization" | "movedToProfile"> & {
- username: string;
+ username: string | null;
hashedPassword?: string;
organizationId: number | null;
creationSource: CreationSource;
locked: boolean;
}
) {
- const organizationIdValue = data.organizationId;
- const { email, username, creationSource, locked, hashedPassword, ...rest } = data;
+ const { email, username, creationSource, locked, hashedPassword, organizationId, ...rest } = data;
- logger.info("create user", {
+ log.info("create user", {
email,
username,
- organizationIdValue,
+ organizationId,
locked,
});
const t = await getTranslation("en", "common");
@@ -939,13 +939,13 @@ export class UserRepository {
},
creationSource,
locked,
- ...(organizationIdValue
+ ...(organizationId && username
? {
- organizationId: organizationIdValue,
+ organizationId,
profiles: {
create: {
username,
- organizationId: organizationIdValue,
+ organizationId,
uid: ProfileRepository.generateProfileUid(),
},
},
@@ -1419,6 +1419,14 @@ export class UserRepository {
});
}
+ async deleteMany({ userIds }: {userIds: number[]}){
+ await this.prismaClient.user.deleteMany({
+ where: {
+ id: { in: userIds },
+ },
+ });
+ }
+
/**
* Finds a user by ID returning only their username
* @param userId - The user ID
@@ -1480,6 +1488,38 @@ export class UserRepository {
});
}
+ async findByEmailWithInvitedTo({ email }: { email: string } ) {
+ return this.prismaClient.user.findUnique({
+ where: {
+ email: email.toLowerCase()
+ },
+ select: {
+ invitedTo: true
+ }
+ })
+ }
+
+ async findByUsernameAndOrganizationId({
+ username,
+ organizationId,
+ excludeEmail,
+ }: {
+ username: string,
+ organizationId: number | null,
+ excludeEmail: string
+ }) {
+ return this.prismaClient.user.findFirst({
+ where: {
+ username,
+ organizationId,
+ NOT: { email: excludeEmail }
+ },
+ select: {
+ id: true
+ }
+ })
+ }
+
async lockByEmail({ email }: { email: string }) {
await this.prismaClient.user.updateMany({
where: { email },
@@ -1506,4 +1546,45 @@ export class UserRepository {
return { email: user.email, username: user.username };
}
+
+ async upsertForSignup({
+ email,
+ username,
+ hashedPassword,
+ organizationId,
+ emailVerified,
+ identityProvider,
+ }: {
+ email: string;
+ username: string | null;
+ hashedPassword: string;
+ organizationId: number | null;
+ emailVerified: Date;
+ identityProvider: IdentityProvider;
+ }) {
+ return this.prismaClient.user.upsert({
+ where: { email },
+ update: {
+ username,
+ emailVerified,
+ identityProvider,
+ password: {
+ upsert: {
+ create: { hash: hashedPassword },
+ update: { hash: hashedPassword },
+ },
+ },
+ organizationId,
+ },
+ create: {
+ username,
+ email,
+ emailVerified,
+ identityProvider,
+ password: { create: { hash: hashedPassword } },
+ organizationId,
+ },
+ select: { id: true },
+ });
+ }
}