Search code examples
meteoriron-routermeteor-accounts

Using onResetPasswordLink, onEnrollmentLink, and onEmailVerificationLink methods properly in Meteor


I was wondering if someone would be kind enough to provide a meteorpad or code example of using one of the methods listed above properly in Meteor (with iron:router). I'm struggling to understand how exactly these methods interact with my app, and it seems these methods are new enough that there isn't much good documentation on how to use them correctly. Thanks!

http://docs.meteor.com/#/full/Accounts-onResetPasswordLink


Solution

  • Ok, so I am going to post what I ended up learning and doing here so others can use it as a reference. I'll do my best to explain what is happening as well.

    As can be seen in the other comments, the 'done' function passed to the Accounts.on****Link callback was the main part that tripped me up. This function only does one thing - re-enables autoLogin. It's worth noting that the 'done' function/autoLogin is a part of one of the core 'accounts' packages, and cannot be modified. 'autoLogin' is used in one particular situation: User A tries to reset his or her pw on a computer where User B is currently logged in. If User A exits the reset password flow before submitting a new password, then User B will remain logged in. If User A completes the reset password flow, then User B is logged out and User A is logged in.

    The pattern used to handle 'done' in the accounts-ui package, and what I ended up doing, assigns 'done' to a variable that can then be passed to your template event handler function, and run once your reset password logic is complete. This variable assignment needs to be done in the Accounts.on****Link callback, but the callback can be placed in any top-level client side code (just make sure you assign the scope of the variables correctly). I just put it at the start of my reset_password_template.js file (I've only done this for resetting passwords so far, but the pattern should be similar):

    client/reset_password_template.js:

    // set done as a variable to pass
    var doneCallback;
    
    Accounts.onResetPasswordLink(function(token, done) {
      Session.set('resetPasswordToken', token);  // pull token and place in a session variable, so it can be accessed later 
      doneCallback = done;  // Assigning to variable
    });
    

    The other challenge of using these on****Link callbacks is understanding how your app 'knows' the callback has been fired, and what needs to be done by the app. Since iron:router is so tightly integrated with Meteor, it's easy to forget it is a separate package. It's important to keep in mind these callbacks were written to operate independently of iron:router. This means when the link sent to your email is clicked, your app is loaded at the root level ('/').

    ***Side note - There are some other answers here on StackOverflow that offer ways to integrate with iron:router, and load a specific route for each link. The problem for me with these patterns was that they seemed a bit hackish, and not in line with the 'meteor' way. More importantly, if the core Meteor team decides to alter the path of these registration links, these routes would break. I tried calling Router.go('path'); in the on****Link callback, but for some reason this didn't work in Chrome and Safari. I would love to have a way to handle specific routes for each of these emailed links, thus eliminating the need for constantly setting and clearing Session variables, but I couldn't think of a good solution that worked.

    Anyways, as @stubailo described in his answer, your app is loaded (at the root level), and the callback is fired. Once the callback is fired, you have your session variable set. You can use this session variable to load the appropriate templates at the root level using the following pattern:

    client/home.html (or your landing page template)

    {{#unless resetPasswordToken}}
      {{> home_template}}
    {{else}}
      {{> reset_password_template}}
    {{/unless}}
    

    With this, there are few things you need to take care of in your reset_password_template.js file, and home.js:

    client/home.js

    // checks if the 'resetPasswordToken' session variable is set and returns helper to home template
    Template.home.helpers({
      resetPasswordToken: function() {
        return Session.get('resetPasswordToken');
      }
    });
    

    client/reset_password_template.js

    // if you have links in your template that navigate to other parts of your app, you need to reset your session variable before navigating away, you also need to call the doneCallback to re-enable autoLogin
    Template.reset_password_template.rendered = function() {
      var sessionReset = function() {
        Session.set('resetPasswordToken', '');
        if (doneCallback) {
          doneCallback();
        }    
      }
    
      $("#link-1").click(function() {
        sessionReset();
      });
    
      $('#link2').click(function() {
        sessionReset();
      });
    }
    
    Template.reset_password_template.events({
      'submit #reset-password-form': function(e) {
        e.preventDefault();
    
        var new_password = $(e.target).find('#new-password').val(), confirm_password = $(e.target).find('#confirm-password').val();
    
        // Validate passwords
        if (isNotEmpty(new_password) && areValidPasswords(new_password, confirm_password)) {
          Accounts.resetPassword(Session.get('resetPasswordToken'), new_password, function(error) {
            if (error) {
              if (error.message === 'Token expired [403]') {
                Session.set('alert', 'Sorry, this link has expired.');
              } else {
                Session.set('alert', 'Sorry, there was a problem resetting your password.');          
              }
            } else {
              Session.set('alert', 'Your password has been changed.');  // This doesn't show. Display on next page
              Session.set('resetPasswordToken', '');
              // Call done before navigating away from here
              if (doneCallback) {
                doneCallback();
              }
              Router.go('web-app');
            }
          });
        }
    
        return false;
      }
    });
    

    Hopefully this is helpful for others who are trying to build their own custom auth forms. The packages mentioned in the other answers are great for many cases, but sometimes you need additional customization that isn't available via a package.