Jon Cursi
Jon Cursi

Reputation: 3371

Meteor: Programmatically generate password reset token?

In Meteor, how do you programmatically generate / store a reset password token for a user (outside the context of a user asking for it themselves in the UI)?

I am sending a custom email and would like to embed my own "Reset Password" button within it. This requires me to generate a valid reset password token on my own.

Are there any undocumented Accounts functions / helpers that I'm not aware of that can help me achieve this? Thanks!

Upvotes: 3

Views: 739

Answers (1)

Waiski
Waiski

Reputation: 9680

For most scenarios, I recommend using the in-built Accounts.sendResetPasswordEmail for sending the email and overriding Accounts.emailTemplates.resetPassword to do customizations for the email. For example, you can do a custom reset link like this:

Accounts.emailTemplates.resetPassword.html = (user, url) =>
  `<a href="${url}" style="{ something cool... }">Reset your password</a>`;

However, if you need more customizability than this, there is no ready function for creating the reset token, but if you look at the source code for Accounts.sendResetPasswordEmail, you'll see that really you only need to insert an object in the services.password.reset field of the user object like so:

var token = Random.secret();
var when = new Date();
var tokenRecord = {
  token: token,
  email: email,
  when: when,
  reason: 'reset'
};
Meteor.users.update(userId, {$set: {
  "services.password.reset": tokenRecord
}});

var resetPasswordUrl = Accounts.urls.resetPassword(token);

Now you can send resetPasswordUrl to your user in any way you like, it should work. Be careful with security though - I suppose that the lack of a ready-made function for generating password reset tokens is intentional, and meant to discourage people from carelessly creating password reset methods.

Upvotes: 3

Related Questions