el.xwx.moe/pages/api/v1/auth/reset-password.ts

85 lines
2.0 KiB
TypeScript
Raw Normal View History

2024-05-18 22:57:00 -05:00
import { prisma } from "@/lib/api/db";
import type { NextApiRequest, NextApiResponse } from "next";
import bcrypt from "bcrypt";
2024-09-14 15:00:19 -05:00
import { ResetPasswordSchema } from "@/lib/shared/schemaValidation";
2024-05-18 22:57:00 -05:00
export default async function resetPassword(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method === "POST") {
2024-07-18 15:29:59 -05:00
if (process.env.NEXT_PUBLIC_DEMO === "true")
return res.status(400).json({
response:
"This action is disabled because this is a read-only demo of Linkwarden.",
});
2024-09-14 15:00:19 -05:00
const dataValidation = ResetPasswordSchema.safeParse(req.body);
2024-05-18 22:57:00 -05:00
2024-09-14 15:00:19 -05:00
if (!dataValidation.success) {
2024-05-18 22:57:00 -05:00
return res.status(400).json({
2024-09-14 15:00:19 -05:00
response: `Error: ${
dataValidation.error.issues[0].message
} [${dataValidation.error.issues[0].path.join(", ")}]`,
2024-05-18 22:57:00 -05:00
});
}
2024-09-14 15:00:19 -05:00
const { token, password } = dataValidation.data;
2024-05-18 22:57:00 -05:00
// Hashed password
const saltRounds = 10;
const hashedPassword = await bcrypt.hash(password, saltRounds);
// Check token in db
const verifyToken = await prisma.passwordResetToken.findFirst({
where: {
token,
expires: {
gt: new Date(),
},
},
});
if (!verifyToken) {
return res.status(400).json({
response: "Invalid token.",
});
}
const email = verifyToken.identifier;
// Update password
await prisma.user.update({
where: {
email,
},
data: {
password: hashedPassword,
},
});
await prisma.passwordResetToken.update({
where: {
token,
},
data: {
expires: new Date(),
},
});
// Delete tokens older than 5 minutes
await prisma.passwordResetToken.deleteMany({
where: {
identifier: email,
createdAt: {
lt: new Date(new Date().getTime() - 1000 * 60 * 5), // 5 minutes
},
},
});
return res.status(200).json({
response: "Password has been reset successfully.",
2024-05-18 22:57:00 -05:00
});
}
}