Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //password change controller with old password , new password and retype password
- const passwordChangeController = async (req,res) => {
- try{
- /*
- in body you have to take 3 input like
- {
- oldPassword: .......(min-8),
- newPassword: ........(min-8),
- repeatPassword: ..........
- }
- */
- const passwordValidator = Joi.object({
- newPassword: Joi.string().required().pattern(new RegExp ('^[a-zA-Z0-9]{8,30}$')),
- repeatPassword: Joi.ref('newPassword'),
- oldPassword: Joi.required()
- })//validator the password
- const {error} = passwordValidator.validate(req.body) //get the validation
- if(error){
- res.json({
- message: "validation error",
- error
- })
- }else{
- const {id} = req.params;//get the id from params
- const {oldPassword, newPassword} = req.body; //get the data from body
- const user = await User.findOne(({_id:id})) //get the user here
- const matchTheOldPassword = await bcrypt.compare(oldPassword, user.password) //match the old password with the existing one
- if(matchTheOldPassword){
- const matchTheNewPasswordWithOldOne = await bcrypt.compare(newPassword, user.password)//check that the new input password is equal to the old one or not
- if(matchTheNewPasswordWithOldOne){
- res.json({
- message: "You have input your old password.Please input a different password"
- })
- }else {
- const hash = await bcrypt.hash(newPassword, 10) //hash the new input password
- await User.findByIdAndUpdate(
- {_id : id},
- {
- $set: {
- password: hash
- }
- }
- )//update the new password
- return res.json({
- message: "password has been changed"
- })
- }
- }else {
- res.json({
- message: "old password doesn't match"
- })
- }
- }
- }
- catch(err){
- res.send(err)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement