mongodb를 사용하여 노드 js에서 암호를 잊어버렸습니다.

3953 단어
이 기사에서는 가입 신청을 진행합니다. 이 부분에서는 암호 기억 실패, nodemailer로 메시지 보내기 및 암호 재설정에 대해 자세히 설명합니다. 당신이 준비한 이벤트, 우리는 시작해야합니다!

우선, 지난번에는 nodemailer가 아닌 mailgun을 사용했습니다. 그런데 이메일 전송 전략을 살펴보니 nodemailer가 보이고 구분용으로만 사용하고 싶다.

비밀 단어를 재설정하려면 User 모델에 String 변수가 필요합니다. Date 변수도 만들지만 전달할 수 있도록 활용하지는 않습니다. 문자열 변수의 이름은 resetPasswordToken입니다. crypto라는 번들이 필요하며 맨 위에 필요합니다.

User 모델에서 다음 요소에서 getResetPasswordToken이라는 전략을 만들 것입니다.

```const resetToken = crypto.randomBytes(20).toString('hex');



**bold**

Presently, we need to hash token and set to resetPasswordToken field, set terminate and return resetToken. The entire code about getResetPasswordToken is here: 

For getting sends I will utilize mailgun, make a record and get a few definitions. 

We'll make a middleware named sendEmail. In this, we need nodemailer, so we'll stop the worker and introduce nodemailer with: 

npm introduce nodemailer 
We'll require it, top of middleware. 
On the nodemailer site, we'll duplicate these codes: 
I change a few sections as I need. In createTransport, you can see host, port and auth are unique in relation to the site. For these, we'll go to .env record and make SMTP_HOST, SMTP_PORT, SMTP_EMAIL, SMTP_PASSWORD. In mailgun, we can see these parts, I don't share them obviously. 

Presently, we need a strategy named forgotPassword. With this strategy, we'll take an email and send a solicitation.




const 클라이언트 = 예상 User.findOne({ 이메일: req.body.email });





In the event that the client doesn't exist, we'll make a blunder. These are like my past articles, so I don't clarify.




const resetToken = user.getResetPasswordToken();await user.save({ validateBeforeSave: false})




With this, we have two factors in the data set, they will annihilate when we reset the secret key. 

We'll make a message like this: 

'You are accepting this email since you (or another person) has mentioned the reset of a secret word. Kindly make a PUT solicitation to: \n\n ${resetUrl}' 

So when messages are gone, this will clarify why it has gone. 

Presently, we make an attempt get. 

attempt {await sendEmail({email: user.email,subject: 'Secret word reset token',message})res.status(200).json({ achievement: valid, data:'Email sent' });} get (mistake) {console.log(err);user.getResetPasswordToken = undefined;user.resetPasswordExpire = undefined;await user.save({ validateBeforeSave: bogus })return next(new ErrorResponse('Email couldn't be sent', 500))} 

This strategy is done, at long last, we'll make the resetPassword work. We'll get hashed token with: 

const resetPasswordToken = crypto.createHash('sha256').update(req.params.resetToken).digest('hex'); 
We'll make a client, and utilize the findOne technique. In this: 

const client = anticipate User.findOne({resetPasswordToken,resetPasswordExpire: { $gt: Date.now() }}); 
On the off chance that the client not exists, we'll make a mistake. Presently, we need to set another secret key, and obliterate resetPasswordToken and resetPasswordExpire, at that point save the client and sendTokenResponse:




user.password = req.body.password;user.resetPasswordToken = 정의되지 않음;user.resetPasswordExpire = 정의되지 않음;await user.save();const id = user.getId();sendTokenResponse(user, 200, res, id);



In courses/auth.js, we'll require forgotPassword and resetPassword capacities and use them down in the getMe work:



router.post('/forgotPassword', forgotPassword);

router.put('/resetPassword/:resetToken', resetPassword);



Hope you liked the post then like, share and comment.

좋은 웹페이지 즐겨찾기