-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathserver.js
More file actions
220 lines (189 loc) · 6.08 KB
/
Copy pathserver.js
File metadata and controls
220 lines (189 loc) · 6.08 KB
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
import Express from 'express';
import mongoose from 'mongoose';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import cors from 'cors';
import session from 'express-session';
import MongoStore from 'connect-mongo';
import passport from 'passport';
import path from 'path';
import basicAuth from 'express-basic-auth';
// Webpack Requirements
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from '@gatsbyjs/webpack-hot-middleware';
import config from '../webpack/config.dev';
// Import all required modules
import api from './routes/api.routes';
import users from './routes/user.routes';
import sessions from './routes/session.routes';
import projects from './routes/project.routes';
import files from './routes/file.routes';
import collections from './routes/collection.routes';
import aws from './routes/aws.routes';
import serverRoutes from './routes/server.routes';
import redirectEmbedRoutes from './routes/redirectEmbed.routes';
import passportRoutes from './routes/passport.routes';
import { requestsOfTypeJSON } from './utils/requestsOfType';
import { renderIndex } from './views/index';
import { get404Sketch } from './views/404Page';
const app = new Express();
app.get('/health', (req, res) => res.json({ success: true }));
const allowedCorsOrigins = [
/p5js\.org$/,
process.env.EDITOR_URL,
process.env.PREVIEW_URL
];
// to allow client-only development
if (process.env.CORS_ALLOW_LOCALHOST === 'true') {
allowedCorsOrigins.push(/localhost/);
}
// Run Webpack dev server in development mode
if (process.env.NODE_ENV === 'development') {
const compiler = webpack(config);
app.use(
webpackDevMiddleware(compiler, {
publicPath: config.output.publicPath
})
);
app.use(webpackHotMiddleware(compiler, { log: false }));
}
const mongoConnectionString = process.env.MONGO_URL;
app.set('trust proxy', true);
// Enable Cross-Origin Resource Sharing (CORS) for all origins
const corsMiddleware = cors({
credentials: true,
origin: allowedCorsOrigins
});
app.use(corsMiddleware);
// Enable pre-flight OPTIONS route for all end-points
app.options('*', corsMiddleware);
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
app.use(bodyParser.json({ limit: '50mb' }));
app.use(cookieParser());
mongoose.set('strictQuery', true);
// TODO: update mongodb connection for other scripts
mongoose.connect(mongoConnectionString, {
serverSelectionTimeoutMS: 30000, // 30 seconds timeout
socketTimeoutMS: 45000 // 45 seconds timeout
});
app.use(
session({
resave: true,
saveUninitialized: false,
secret: process.env.SESSION_SECRET,
proxy: true,
name: 'sessionId',
cookie: {
httpOnly: true,
secure: false,
maxAge: 1000 * 60 * 60 * 24 * 28 // 4 weeks in milliseconds
},
store: MongoStore.create({
mongoUrl: mongoConnectionString,
ttl: 1000 * 60 * 60 * 24 * 28 // 4 weeks in milliseconds to match cookie maxAge
})
})
);
app.use('/api/v1', requestsOfTypeJSON(), api);
// This is a temporary way to test access via Personal Access Tokens
// Sending a valid username:<personal-access-token> combination will
// return the user's information.
app.get(
'/api/v1/auth/access-check',
passport.authenticate('basic', { session: false }),
(req, res) => res.json(req.user)
);
// For basic auth, but can't have double basic auth for API
if (process.env.BASIC_USERNAME && process.env.BASIC_PASSWORD) {
app.use(
basicAuth({
users: {
[process.env.BASIC_USERNAME]: process.env.BASIC_PASSWORD
},
challenge: true
})
);
}
// Body parser, cookie parser, sessions, serve public assets
app.use(
'/locales',
Express.static(path.resolve(__dirname, '../dist/static/locales'), {
// Browsers must revalidate for changes to the locale files
// It doesn't actually mean "don't cache this file"
// See: https://jakearchibald.com/2016/caching-best-practices/
setHeaders: (res) => res.setHeader('Cache-Control', 'no-cache')
})
);
app.use(
Express.static(path.resolve(__dirname, '../dist/static'), {
maxAge:
process.env.STATIC_MAX_AGE ||
(process.env.NODE_ENV === 'production' ? '1d' : '0')
})
);
app.use(Express.static(path.resolve(__dirname, '../public')));
app.use(passport.initialize());
app.use(passport.session());
app.use('/editor', requestsOfTypeJSON(), users);
app.use('/editor', requestsOfTypeJSON(), sessions);
app.use('/editor', requestsOfTypeJSON(), files);
app.use('/editor', requestsOfTypeJSON(), projects);
app.use('/editor', requestsOfTypeJSON(), aws);
app.use('/editor', requestsOfTypeJSON(), collections);
// this is supposed to be TEMPORARY -- until i figure out
// isomorphic rendering
app.use('/', serverRoutes);
app.use('/', redirectEmbedRoutes);
app.use('/', passportRoutes);
// configure passport
require('./config/passport');
app.get('/', (req, res) => {
res.sendFile(renderIndex());
});
// Handle API errors
app.use('/api', (error, req, res, next) => {
if (error && error.code && !res.headersSent) {
console.error('API error:', error.message);
res.status(error.code).json({ error: 'Internal server error' });
return;
}
next(error);
});
// Handle missing routes.
app.get('*', async (req, res) => {
res.status(404);
if (req.accepts('html')) {
try {
const html = await get404Sketch();
res.send(html);
} catch (err) {
console.error('Error generating 404 sketch:', err);
res.send('Error generating 404 page.');
}
return;
}
if (req.accepts('json')) {
res.send({ error: 'Not found.' });
return;
}
res.type('txt').send('Not found.');
});
// Global error handler for unhandled errors
app.use((error, req, res, next) => {
console.error('Unhandled error:', error);
if (res.headersSent) {
return next(error);
}
const statusCode = error.status || 500;
return res.status(statusCode).json({
error: 'Internal server error'
});
});
// start app
app.listen(process.env.PORT, (error) => {
if (!error) {
console.log(`p5.js Web Editor is running on port: ${process.env.PORT}!`); // eslint-disable-line
}
});
export default app;