app.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. const express = require('express');
  2. const bodyParser = require('body-parser');
  3. const fileUpload = require('express-fileupload');
  4. const compression = require('compression');
  5. const log = require('./logger').express;
  6. /**
  7. * App
  8. */
  9. const app = express();
  10. app.use(fileUpload());
  11. app.use(bodyParser.json());
  12. app.use(bodyParser.urlencoded({extended: true}));
  13. // Gzip
  14. app.use(compression());
  15. /**
  16. * General Logging, BEFORE routes
  17. */
  18. app.disable('x-powered-by');
  19. app.enable('trust proxy', ['loopback', 'linklocal', 'uniquelocal']);
  20. app.enable('strict routing');
  21. // pretty print JSON when not live
  22. if (process.env.NODE_ENV !== 'production') {
  23. app.set('json spaces', 2);
  24. }
  25. // CORS for everything
  26. app.use(require('./lib/express/cors'));
  27. // General security/cache related headers + server header
  28. app.use(function (req, res, next) {
  29. let x_frame_options = 'DENY';
  30. if (typeof process.env.X_FRAME_OPTIONS !== 'undefined' && process.env.X_FRAME_OPTIONS) {
  31. x_frame_options = process.env.X_FRAME_OPTIONS;
  32. }
  33. res.set({
  34. 'Strict-Transport-Security': 'includeSubDomains; max-age=631138519; preload',
  35. 'X-XSS-Protection': '1; mode=block',
  36. 'X-Content-Type-Options': 'nosniff',
  37. 'X-Frame-Options': x_frame_options,
  38. 'Cache-Control': 'no-cache, no-store, max-age=0, must-revalidate',
  39. Pragma: 'no-cache',
  40. Expires: 0
  41. });
  42. next();
  43. });
  44. app.use(require('./lib/express/jwt')());
  45. app.use('/', require('./routes/api/main'));
  46. // production error handler
  47. // no stacktraces leaked to user
  48. // eslint-disable-next-line
  49. app.use(function (err, req, res, next) {
  50. let payload = {
  51. error: {
  52. code: err.status,
  53. message: err.public ? err.message : 'Internal Error'
  54. }
  55. };
  56. if (process.env.NODE_ENV === 'development') {
  57. payload.debug = {
  58. stack: typeof err.stack !== 'undefined' && err.stack ? err.stack.split('\n') : null,
  59. previous: err.previous
  60. };
  61. }
  62. // Not every error is worth logging - but this is good for now until it gets annoying.
  63. if (typeof err.stack !== 'undefined' && err.stack) {
  64. if (process.env.NODE_ENV === 'development') {
  65. log.debug(err.stack);
  66. } else if (typeof err.public == 'undefined' || !err.public) {
  67. log.warn(err.message);
  68. }
  69. }
  70. res
  71. .status(err.status || 500)
  72. .send(payload);
  73. });
  74. module.exports = app;