2
votes

I am using Loopback as an api for a phone app.

How could I change the out of the box verification of an email address when a user signs up. I need it to be a 4 digit code (instead of a url) so that it's more friendly to the user verifying their account inside the app.

ie. they would then just need to enter the 4 digit number to confirm the registration

2
I think you could just overwrite the default verification generation method, but I've never tried... I'll see if I can work up an example. - Jordan Kasper

2 Answers

4
votes

There are a couple of ways to do this, but it basically comes down to overriding the user.verify() method (or some portion of it). If you click on that link above and scroll down just a bit you'll see how LoopBack is using the crypto.randomBytes() method to generate the verificationToken which is stored on the user object, then it emails it to the user. We can override this method in a "submodel" which extends user and then implement it ourselves, but note that you would be copying a lot of that information.

That said, I've submitted a PR to LoopBack to make this easier. Check out that link and you can see how it might be done in the future (if the PR doesn't change).

For now, you would have to override the verify() method:

User.prototype.verify = function(options, fn) {
  var user = this;

  // do a lot of audits and other stuff (check the current source)...

  // Set the token any way you like...
  user.verificationToken = "123456"; // <-- this probably isn't a good way
  user.save(function(err) {
    if (err) {
      fn(err);
    } else {
      sendEmail(user);
    }
  });

  function sendEmail(user) {
    // you should be able to keep this exactly as it is in the source...
  }
};

And of course, don't forget to read about verifying user email addresses in the LoopBack documentation!

0
votes

Another option is to pass the token generation function to the options object. You can see how it's used if you scroll down a bit.

Check my answer to a somewhat related question for steps on how to override the User model and pass the options object to the verify() method.

You can do this in the remote hook after you create a new User, e.g.:

User.afterRemote('create', function(context, user, next) {
    var userModel = User.constructor;

    myTokenGenerator = function(user, cb) {
      myToken = '1234'
      cb(null, myToken);
    };

    var options = {
      type: 'email',
      mailer: Email,
      to: user.email,
      from: senderEmail,
      subject: 'My subject',
      template: path.resolve(__dirname, '../views/verify.ejs'),
      user: user,
      host: myEmailHost,
      port: myEmailPort,
      generateVerificationToken: myTokenGenerator
    };

    user.verify(options, function(err, response) {

      if (err) {
        next(err);
        return;
      }
      console.log("Account verification email sent to " + options.to);
      next();
      return;
    });
});