2021-08-18 11:52:25 +00:00
|
|
|
import type { NextApiRequest, NextApiResponse } from "next";
|
2021-09-22 19:52:38 +00:00
|
|
|
|
2023-03-10 23:45:24 +00:00
|
|
|
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";
|
2022-07-28 19:58:26 +00:00
|
|
|
import prisma from "@calcom/prisma";
|
2023-05-02 11:44:05 +00:00
|
|
|
import { IdentityProvider } from "@calcom/prisma/enums";
|
2022-07-28 19:58:26 +00:00
|
|
|
|
2021-04-07 15:03:02 +00:00
|
|
|
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
2023-03-10 23:45:24 +00:00
|
|
|
const session = await getServerSession({ req, res });
|
2021-08-19 12:27:01 +00:00
|
|
|
|
2022-01-13 20:05:23 +00:00
|
|
|
if (!session || !session.user || !session.user.email) {
|
2021-08-19 12:27:01 +00:00
|
|
|
res.status(401).json({ message: "Not authenticated" });
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const user = await prisma.user.findFirst({
|
|
|
|
where: {
|
|
|
|
email: session.user.email,
|
|
|
|
},
|
|
|
|
select: {
|
|
|
|
id: true,
|
|
|
|
password: true,
|
2022-01-13 20:05:23 +00:00
|
|
|
identityProvider: true,
|
2021-08-19 12:27:01 +00:00
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
if (!user) {
|
|
|
|
res.status(404).json({ message: "User not found" });
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2022-01-13 20:05:23 +00:00
|
|
|
if (user.identityProvider !== IdentityProvider.CAL) {
|
|
|
|
return res.status(400).json({ error: ErrorCode.ThirdPartyIdentityProviderEnabled });
|
|
|
|
}
|
|
|
|
|
2021-08-19 12:27:01 +00:00
|
|
|
const oldPassword = req.body.oldPassword;
|
|
|
|
const newPassword = req.body.newPassword;
|
2021-09-21 09:29:20 +00:00
|
|
|
|
2021-08-19 12:27:01 +00:00
|
|
|
const currentPassword = user.password;
|
2021-09-21 09:29:20 +00:00
|
|
|
if (!currentPassword) {
|
|
|
|
return res.status(400).json({ error: ErrorCode.UserMissingPassword });
|
|
|
|
}
|
2021-08-19 12:27:01 +00:00
|
|
|
|
|
|
|
const passwordsMatch = await verifyPassword(oldPassword, currentPassword);
|
|
|
|
if (!passwordsMatch) {
|
2021-09-21 09:29:20 +00:00
|
|
|
return res.status(403).json({ error: ErrorCode.IncorrectPassword });
|
2021-08-19 12:27:01 +00:00
|
|
|
}
|
|
|
|
|
2021-09-21 09:29:20 +00:00
|
|
|
if (oldPassword === newPassword) {
|
|
|
|
return res.status(400).json({ error: ErrorCode.NewPasswordMatchesOld });
|
|
|
|
}
|
2021-08-19 12:27:01 +00:00
|
|
|
|
2021-09-21 09:29:20 +00:00
|
|
|
const hashedPassword = await hashPassword(newPassword);
|
2021-08-19 12:27:01 +00:00
|
|
|
await prisma.user.update({
|
|
|
|
where: {
|
|
|
|
id: user.id,
|
|
|
|
},
|
|
|
|
data: {
|
|
|
|
password: hashedPassword,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
res.status(200).json({ message: "Password updated successfully" });
|
|
|
|
}
|