expressConfig.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. var passport = require('passport');
  2. var cookieSession = require('cookie-session');
  3. var bodyParser = require('body-parser');
  4. var cookieParser = require('cookie-parser');
  5. var csrf = require('csurf');
  6. module.exports = function(app, express) {
  7. // Serve static assets from the app folder. This enables things like javascript
  8. // and stylesheets to be loaded as expected. You would normally use something like
  9. // nginx for this normally, but this makes for a simpler demo app to just let express do it.
  10. app.use("/", express.static("app/"));
  11. app.set('views', __dirname + '/../views'); // Set the view directory, this enables us to use the .render method inside routes
  12. app.use(bodyParser.urlencoded({ extended: false })); // parse application/x-www-form-urlencoded
  13. app.use(bodyParser.json()); // parse application/json
  14. // Setup cookie sessions
  15. app.use(cookieParser());
  16. app.use(cookieSession({secret: 'Super secret, this should be something super secure'}));
  17. // Add CSRF token to requests to secure our ajax requests from the angular.js app
  18. app.use(csrf());
  19. app.set('view engine', 'ejs'); // Set the template engine to ejs
  20. // This is a little custom middleware which adds the csrf token to local variables
  21. // which can be used used within ejs template forms by doing something like:
  22. // <form>
  23. // <input type="hidden", name="_csrf", value='<%-csrfToken%>'>
  24. // ... other inputs and submit buttons
  25. // </form>
  26. //
  27. // Setting the: res.cookie('XSRF-TOKEN', req.csrfToken()); is for angularJS
  28. // AngularJs looks for this cookie, and if it exists it sends it along with each
  29. // ajax request made with the $http service.
  30. app.use(function(req, res, next) {
  31. res.locals.csrfToken = req.csrfToken();
  32. res.cookie('XSRF-TOKEN', req.csrfToken());
  33. next();
  34. });
  35. // Initialize passport middleware for user authentication
  36. app.use(passport.initialize());
  37. app.use(passport.session());
  38. }