title: BasicAuth with Express and Mongoose
body: <p>I'm trying to add a basic authentication to my Express paths. To check if the combination user/pass is correct, I read the collections usermodels in my MongoDB database.
  Here is my code :</p>
  
  <p><strong>server.js</strong></p>
  
  <pre><code>var normal = express.basicAuth(normalAuth);
  
  app.get('path', normal, function(req, res){etc.});
  
  function normalAuth(user, pass) {
    var mongo = require('./database/userManager');
    var result = false;
    mongo.start(mongo.list(function(err, data) {
        if(err) { throw err; }
        else {
          console.log('Getting list from db...');
          for(var i in data) {
            console.log('Getting details from db...');
            if(user == data[i].name &amp;&amp; pass == data[i].pass) {
              console.log('New connection : ' + user);
              result = true;
              break;
            }
            else {
              console.log('Failed connection : ' + user);
              result = false;
            }
          }
          console.log('OK');
        }
        mongo.mongoose.connection.close();
    }));
    return result;
  }
  </code></pre>
  
  <p><strong>userManager.js</strong></p>
  
  <pre><code>var mongoose = require('mongoose');
  
  var userModel = mongoose.connection.model('usermodel', new mongoose.Schema({
      name: String,
      pass: String,
      status: { type: Boolean, default: false }
  }), 'usermodels');
  
  function start(callback) {
    mongoose.connect('mongodb://localhost/derp', function(err) {
        if(err) { throw err; }
        else { 
          console.log('Connected to database ');
        }
    });
  }
  
  function list(callback) {
    userModel.find(callback); 
  }
  </code></pre>
  
  <p>The authentication almost works, it connects to the db and get the informations. It prints on the console </p>
  
  <pre><code>"New connection : /*user connected*/". 
  </code></pre>
  
  <p>But there is a problem : my function normalAuth always return false, so even if I have correct user/pass, I can't access the pages and I have the connection window as if I gave wrong user/pass. I guess it is because this function return the result before my mongo.start(blabla) finished, but I don't know what to do.</p>
  
  <p>Thank you for your help.</p>