Arun Febi Arun Febi - 1 year ago 126
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
block content
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")
<input type="checkbox" value="remember-me" /> Remember me
button.btn.btn-large.btn-primary(type="submit") Sign in

index.js'/login', function(req, res, next) {
var uname=req.body.username;
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' });
//render loginpage with error msg
res.render('login', { title: 'Express' });

Please help.

Answer Source

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:
  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

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

});"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:

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

npm install jwt

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download