-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathserver.js
228 lines (198 loc) · 6.25 KB
/
server.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
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
221
222
223
224
225
226
227
228
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 connectMongo 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();
const MongoStore = connectMongo(session);
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);
const clientPromise = mongoose
.connect(mongoConnectionString, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverSelectionTimeoutMS: 30000, // 30 seconds timeout
socketTimeoutMS: 45000 // 45 seconds timeout
})
.then((m) => m.connection.getClient());
app.use(
session({
resave: true,
saveUninitialized: false,
secret: process.env.SESSION_SECRET,
proxy: true,
name: 'sessionId',
cookie: {
httpOnly: true,
secure: false
},
store: new MongoStore({
clientPromise,
autoReconnect: true
})
})
);
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
})
);
}
// routing to serve files in .well-known with specific content type
// temporary addition for the apple pay integration with donorbox
app.use(
'/.well-known/apple-developer-merchantid-domain-association',
(req, res, next) => {
const filePath = path.join(
__dirname,
'../public/.well-known/apple-developer-merchantid-domain-association'
);
res.setHeader('Content-Type', 'text/plain');
res.sendFile(filePath, (err) => {
if (err) {
console.error('Error serving file:', err);
next(err);
}
});
}
);
// 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) {
res.status(error.code).json({ error: error.message });
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.');
});
// 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;