What should be done for fixing this reset password feature in this Angular code with Node.js and Nodemailer

三世轮回 提交于 2019-12-13 03:49:14

问题


We are trying to create a reset password feature in Angular 6 with Node.js. The point is that when you click the reset password and fill your email it sends the email with the link of reset password. But the link inside the email is not communicating with Angular. We are using Node.js and Node mailer in the backend. Here is the code:

Node.js

 async ResetPassword(req, res) {
    if (!req.body.email) {
      return res
        .status(HttpStatus.INTERNAL_SERVER_ERROR)
        .json({ message: 'Email is required' });
    }

    const userEmail = await User.findOne({
      email: Helpers.lowerCase(req.body.email)
    });
    if (!userEmail) {
      return res
        .status(HttpStatus.CONFLICT)
        .json({ message: 'Email does not exist' });
    }

      const body = {
        email: Helpers.lowerCase(value.email),

      };
            var resettoken = new resetToken({ _userId: user._id, resettoken: crypto.randomBytes(16).toString('hex') });
            resettoken.save(function (err) {
                if (err) { return res.status(500).send({ msg: err.message }); }
                var transporter = nodemailer.createTransport({
                    service: '"SendGrid"',
                    auth:
                     {
                      user: 'login',
                      pass: 'password'
                     }
                });
                var mailOptions = {
                    from: 'email',
                    subject: 'Node.js Password Reset',
                    text: 'You are receiving this because you (or someone else) have requested the reset of the password for your account.\n\n' +
                      'Please click on the following link, or paste this into your browser to complete the process:\n\n' +
                      'http://' + req.headers.host + '/new-password/' + resettoken + '\n\n' +
                      'If you did not request this, please ignore this email and your password will remain unchanged.\n'
                }

                transporter.sendMail(mailOptions 
                )          
            })

        .catch(err => {
            res
                .status(HttpStatus.INTERNAL_SERVER_ERROR)
                .json({ message: 'Error occured' });
        });
    },

The link inside email template is not working.

Route

router.post('/new-password', AuthCtrl.NewPassword);

Angular

      route.queryParams.subscribe(params => {
        this.form.resetToken = params['token'];
      });
    }


  ngOnInit() {
    this.Init();
  }

  Init() {
    this.ResponseResetForm = this.fb.group(
      {
        email: ['', Validators.required, Validators.email],
        newPassword: ['', Validators.required],
        confirmPassword: ['', Validators.required]
      },
      {
        validator: this.Validate.bind(this)
      }
    );
  }

 ...
...

  ResetPassword() {

    this.authService.newPassword(this.ResponseResetForm.value).subscribe(
      data => {
        this.ResponseResetForm.reset();
        setTimeout(() => {
          this.router.navigate(['sign-in']);
        }, 3000);
      },
      err => {

        if (err.error.message) {
          this.errorMessage = err.error.message;
        }
      }
    );
  }
}

This part I've added from another code:

 route.queryParams.subscribe(params => {
            this.form.resetToken = params['token'];
          });
        }

But I don't think it's suitable for our code. Also here is the route for this component in Angular:

  {
    path: 'response-reset-password',
    component: ResponseResetComponent
  },

How can we make this backend controller work as expected with Angular front-end?


回答1:


So when you embed a link in your email, that link needs to route to the Angular frontend, not backend:

{
   path: 'new-password', // I would suggest changing this path to match your Component. This will also lead to changing the URL being embedded in the ResetPassword email
   component: ResponseResetComponent
}

Now, when the user clicks the link in the email, the frontend will be loaded, then you can handle the token in the ResponseResetComponent to actually send the request to: router.post('/new-password') on the backend.



来源:https://stackoverflow.com/questions/54343388/what-should-be-done-for-fixing-this-reset-password-feature-in-this-angular-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!