forked from pbock/c3t-drop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
239 lines (202 loc) · 6.49 KB
/
index.ts
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
229
230
231
232
233
234
235
236
237
238
239
import * as archiver from 'archiver';
import * as express from 'express';
import * as i18n from 'i18n';
import * as _ from 'lodash';
import * as moment from 'moment';
import * as multer from 'multer';
import * as URL from 'node:url';
import * as path from 'path';
// Middleware
import * as cookieParser from 'cookie-parser';
import helmet from 'helmet';
// Models
import TalkModel, { FileInfo, TalkFile } from './src/models/talks';
// JSON Views
import * as JSONViews from './src/json-views';
import { fromRoot } from './src/lib/from-root';
// Set up logger
import { log } from './src/logger';
const MONTH = 30 * 24 * 60 * 60 * 1000;
// Load config
import * as config from './config';
import {
checkBasicAuth,
checkCookieAuth,
checkTokenAuth,
PotentiallyAuthenticatedRequest,
} from './src/auth';
import { Error404 } from './src/errors';
if ((config.secret as unknown) === 'REPLACE THIS WITH A LONG RANDOM STRING') {
log.error('You must replace config.secret with a long random string');
process.exit(1);
}
const eventName = config.eventName;
const isProduction = process.env.NODE_ENV === 'production';
if (!isProduction) {
log.warn('NODE_ENV is not set to production. Actual value: %s', process.env.NODE_ENV);
}
const filesBase = fromRoot('files/');
const Talk = TalkModel(config, filesBase);
const upload = multer({
dest: path.resolve(filesBase, '.temp/'),
limits: {
fileSize: 50e6,
},
});
const app = express();
// Configure internationalization
i18n.configure({
directory: fromRoot('src/locales/'),
locales: ['en', 'de'],
cookie: 'lang',
});
if (isProduction) {
app.use(helmet());
}
// Set up basic auth
function forceAuth(
req: PotentiallyAuthenticatedRequest,
res: express.Response,
next: express.NextFunction
) {
function unauthorized(res: express.Response) {
res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
return res.status(401).send('<h1>Unauthorized</h1>');
}
if (req.isAuthorized === undefined) checkBasicAuth(req, res);
if (req.isAuthorized) return next();
return unauthorized(res);
}
app.use((req, res, next) => {
log.info('%s %s', req.method, req.url);
if (req.query.lang) {
log.info('Setting language to %s', req.query.lang);
res.cookie('lang', req.query.lang, { maxAge: MONTH, httpOnly: true });
const { pathname } = URL.parse(req.url);
res.redirect(pathname || '/');
} else {
next();
}
});
app.use(cookieParser() as any);
app.use(i18n.init);
app.use(checkTokenAuth);
app.use(checkBasicAuth);
app.use(checkCookieAuth);
app.set('views', fromRoot('src/views/'));
app.set('view engine', 'pug');
app.use('/static', express.static(fromRoot('src/static/')) as any);
app.locals.moment = moment;
app.get('/', async (req: PotentiallyAuthenticatedRequest, res) => {
const { isAuthorized } = req;
const scheduleVersion = Talk.getScheduleVersion();
const talks = await Talk.allSorted();
const resData = { talks, isAuthorized, eventName, scheduleVersion };
if (req.accepts('html')) res.render('index', resData);
else if (req.accepts('json')) res.json(await JSONViews.index(resData));
else res.status(406).send();
});
function ensureExistence<T>(thing?: T | null): T {
if (!thing) {
const err = new Error404('Not found');
throw err;
}
return thing;
}
app.get('/talks/:id', async (req: PotentiallyAuthenticatedRequest, res, next) => {
const { uploadCount, commentCount, nothingReceived } = req.query;
const { isAuthorized } = req;
const talk = await Talk.findById(req.params.id).then(ensureExistence);
let comments: { body: Buffer; info: FileInfo }[] | null = null;
if (req.isAuthorized) comments = await talk.getComments();
const resData = {
talk,
comments,
uploadCount,
commentCount,
nothingReceived,
isAuthorized,
eventName,
};
if (req.accepts('html')) res.render('talk', resData);
else if (req.accepts('json')) {
res.json(await JSONViews.talk(resData));
} else res.status(406).send();
});
app.get('/sign-in', forceAuth, (req, res) => {
res.redirect('/');
});
app.post('/talks/:id/files/', upload.any() as any, (req, res, next) => {
let requestTalk;
const { body } = req;
const files = req.files as Express.Multer.File[];
if (!files.length && !body.comment) {
log.info('Form submitted, but no files and no comment received');
res.redirect(`/talks/${req.params.id}/?nothingReceived=true`);
return;
}
log.info({ files, body }, 'Files received');
return Talk.findById(req.params.id)
.then(ensureExistence)
.then((talk) => {
requestTalk = talk;
const tasks = [];
if (files.length) tasks.push(talk.addFiles(files));
if (body.comment) tasks.push(talk.addComment(body.comment));
return Promise.all(tasks).then(() => talk);
})
.then((talk) => {
res.redirect(
`/talks/${talk.id}/?uploadCount=${files.length}&commentCount=${body.comment ? '1' : '0'}`
);
})
.catch((err) => {
log.error(err, 'Failed to add files');
next(err);
});
});
app.get('/talks/:id/files.zip', forceAuth, (req, res, next) => {
return Talk.findById(req.params.id)
.then(ensureExistence)
.then((talk) => {
const archive = archiver('zip');
archive.directory(talk.filePath, '/');
archive.on('error', next);
res.set({
'Content-Type': 'application/octet-stream',
'Content-Disposition': `attachment; filename="${talk.slug}.zip"`,
});
archive.pipe(res);
archive.finalize();
})
.catch(next);
});
app.get('/talks/:id/files/:filename', forceAuth, (req, res, next) => {
return Talk.findById(req.params.id)
.then(ensureExistence)
.then((talk) => {
const file = _.find(talk.files, { name: req.params.filename }) as TalkFile;
if (!file) {
const error = new Error404('File not found');
throw error;
}
res.sendFile(file.path);
})
.catch(next);
});
app.get('/talks/:id/files/', (req, res) => {
res.redirect(`/talks/${req.params.id}/`);
});
app.use((req, res, next) => {
log.info(`%s %s Request didn't match a route`, req.method, req.url);
res.status(404).render('error', { status: 404 });
});
app.use((err: Error, req: express.Request, res: express.Response, next: express.NextFunction) => {
const status: number = (err as any).status || 500;
const publicMessage: string | undefined = (err as any).publicMessage;
log.warn(err, '%s %s Error handler sent', req.method, req.url);
res.status(status).render('error', { status, publicMessage });
});
app.listen(9000, () => {
log.info('App listening on :9000');
});