{"size": 1361, "ext": "js", "max_stars_repo_path": "pages/api/user/change-password.js", "max_stars_repo_name": "mrefil/it-kariyer", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pages/api/user/change-password.js", "max_issues_repo_name": "mrefil/it-kariyer", "max_issues_repo_issues_event_min_datetime": "2022-01-13T11:14:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-17T19:59:23.000Z", "max_forks_repo_path": "pages/api/user/change-password.js", "max_forks_repo_name": "mrefil/it-kariyer", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": 10, "max_forks_count": null, "avg_line_length": 24.7454545455, "max_line_length": 78, "alphanum_fraction": 0.6531961793}
import { getSession } from "next-auth/client";
import { hashPassword, verifyPassword } from "../../../lib/auth";
import { connectToDatabase } from "../../../lib/db";

async function handler(req, res) {
  if (req.method !== "PATCH") {
    return;
  }

  const session = await getSession({ req: req });

  if (!session) {
    res.status(401).json({ message: "Not Authenticated!" });
    return;
  }

  const userEmail = session.user.email;
  const oldPassword = req.body.oldPassword;
  const newPassword = req.body.newPassword;

  const client = await connectToDatabase();
  const userCollection = client.db().collection("users");
  const user = await userCollection.findOne({ email: userEmail });

  if (!user) {
    res.status(404).json({ message: "User not found!" });
    client.close();
    return;
  }

  const currenPassword = user.password;
  const passwordsAreEqual = await verifyPassword(oldPassword, currenPassword);

  if (!passwordsAreEqual) {
    res.status(403).json({ message: "Invalid password." });
    client.close();
    return;
  }

  const hashedPassword = await hashPassword(newPassword);

  const result = await userCollection.updateOne(
    { email: userEmail },
    {
      $set: {
        password: hashedPassword,
      },
    }
  );
  client.close();
  res.status(200).json({message: 'Password Updated.'});
}

export default handler;
