在 user 真正重設密碼前,後端大致上會經過以下過程:
一開始,我們需要在 AuthController 中建立一個 forgotPassword 的 function:
在這之中,我們需要:
forgotPassword function:
exports.forgotPassword = catchAsync(async(req, res, next) => {
   // 1. 根據 post 的 email 取得 user
   const user = await User.findOne({ email: req.body.email });
   if (!user) {
       return next(new AppError('There is no user with this email address.', 404));
   }
   
   // 2. 隨機生成 reset token
   const resetToken = user.createTokenForResetPassword();
   // 儲存加密後的 resetToken & 停掉驗證器
   await user.save({ validateBeforeSave: false });
   
   // 3. 寄送 email
   // 此處會在下次進行講解
});
在 userModel 中建立 createPasswordResetToken function,並實作加密:
userSchema.methods.createTokenForResetPassword = function () {
    const resetToken = crypto.randomBytes(32).toString('hex');
    
    this.tokenForResetPassword = crypto.createHash('sha256').update(resetToken).digest('hex');
    
    // 為了安全性,我們需要設定這個 passwordReset 什麼時候會過期: 10 mins
    this.passwordResetExpiresIn = Date.now() + 10 * 60 * 1000;
    
    return resetToken;
}
在 userModel 更新 userSchema:
const userSchema = new mongoose.Schema({
// 略
    tokenForResetPassword: String,
    passwordResetExpiresIn: Date
});
最近身體狀況有點不太好,但還是先今天的一些學習打了出來,希望之後能慢慢進步。
Udemy Node.js, Express, MongoDB & More: The Complete Bootcamp 2023:
https://www.udemy.com/course/nodejs-express-mongodb-bootcamp
Hacksplaining:
https://www.hacksplaining.com/