Arun Febi Arun Febi - 3 months ago 19
Node.js Question

How to do form Authentication using node.js+Express+Mongodb?

I'm trying to do small app using Node.js+Express+MongoDb.Created login Page. Now I want post data from loginpage and validate username and email according to database. I wonder how to do this.
My Login-page View(Jade):

extends layout
body
block content
.container
form.form-signin(action="/login", method="post")
h2.form-signin-heading Please sign in
input.input-block-level(type="text", name="username", placeholder="username")
input.input-block-level(type="text", name="text", placeholder="user mail")
label.checkbox.
<input type="checkbox" value="remember-me" /> Remember me
button.btn.btn-large.btn-primary(type="submit") Sign in


index.js



router.post('/login', function(req, res, next) {
var uname=req.body.username;
var email=req.body.email;
var db = req.db;
var collection = db.get('userlist');
if(check with database uname and email present or not)
{
//if true
res.render('index', { title: 'Express' });
}
else
{
//render loginpage with error msg
res.render('login', { title: 'Express' });
}
});


Please help.

Answer

There are a lot of methods to reach the goal. I can recommend you the following.

  1. Use Passport.js
  2. Use Token Authentication

Passport.js way

  • install passport npm
  • configure local login strategy
  • install encrypt module to encrypt incoming passwords and store in database
  • use encrypt module to compare passwords
  • create methods to validate incoming passwords

Here are links below

  1. Passport.js: http://passportjs.org/docs
  2. Encrypt module: npm install bcrypt

Code examples:

//User Schema
/*
 * Generate Hash to save password
 */
userSchema.methods.generateHash = function (password) {
    // some service to encrypt and check passwords
    return encryptService.encrypt(password);
};

/*
 * Check if password is valid
 */
userSchema.methods.validPassword = function (password) {
    var user = this;
    var checkPasswordParams = {
        password: password,
        hash: user['authentication']['hash']
    };
    // some service to encrypt and check passwords
    return encryptService.compare(checkPasswordParams);
};

//encrypt service
//here are examples from bcrypt page
bcrypt.hash("bacon", null, null, function(err, hash) {
// Store hash in your password DB.
});

bcrypt.compare("bacon", hash, function(err, res) {

});
bcrypt.compare("veggies", hash, function(err, res) {

});


//Example Of Passport Local Strategy (Username + Password) 
var passport = require('passport')
  , LocalStrategy = require('passport-local').Strategy;

passport.use(new LocalStrategy(
  function(username, password, done) {
    User.findOne({ username: username }, function(err, user) {
      if (err) { return done(err); }
      if (!user) {
        return done(null, false, { message: 'Incorrect username.' });
      }
      if (!user.validPassword(password)) {
        return done(null, false, { message: 'Incorrect password.' });
      }
      return done(null, user);
    });
  }
));

Token Way

Here you can find good example of Token Authentication:

https://scotch.io/tutorials/authenticate-a-node-js-api-with-json-web-tokens

I recommend using this npm module to create and check tokens:

npm install jwt