Creating the Server

Listing 26.2 implements the Express webserver for the application. You should recognize much of the code. The general flow of this code is to first require the necessary modules, connect to the MongoDB database, configure the Express server, and begin listening.

The following line ensures that the User model is registered in Mongoose:

require('./models/users_model.js'),

Also, the following require() adds the routes from ./routes to the Express server:

require('./routes')(app);

The following Express configuration code uses the connect-mongo library to register the MongoDB connection as the persistent store for the authenticated sessions. Notice that the connect-mongo store is passed an object with session set to the express-session module instance. Also notice that the db value in the mongoStore instance is set to the mongoose.connection.db database that is already connected:

var expressSession = require('express-session'),
var mongoStore = require('connect-mongo')({session: expressSession});
app.use(expressSession({
  secret: 'SECRET',
  cookie: {maxAge: 60*60*1000},
  store: new mongoStore({
      db: mongoose.connection.db,
      collection: 'sessions'
    })
  }));

This code adds a session property to the request object. The session object is directly tied to the sessions collection in MongoDB so that when you make changes to the session, they are saved in the database.

Listing 26.2 auth_server.js: Implementing the application database connection and Express webserver


01 var express = require('express'),
02 var bodyParser = require('body-parser'),
03 var cookieParser = require('cookie-parser'),
04 var expressSession = require('express-session'),
05 var mongoStore = require('connect-mongo')({session: expressSession});
06 var mongoose = require('mongoose'),
07 require('./models/users_model.js'),
08 var conn = mongoose.connect('mongodb://localhost/myapp'),
09 var app = express();
10 app.engine('.html', require('ejs').__express);
11 app.set('views', __dirname + '/views'),
12 app.set('view engine', 'html'),
13 app.use(bodyParser());
14 app.use(cookieParser());
15 app.use(expressSession({
16   secret: 'SECRET',
17   cookie: {maxAge: 60*60*1000},
18   store: new mongoStore({
19       db: mongoose.connection.db,
20       collection: 'sessions'
21     })
22   }));
23 require('./routes')(app);
24 app.listen(80);


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.177.151