Guest User

Untitled

a guest
Jan 6th, 2018
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.23 KB | None | 0 0
  1. exports.changePassword = (req, res) => {
  2. const { token, password, confirmPassword } = req.body
  3.  
  4. User.findOne({resetPasswordToken: token}, (err, user)=>{
  5. if(!user){
  6. return res.status(400).send({
  7. msg: 'Invalid token or token has been used!'
  8. })
  9. }
  10.  
  11. const hash_password = bcrypt.hashSync(password, 10)
  12. User.findOneAndUpdate({_id: user._id},
  13. {hash_password},
  14. (err, result)=>{
  15.  
  16. if(err){
  17. return res.status(400).send({
  18. msg: err
  19. })
  20. }
  21.  
  22. User.findOneAndUpdate({_id: user._id},
  23. {resetPasswordToken: ''},
  24. (err, result)=>{
  25. if(err){
  26. return res.status(400).send({
  27. msg: err
  28. })
  29. }
  30.  
  31. res.status(200).json({
  32. status: 1,
  33. data: 'Your password has been changed.'
  34. })
  35. }
  36. )
  37. })
  38. })
  39. }
  40.  
  41. exports.changePassword = (req, res) => {
  42. const { token, password, confirmPassword } = req.body
  43.  
  44. User.findOne({resetPasswordToken: token}).then((user)=>{
  45. // do stuff with user here
  46.  
  47. const hash_password = bcrypt.hashSync(password, 10)
  48. // Now chain the next promise by returning it
  49. return User.findOneAndUpdate({_id: user._id}, {hash_password});
  50. }).then((result)=>{
  51. // Now you have the result from the next promise, carry on...
  52. res.status(200).json({
  53. status: 1,
  54. data: 'Your password has been changed.'
  55. })
  56. }).catch(err => {
  57. // Handle any errors caught along the way
  58. });
  59. }
  60.  
  61. // Note this now has the async keyword to make it an async function
  62. exports.changePassword = async (req, res) => {
  63. const { token, password, confirmPassword } = req.body
  64.  
  65. try {
  66. // Here is the await keyword
  67. const user = await User.findOne({resetPasswordToken: token});
  68.  
  69. // do stuff with user here
  70.  
  71. const hash_password = bcrypt.hashSync(password, 10)
  72.  
  73. // Now the next promise can also be awaited
  74. const result = await User.findOneAndUpdate({_id: user._id}, {hash_password});
  75.  
  76. // Finally send the status
  77. res.status(200).json({
  78. status: 1,
  79. data: 'Your password has been changed.'
  80. });
  81. } catch (err) {
  82. // Any promise rejections along the way will be caught here
  83. });
  84. }
Add Comment
Please, Sign In to add comment