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.

Account

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

Get Building Node Applications with MongoDB and Backbone now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.