Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // @desc Forgot password
- // @route POST /api/v1/auth/forgotpassword
- // @access Public
- // @status DONE
- exports.forgotPassword = asyncHandler(async (req, res, next) => {
- const user = await User.findOne({ email: req.body.email }); // Does the email submitted match with a user in the system?
- if (!user) {
- return next(new ErrorResponse('There is not user with that email', 404)); // Does not exists? Then thrown an error
- }
- // Get userId
- const userId = user.id; // YOU DONT NEED THE USERID. If you decide to delete this, make sure to delete it from the const resetURL also.
- // Get reset token
- const resetToken = user.getResetPasswordToken(); // THIS IS AFUNCTION LOCATED IN YOUR MODEL USING MONGOOSE. SEE BELOW
- // user.password = undefined;
- await user.save({ validateBeforeSave: false });
- // Create reset url
- const resetUrl = `${req.protocol}://${req.get(
- 'host'
- )}/auth/resetpassword/${userId}/${resetToken}`;
- const message = `You are receiving this email because you have requested the reset of a password. Please make a PUT request to: \n\n <a href="${resetUrl}">Reset Password</a> `;
- try {
- await sendEmail({ // sendEmail is a function that you can call as many times as you want. SEE BELOW
- email: user.email,
- subject: 'Password reset token',
- message
- });
- res.status(200).json({ success: true, data: 'Email sent', user });
- } catch (err) {
- console.log(err);
- user.resetPasswordToken = undefined;
- user.resetPasswordExpire = undefined;
- await user.save({ validateBeforeSave: false });
- return next(new ErrorResponse('Email could not be sent', 500)); // YOU CAN HANGLE ERRORS HOWEVER YOU WANT. YOU MIGHT DELETE THIS AS IT WILL SHOW YOU AN ERROR(--PROBABLY--).
- }
- });
- /*
- * THIS IS A HELPER FILE CONTAINING A FUNCTION THAT YOU CAN CALL FROM ANY OF YOUR ROUTES.
- */
- const nodemailer = require('nodemailer');
- const sendEmail = async options => {
- const transporter = nodemailer.createTransport({
- host: process.env.SMTP_HOST, // YOU GET ALL OF THIS FROM E-MAIL SERVER
- port: process.env.SMTP_PORT, // YOU GET ALL OF THIS FROM E-MAIL SERVER
- auth: {
- user: process.env.SMTP_EMAIL, // YOU GET ALL OF THIS FROM E-MAIL SERVER
- pass: process.env.SMTP_PASSWORD // YOU GET ALL OF THIS FROM E-MAIL SERVER
- }
- });
- const message = {
- from: `${process.env.FROM_NAME} <${process.env.FROM_EMAIL}>`,
- to: options.email,
- subject: options.subject,
- text: options.message,
- html: options.message
- };
- const info = await transporter.sendMail(message);
- console.log('Message sent: %s', info.messageId);
- };
- module.exports = sendEmail;
- /*
- * FUNCTION TO GET A GENERATE TOKEN LOCATED IN MODEL - you need CRYPTO in order to make it work.
- */
- UserSchema.methods.getResetPasswordToken = function() {
- // Generate token
- const resetToken = crypto.randomBytes(20).toString('hex');
- // Hash token and set to resetPasswordToken field
- this.resetPasswordToken = crypto
- .createHash('sha256')
- .update(resetToken)
- .digest('hex');
- // Set expire
- this.resetPasswordExpire = Date.now() + 10 * 60 * 1000;
- return resetToken;
- };
- /*
- * THIS IS THE ROUTE TO USE WITH THE URL SENT IN THE EMAIL.
- * AGAIN YOU DON'T NEED USERID -- OPTIONAL
- * EXAMPLE OF ROUTE IN FRONT END: /auth/resetpassword/:userid/:resettoken
- */
- exports.resetPassword = asyncHandler(async (req, res, next) => {
- // Get hashed token
- const resetPasswordToken = crypto
- .createHash('sha256')
- .update(req.params.resettoken)
- .digest('hex');
- const user = await User.findOne({
- _id: req.params.userid,
- resetPasswordToken,
- resetPasswordExpire: { $gt: Date.now() }
- });
- if (!user) {
- return next(new ErrorResponse('Invalid token', 400));
- }
- // Set new password
- user.password = req.body.password;
- user.resetPasswordToken = undefined;
- user.resetPasswordExpire = undefined;
- await user.save();
- res
- .status(200)
- .json({ success: true, data: 'New password has been created', user });
- // sendTokenResponse(user, 200, res);
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement