Files
cal.diy/apps/web/app/api/auth/signup/handlers/selfHostedHandler.ts
T
Benny JooandDevin AI ab21c7f805 refactor: Cal.diy (#28903)
* feat: Cal.diy — community-driven MIT-licensed fork of Cal.com

This squashed commit contains all Cal.diy changes applied on top of calcom/cal.com main:

- Rebrand Cal.com to Cal.diy across the entire codebase
- Remove Enterprise Edition (EE) features, license checks, and AGPL restrictions
- Switch license from AGPL-3.0 to MIT
- Remove docs/ directory (migrated to Nextra at cal.diy)
- Remove dead code: org tests, EE tips, platform nav, premium username, SAML/SSO, etc.
- Clean up .env.example for self-hosted Cal.diy
- Update Docker image references to calcom/cal.diy
- Update README, CONTRIBUTING.md, and issue templates for Cal.diy community fork
- Add PR welcome bot for Cal.diy contributors
- Fix API v2 breaking changes oasdiff ignore entries
- Replace Blacksmith CI runners with default GitHub Actions

3893 files changed, 20789 insertions(+), 411020 deletions(-)

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* refactor: remove org-specific /organizations/:orgId endpoints from API v2 atoms controllers (#1701)

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix: revert Cal.diy Inc to Cal.com, Inc. in license files, copyright notices, and package metadata (#1702)

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* rip out org related comments in api v2

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-04-15 09:52:36 -03:00

210 lines
7.0 KiB
TypeScript

import process from "node:process";
import { sendEmailVerification } from "@calcom/features/auth/lib/verifyEmail";
import { SIGNUP_ERROR_CODES } from "@calcom/features/auth/signup/constants";
import { createOrUpdateMemberships } from "@calcom/features/auth/signup/utils/createOrUpdateMemberships";
import { joinAnyChildTeamOnOrgInvite } from "@calcom/features/auth/signup/utils/organization";
import { prefillAvatar } from "@calcom/features/auth/signup/utils/prefillAvatar";
import {
findTokenByToken,
throwIfTokenExpired,
validateAndGetCorrectedUsernameForTeam,
} from "@calcom/features/auth/signup/utils/token";
import { validateAndGetCorrectedUsernameAndEmail } from "@calcom/features/auth/signup/utils/validateUsername";
import { hashPassword } from "@calcom/lib/auth/hashPassword";
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 { IdentityProvider } from "@calcom/prisma/enums";
import { signupSchema } from "@calcom/prisma/zod-utils";
import { NextResponse } from "next/server";
export default async function handler(body: Record<string, string>) {
const { email, password, language, token } = signupSchema.parse(body);
const username = slugify(body.username);
const userEmail = email.toLowerCase();
if (!username) {
return NextResponse.json({ message: "Invalid username" }, { status: 422 });
}
let foundToken: { id: number; teamId: number | null; expires: Date } | null = null;
let correctedUsername = username;
if (token) {
foundToken = await findTokenByToken({ token });
throwIfTokenExpired(foundToken?.expires);
correctedUsername = await validateAndGetCorrectedUsernameForTeam({
username,
email: userEmail,
teamId: foundToken?.teamId,
isSignup: true,
});
if (foundToken?.teamId) {
const existingUser = await prisma.user.findUnique({
where: { email: userEmail },
select: { invitedTo: true },
});
if (existingUser && existingUser.invitedTo !== foundToken.teamId) {
return NextResponse.json({ message: SIGNUP_ERROR_CODES.USER_ALREADY_EXISTS }, { status: 409 });
}
}
} else {
const userValidation = await validateAndGetCorrectedUsernameAndEmail({
username,
email: userEmail,
isSignup: true,
});
if (!userValidation.isValid) {
logger.error("User validation failed", { userValidation });
return NextResponse.json({ message: "Username or email is already taken" }, { status: 409 });
}
if (!userValidation.username) {
return NextResponse.json({ message: "Invalid username" }, { status: 422 });
}
correctedUsername = userValidation.username;
}
const hashedPassword = await hashPassword(password);
if (foundToken?.teamId) {
const team = await prisma.team.findUnique({
where: {
id: foundToken.teamId,
},
include: {
parent: {
select: {
id: true,
slug: true,
organizationSettings: true,
},
},
organizationSettings: true,
},
});
if (team) {
const isInviteForATeamInOrganization = !!team.parent;
const isCheckingUsernameInGlobalNamespace = !team.isOrganization && !isInviteForATeamInOrganization;
if (isCheckingUsernameInGlobalNamespace) {
const isUsernameAvailable = !(await isUsernameReservedDueToMigration(correctedUsername));
if (!isUsernameAvailable) {
return NextResponse.json({ message: "A user exists with that username" }, { status: 409 });
}
}
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 },
});
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 },
});
} catch (error) {
if (isPrismaError(error) && error.code === "P2002") {
const target = String(error.meta?.target ?? "");
if (target.includes("email") || target.includes("username")) {
return NextResponse.json({ message: SIGNUP_ERROR_CODES.USER_ALREADY_EXISTS }, { status: 409 });
}
}
throw error;
}
await createOrUpdateMemberships({
user,
team,
});
// Accept any child team invites for orgs.
if (team.parent) {
await joinAnyChildTeamOnOrgInvite({
userId: user.id,
org: team.parent,
});
}
}
// Cleanup token after use
await prisma.verificationToken.delete({
where: {
id: foundToken.id,
},
});
} else {
const isUsernameAvailable = !(await isUsernameReservedDueToMigration(correctedUsername));
if (!isUsernameAvailable) {
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 },
});
} catch (error) {
// Fallback for race conditions where user was created between our check and create
if (isPrismaError(error) && error.code === "P2002") {
const target = String(error.meta?.target ?? "");
if (target.includes("email") || target.includes("username")) {
return NextResponse.json({ message: SIGNUP_ERROR_CODES.USER_ALREADY_EXISTS }, { status: 409 });
}
}
throw error;
}
if (process.env.AVATARAPI_USERNAME && process.env.AVATARAPI_PASSWORD) {
await prefillAvatar({ email: userEmail });
}
await sendEmailVerification({
email: userEmail,
username: correctedUsername,
language,
});
}
return NextResponse.json({ message: "Created user" }, { status: 201 });
}