0
votes

I am pretty new to loopback and here is what I am doing:

I am using standard login route provided by the loopback to log in the users - extended base Users to my own model say orgadmin.

With prebuilt route /api/orgadmin/login, I can easily login.

Now, I have a flag in orgadmins say 'status' which can be either 'active' or 'inactive' based on which I have to defer user login.

I was thinking something with remote hooks like beforeRemote as below but it doesn't work:

//this file is in the boot directory
module.exports = function(orgadmin) {
    orgadmin.beforeRemote('login', function(context, user, next) {
        console.log(user)
        // context.args.data.date = Date.now();
        // context.args.data.publisherId = context.req.accessToken.userId;
        next();
    });
};

So what is the best way to accomplish this?

1

1 Answers

3
votes

The user attribute will only be available if the request is coming with a valid access token. The attribute is unused for unauthenticated requests, which login is.

Here's a possible alternative:

module.exports = (OrgAdmin) => {
  OrgAdmin.on('dataSourceAttached', () => {
    const { login } = OrgAdmin;
    OrgAdmin.login = async (credentials, include) => {
      const accessToken = await login.call(OrgAdmin, credentials, include);
      const orgAdmin = await OrgAdmin.findById(accessToken.userId);
      if (orgAdmin.status !== 'active') {
        OrgAdmin.logout(accessToken);
        const err = new Error('Your account has not been activated');
        err.code = 'NOT_ACTIVE_USER';
        err.statusCode = 403;
        throw err
      }
      return accessToken;
    };
  });
};

The above code overrides the login method and does the following:

  1. Login the user, using loopback's built-in login
  2. Take the response of login, which is an access token, and use it to get the user.
  3. If the user is active, return the access token, satisfying the expected successful response of login.
  4. If the user is not active, remove the access token that was created (which is what logout does), and throw an error.