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:
1 parent
33226f268d
commit
ae659b5176
5 files changed
+33
-215
No files matched your search
@@ -0,0 +1,49 @@
|
||||
import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { passwordResetRequest } from "@calcom/features/auth/lib/passwordResetRequest";
|
||||
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
|
||||
import { emailSchema } from "@calcom/lib/emailSchema";
|
||||
import prisma from "@calcom/prisma";
|
||||
|
||||
async function handler(req: NextRequest) {
|
||||
const email = emailSchema.transform((val) => val.toLowerCase()).safeParse((await req.json())?.email);
|
||||
|
||||
if (!email.success) {
|
||||
return NextResponse.json({ message: "email is required" }, { status: 400 });
|
||||
}
|
||||
|
||||
// fallback to email if ip is not present
|
||||
let ip = (req.headers.get("x-real-ip") as string) ?? email.data;
|
||||
|
||||
const forwardedFor = req.headers.get("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 NextResponse.json({ message: "password_reset_email_sent" }, { status: 201 });
|
||||
await passwordResetRequest(user);
|
||||
return NextResponse.json({ message: "password_reset_email_sent" }, { status: 201 });
|
||||
} catch (reason) {
|
||||
console.error(reason);
|
||||
return NextResponse.json({ message: "Unable to create password reset request" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
const postHandler = defaultResponderForAppDir(handler);
|
||||
|
||||
export { postHandler as POST };
|
||||
@@ -0,0 +1,77 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
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.
|
||||
});
|
||||
|
||||
async function handler(req: NextRequest) {
|
||||
const { password: rawPassword, requestId: rawRequestId } = passwordResetRequestSchema.parse(
|
||||
await req.json()
|
||||
);
|
||||
// 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 NextResponse.json({}, { status: 404 });
|
||||
}
|
||||
|
||||
await expireResetPasswordRequest(rawRequestId);
|
||||
|
||||
return NextResponse.json({ message: "Password reset." }, { status: 201 });
|
||||
}
|
||||
|
||||
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(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export { handler as POST };
|
||||
@@ -0,0 +1,62 @@
|
||||
import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
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 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: NextRequest) {
|
||||
const userCount = await prisma.user.count();
|
||||
if (userCount !== 0) {
|
||||
throw new HttpError({ statusCode: 400, message: "No setup needed." });
|
||||
}
|
||||
|
||||
const parsedQuery = querySchema.safeParse(await req.json());
|
||||
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 NextResponse.json({ message: "First admin user created successfully." });
|
||||
}
|
||||
|
||||
const postHandler = defaultResponderForAppDir(handler);
|
||||
|
||||
export { postHandler as POST };
|
||||
Reference in new issue
Block a user