-
Notifications
You must be signed in to change notification settings - Fork 189
/
app.js
96 lines (85 loc) · 2.75 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
const path = require('path');
const express = require('express');
const expressHandlebars = require('express-handlebars');
const session = require('express-session');
const bodyParser = require('body-parser');
const passport = require('passport');
const cors = require('cors');
const helmet = require('helmet');
const RedisStore = require('connect-redis')(session);
const { redis } = require('../lib/redis');
const logger = require('../utils/logger');
const authentication = require('./authentication');
const router = require('./routes');
const app = express();
/**
* Use Helmet to secure our Express server.
*/
app.use(
helmet({
contentSecurityPolicy:
process.env.NODE_ENV === 'development'
? {
directives: {
defaultSrc: ["'self'"],
fontSrc: ["'self'", 'https:', 'data:'],
frameSrc: ["'self'", '*.youtube.com', '*.vimeo.com'],
frameAncestors: ["'self'"],
imgSrc: ["'self'", 'data:', 'https:'],
scriptSrc: ["'self'"],
styleSrc: ["'self'", 'https:', "'unsafe-inline'"],
objectSrc: ["'none'"],
upgradeInsecureRequests: [],
},
}
: undefined,
})
);
// Enable CORS and preflight checks on all routes
const corsOptions = {
exposedHeaders: ['X-Total-Count', 'Link'],
};
app.use(cors(corsOptions));
// Setup session and passport for authentication
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(
session({
store: new RedisStore({ client: redis }),
secret: process.env.SECRET || `telescope-has-many-secrets-${Date.now()}!`,
resave: false,
saveUninitialized: false,
})
);
authentication.init();
app.use(passport.initialize());
app.use(passport.session());
// Template rendering for legacy "planet" view of posts
app.engine('handlebars', expressHandlebars());
app.set('views', path.join(__dirname, 'planet/views'));
app.set('view engine', 'handlebars');
// Add our logger to the app
app.set('logger', logger);
app.use(logger);
// Include our router with all endpoints
app.use('/', router);
/**
* Error Handler, Pass to front-end
*/
/* eslint-disable no-unused-vars */
app.use((err, req, res, next) => {
logger.logger.error({ error: err });
const status = err.status || 500;
res
.status(status)
.redirect(`/error?status=${status}${err.message ? `&message=${encodeURI(err.message)}` : ``}`);
});
/**
* 404 Handler, Pass to front-end
* Leverage .status because adding the `404` status in redirect causes "Not Found. Redirecting to /404?search=" to display.
*/
app.use((req, res) => {
logger.logger.warn(`Attempted to access the following unknown URL: ${req.url}`);
res.status(404).redirect(`/error?status=404`);
});
module.exports = app;