Skip to content

Commit

Permalink
ft(update-password): created function to update the password
Browse files Browse the repository at this point in the history
  • Loading branch information
JacquelineTuyisenge committed Apr 24, 2024
1 parent abbc596 commit 145c21a
Show file tree
Hide file tree
Showing 2 changed files with 109 additions and 1 deletion.
107 changes: 106 additions & 1 deletion src/controllers/userController.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { NextFunction, Request, Response } from "express";
import { UserModelAttributes } from "../database/models/User";
import { User } from "../database/models/User";
import bcrypt from "bcrypt";
import { generateAccessToken } from "../helpers/security.helpers";
import { HttpException } from "../utils/http.exception";
import passport, { CustomVerifyOptions } from "../middlewares/passport";
import { PassThrough } from "stream";


interface InfoAttribute extends CustomVerifyOptions {}
Expand Down Expand Up @@ -75,7 +78,109 @@ const login = async (req: Request, res: Response, next: NextFunction) => {
)(req, res, next);
};

const updatePassword = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
const { oldPassword, newPassword, confirmPassword } = req.body;

//if new pass matches confirm pass

if (newPassword !== confirmPassword) {
throw new HttpException(
"BAD REQUEST", "New password and confirm password do not match"
);
}

//authenticate user

passport.authenticate(
"login",
async (error: Error, user: UserModelAttributes, info: InfoAttribute) => {
if (error || !user) {
throw new HttpException(
"UNAUTHORIZED", "Invalid credentials. Please try again."
)
}

//if old pass matches

const passwordMatch = await bcrypt.compare(oldPassword, user.password);
if (!passwordMatch) {
throw new HttpException(
"UNAUTHORIZED", "Invalid credentials. Please try again."
)
}

//hash new password

const hashedPassword = await bcrypt.hash(newPassword, 10);

// update password

await User.update({ password: hashedPassword }, { where: { id: user.id } });

// Generate new access token
const token = generateAccessToken({ id: user.id, role: user.role });

// Send response
const response = new HttpException(
"SUCCESS",
"Password updated successfully."
).response();
res.status(200).json({ ...response, token });
}
)(req, res, next);
} catch (error) {
res.status(500).json(new HttpException("SERVER ERROR", "Something went wrong!"));
}
};

// // Check if new password and confirm password match
// if (newPassword !== confirmPassword) {
// return res
// .status(400)
// .json(new HttpException("BAD REQUEST", "New password and confirm password do not match"));
// }

// // Find the user by userId
// const user = await UserModelAttributes.findByPk(userId);
// if (!user) {
// return res
// .status(404)
// .json(new HttpException("NOT FOUND", "User not found"));
// }

// // Check if old password matches
// const isPasswordValid = await bcrypt.compare(oldPassword, user.password);
// if (!isPasswordValid) {
// return res
// .status(400)
// .json(new HttpException("BAD REQUEST", "Old password is incorrect"));
// }

// // Validate new password (you can add additional validation logic here if needed)

// // Hash the new password
// const hashedPassword = await bcrypt.hash(newPassword, 10);

// // Update user's password
// await user.update({ password: hashedPassword });

// // Password updated successfully
// return res.status(200).json({ message: "Password updated successfully" });

// } catch (error) {
// console.error("Error updating password:", error);
// return res
// .status(500)
// .json(new HttpException("SERVER ERROR", "Failed to update password"));
// }

export default {
registerUser,
login
login,
updatePassword,
};
3 changes: 3 additions & 0 deletions src/routes/userRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ userRoutes.post(
);

userRoutes.post("/login", userMiddleware.logInValidated, userController.login);
userRoutes.patch(
"/password-update", userController.updatePassword
);


export default userRoutes;

0 comments on commit 145c21a

Please sign in to comment.