chore: migrate forgot-password, reset-password, auth/setup apis to App Router (#19512)

* chore: migrate /api/auth/changepw

* migrate forgot-password and reset-password

* remove unneeded export

* rename request to req for easier review

* migrate auth/setup

* remove setup

* refactor

* remove redundant code

* fix

* remove changepw api and unused ui
This commit is contained in:
Benny Joo authored and GitHub committed 2025-03-07 14:43:36 -07:00
1 parent 33226f268d
commit ae659b5176
5 files changed
+33 -215

No files matched your search

-70
View File
@@ -1,70 +0,0 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { ErrorCode } from "@calcom/features/auth/lib/ErrorCode";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { hashPassword } from "@calcom/features/auth/lib/hashPassword";
import { verifyPassword } from "@calcom/features/auth/lib/verifyPassword";
import prisma from "@calcom/prisma";
import { IdentityProvider } from "@calcom/prisma/enums";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const session = await getServerSession({ req });
if (!session || !session.user || !session.user.email) {
res.status(401).json({ message: "Not authenticated" });
return;
}
const user = await prisma.user.findFirst({
where: {
email: session.user.email,
},
select: {
id: true,
password: true,
identityProvider: true,
},
});
if (!user) {
res.status(404).json({ message: "User not found" });
return;
}
if (user.identityProvider !== IdentityProvider.CAL) {
return res.status(400).json({ error: ErrorCode.ThirdPartyIdentityProviderEnabled });
}
const oldPassword = req.body.oldPassword;
const newPassword = req.body.newPassword;
const currentPassword = user.password?.hash;
if (!currentPassword) {
return res.status(400).json({ error: ErrorCode.UserMissingPassword });
}
const passwordsMatch = await verifyPassword(oldPassword, currentPassword);
if (!passwordsMatch) {
return res.status(403).json({ error: ErrorCode.IncorrectPassword });
}
if (oldPassword === newPassword) {
return res.status(400).json({ error: ErrorCode.NewPasswordMatchesOld });
}
const hashedPassword = await hashPassword(newPassword);
await prisma.userPassword.upsert({
where: {
userId: user.id,
},
create: {
hash: hashedPassword,
userId: user.id,
},
update: {
hash: hashedPassword,
},
});
res.status(200).json({ message: "Password updated successfully" });
}
@@ -1,48 +0,0 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { passwordResetRequest } from "@calcom/features/auth/lib/passwordResetRequest";
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
import { emailSchema } from "@calcom/lib/emailSchema";
import { defaultHandler } from "@calcom/lib/server/defaultHandler";
import prisma from "@calcom/prisma";
async function handler(req: NextApiRequest, res: NextApiResponse) {
const email = emailSchema.transform((val) => val.toLowerCase()).safeParse(req.body?.email);
if (!email.success) {
return res.status(400).json({ message: "email is required" });
}
// fallback to email if ip is not present
let ip = (req.headers["x-real-ip"] as string) ?? email.data;
const forwardedFor = req.headers["x-forwarded-for"] as string;
if (!ip && forwardedFor) {
ip = forwardedFor?.split(",").at(0) ?? email.data;
}
// 10 requests per minute
await checkRateLimitAndThrowError({
rateLimitingType: "core",
identifier: ip,
});
try {
const user = await prisma.user.findUnique({
where: { email: email.data },
select: { name: true, email: true, locale: true },
});
// Don't leak info about whether the user exists
if (!user) return res.status(201).json({ message: "password_reset_email_sent" });
await passwordResetRequest(user);
return res.status(201).json({ message: "password_reset_email_sent" });
} catch (reason) {
console.error(reason);
return res.status(500).json({ message: "Unable to create password reset request" });
}
}
export default defaultHandler({
POST: Promise.resolve({ default: handler }),
});
-75
View File
@@ -1,75 +0,0 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { z } from "zod";
import { hashPassword } from "@calcom/features/auth/lib/hashPassword";
import { validPassword } from "@calcom/features/auth/lib/validPassword";
import prisma from "@calcom/prisma";
import { IdentityProvider } from "@calcom/prisma/enums";
const passwordResetRequestSchema = z.object({
password: z.string().refine(validPassword, () => ({
message: "Password does not meet the requirements",
})),
requestId: z.string(), // format doesn't matter.
});
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
// Bad Method when not POST
if (req.method !== "POST") return res.status(405).end();
const { password: rawPassword, requestId: rawRequestId } = passwordResetRequestSchema.parse(req.body);
// rate-limited there is a low, very low chance that a password request stays valid long enough
// to brute force 3.8126967e+40 options.
const maybeRequest = await prisma.resetPasswordRequest.findFirstOrThrow({
where: {
id: rawRequestId,
expires: {
gt: new Date(),
},
},
select: {
email: true,
},
});
const hashedPassword = await hashPassword(rawPassword);
// this can fail if a password request has been made for an email that has since changed or-
// never existed within Cal. In this case we do not want to disclose the email's existence.
// instead, we just return 404
try {
await prisma.user.update({
where: {
email: maybeRequest.email,
},
data: {
password: {
upsert: {
create: { hash: hashedPassword },
update: { hash: hashedPassword },
},
},
emailVerified: new Date(),
identityProvider: IdentityProvider.CAL,
identityProviderId: null,
},
});
} catch (e) {
return res.status(404).end();
}
await expireResetPasswordRequest(rawRequestId);
return res.status(201).json({ message: "Password reset." });
}
async function expireResetPasswordRequest(rawRequestId: string) {
await prisma.resetPasswordRequest.update({
where: {
id: rawRequestId,
},
data: {
// We set the expiry to now to invalidate the request
expires: new Date(),
},
});
}
-62
View File
@@ -1,62 +0,0 @@
import type { NextApiRequest } from "next";
import z from "zod";
import { hashPassword } from "@calcom/features/auth/lib/hashPassword";
import { isPasswordValid } from "@calcom/features/auth/lib/isPasswordValid";
import { emailRegex } from "@calcom/lib/emailSchema";
import { HttpError } from "@calcom/lib/http-error";
import { defaultHandler } from "@calcom/lib/server/defaultHandler";
import { defaultResponder } from "@calcom/lib/server/defaultResponder";
import slugify from "@calcom/lib/slugify";
import prisma from "@calcom/prisma";
import { IdentityProvider } from "@calcom/prisma/enums";
import { CreationSource } from "@calcom/prisma/enums";
const querySchema = z.object({
username: z
.string()
.refine((val) => val.trim().length >= 1, { message: "Please enter at least one character" }),
full_name: z.string().min(3, "Please enter at least 3 characters"),
email_address: z.string().regex(emailRegex, { message: "Please enter a valid email" }),
password: z.string().refine((val) => isPasswordValid(val.trim(), false, true), {
message:
"The password must be a minimum of 15 characters long containing at least one number and have a mixture of uppercase and lowercase letters",
}),
});
async function handler(req: NextApiRequest) {
const userCount = await prisma.user.count();
if (userCount !== 0) {
throw new HttpError({ statusCode: 400, message: "No setup needed." });
}
const parsedQuery = querySchema.safeParse(req.body);
if (!parsedQuery.success) {
throw new HttpError({ statusCode: 422, message: parsedQuery.error.message });
}
const username = slugify(parsedQuery.data.username.trim());
const userEmail = parsedQuery.data.email_address.toLowerCase();
const hashedPassword = await hashPassword(parsedQuery.data.password);
await prisma.user.create({
data: {
username,
email: userEmail,
password: { create: { hash: hashedPassword } },
role: "ADMIN",
name: parsedQuery.data.full_name,
emailVerified: new Date(),
locale: "en", // TODO: We should revisit this
identityProvider: IdentityProvider.CAL,
creationSource: CreationSource.WEBAPP,
},
});
return { message: "First admin user created successfully." };
}
export default defaultHandler({
POST: Promise.resolve({ default: defaultResponder(handler) }),
});