Smut
Smut

Reputation: 89

Auth0 Custom MongoDB get user script

I have an angular 2 webapplication with auth0 for authorization. I'm using my own mongodb database for storing user information. Auth0 provides templates in a sandbox to achieve this, for example the login script:

function login(email, password, callback) {
  mongo('mongodb://myusername:mypassword@mymongodbaddres:port/mydbname', function (db) {
    var users = db.collection('users');
    users.findOne({ email: email }, function (err, user) {

      if (err) return callback(err);

      if (!user) return callback(new WrongUsernameOrPasswordError(email));

      bcrypt.compare(password, user.password, function (err, isValid) {
        if (err) {
          callback(err);
        } else if (!isValid) {
          callback(new WrongUsernameOrPasswordError(email));
        } else {
          callback(null, {
            user_id: user._id.toString(),
            nickname: user.nickname,
            email: user.email
          });
        }
      });
    });
  });
}

Now the problem is that for the create script Auth0 needs to complete the "get user" script (checks if there isn't already a user with the same email). But the template for the "get user" script is as following:

function getByEmail (name, callback) {
  var profile = {
    user_id:     "103547991597142817347",
    nickname:    "johnfoo",
    email:       "[email protected]",
    name:        "John Foo",
    given_name:  "John",
    family_name: "Foo"
  };

  callback(null, profile);
}

Who can help me to achieve a working "get user" script?

Upvotes: 1

Views: 617

Answers (1)

Gabri
Gabri

Reputation: 411

This is the code I use:

function getByEmail (email, callback) {
  mongo(configuration.mongo_url, function (db) {
    var users = db.collection('users');
    users.findOne({ email: email }, function (err, user) {

      if (err) return callback(err);
      if (!user) return callback(null, null);
      callback(null, {
            user_id: user._id.toString(),
            nickname: user.nickname,
            email: user.email,
            email_verified: user.email_verified
          });
    });
  });
}

I hope this helps.

Upvotes: 1

Related Questions