Search code examples
loopbackjsstrongloop

Loopback stop login while emailVerified is false


i have a custom user model (user extended) and i would like to implement a classic double optin and don't permit login while emailVerified is false, I've tried to write an afterRemote method like this

    var app = loopback();
        app.currentUser = false; 


    user.afterRemote('login', function(context, user, next) {

      var UserModel = app.models.User;

      UserModel.findById(user.userId, function (err, usr) {

         if (err) {

           return next(err);
         }

         if ( !usr ) {

           return next(new Error('could not find a valid user'));
         }

         console.log('> USER SEARCH: %j', usr);

         next();
    });

but UserModel is undefined.

Is this a wrong method to implement double optin in loopback?


Solution

  • You need to use a beforeRemote hook since you want to STOP the login action, using an afterRemote hook the login has already occurred. Based on the code you shared, however, I'm not event sure how you're doing this or where you put this code. You appear to be attaching the hook to user, but then you get the User model off the app anyway?

    I think you will need to extend the core User model in order to do this. So create a new model with User as its base:

    {
      "name": "MyUser",
      "base": "User",
      "properties": {},
      "validations": [],
      "relations": {},
      "acls": [],
      "methods": []
    }
    

    Then in the /common/models/MyUser.js file you have this:

    module.exports = function(MyUser) {
      MyUser.beforeRemote('login', function(context, unused, next) {
    
        MyUser.findOne(
          // assuming they log in with their email address...
          { where: { email: context.req.body.email } },
          function (err, user) {
             if (err || !user) {
               return next(err || (new Error('No user found')));
             }
    
             if (!user.emailVerified) {
               return next(new Error('You need to verify your email first!'));
             }
    
             next();
        });
    };