You are previewing Building Node Applications with MongoDB and Backbone.

Building Node Applications with MongoDB and Backbone

Cover of Building Node Applications with MongoDB and Backbone by Mike Wilson Published by O'Reilly Media, Inc.

Chapter 6. Authentication

Because this application will be fully multi-user, the first gateway to build involves registration and identity authentication. Before users can access any other functionality, they must first identify themselves and prove they have authority to perform certain functions.

In this chapter you will create an account model to represent a user who has registered with your system, with the email address being the primary means of accessing the system. The user will also be expected to supply a password, which will be verified against the account with the matching email.

With a working account model, the next task will be creating login and registration views to bring users into and grant them access to the system.


The account model is the main point of contact between Node.js and the MongoDB database.

The account model in Example 6-1 includes database fields for an email address, password, name, photo, description, and biography. This is a CommonJS module, which exports the account and register, forgotPassword, changePassword, and login functions.

Example 6-1. The user account: models/Account.js

module.exports = function(config, mongoose, nodemailer) {
  var crypto = require('crypto');

  var AccountSchema = new mongoose.Schema({
    email:     { type: String, unique: true },
    password:  { type: String },
    name: {
      first:   { type: String },
      last:    { type: String }
    birthday: {
      day:     { type: Number, min: 1, max: 31, required: false },
      month:   { type: Number, min: 1, max: 12

The best content for your career. Discover unlimited learning on demand for around $1/day.