This repository has been archived by the owner on Dec 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
265 lines (232 loc) · 7.08 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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
import * as path from 'path';
import * as bunyan from 'bunyan';
import * as express from 'express';
import * as multer from 'multer';
import * as i18n from 'i18n';
import * as URL from 'url';
import * as moment from 'moment';
import * as _ from 'lodash';
import * as archiver from 'archiver';
// Middleware
import * as cookieParser from 'cookie-parser';
import helmet from 'helmet';
import * as basicAuth from 'basic-auth';
// Models
import TalkModel, { TalkFile } from './models/talks';
interface PotentiallyAuthenticatedRequest extends express.Request {
isAuthorized?: boolean;
}
class Error404 extends Error {
status = 404;
}
// Set up logger
const log = bunyan.createLogger({ name: 'c3t-drop-server' });
const MONTH = 30 * 24 * 60 * 60 * 1000;
// Load config
import * as config from './config';
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 = path.resolve(__dirname, 'files/');
const Talk = TalkModel(config.schedulePaths, filesBase);
const upload = multer({
dest: path.resolve(__dirname, '.temp/'),
limits: {
fileSize: 50e6,
},
});
const app = express();
// Configure internationalization
i18n.configure({
directory: path.resolve(__dirname, '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) checkAuth(req, res);
if (req.isAuthorized) return next();
return unauthorized(res);
}
function checkAuth(
req: PotentiallyAuthenticatedRequest,
res: express.Response,
next?: express.NextFunction
) {
const user = basicAuth(req);
const cookieAuth = req.cookies.auth;
let authorized = false;
if (!config.readCredentials) authorized = false;
else if (
user &&
user.name in config.readCredentials &&
user.pass === config.readCredentials[user.name]
) {
authorized = true;
res.cookie('auth', `${user.name}:${user.pass}`, { maxAge: MONTH, httpOnly: true });
} else if (cookieAuth) {
try {
const [cookieUser, cookiePass] = cookieAuth.split(':');
authorized =
cookieUser in config.readCredentials && cookiePass === config.readCredentials[cookieUser];
} catch (e) {
log.warn(e);
}
}
req.isAuthorized = authorized;
if (next) next();
return authorized;
}
app.use(cookieParser() as any);
app.use(checkAuth);
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(i18n.init);
app.set('views', path.resolve(__dirname, 'views/'));
app.set('view engine', 'pug');
app.use(
'/vendor/bootstrap',
express.static(path.resolve(__dirname, 'node_modules/bootstrap/dist/')) as any
);
app.use('/static', express.static(path.resolve(__dirname, 'static/')) as any);
app.locals.moment = moment;
app.get('/', (req: PotentiallyAuthenticatedRequest, res) => {
const { isAuthorized } = req;
const scheduleVersion = Talk.getScheduleVersion();
return Talk.allSorted().then((talks) =>
res.render('index', { talks, isAuthorized, scheduleVersion })
);
});
app.get('/impressum', (req: PotentiallyAuthenticatedRequest, res) => {
const { isAuthorized } = req;
res.render('impressum', { isAuthorized });
});
function ensureExistence<T>(thing?: T | null): T {
if (!thing) {
const err = new Error404('Not found');
throw err;
}
return thing;
}
app.get('/talks/:id', (req: PotentiallyAuthenticatedRequest, res, next) => {
const { uploadCount, commentCount, nothingReceived } = req.query;
const { isAuthorized } = req;
return Talk.findById(req.params.id)
.then(ensureExistence)
.then(async (talk) => {
if (req.isAuthorized) {
const comments = await talk.getComments();
// FIXME: This destroys the getter
return { talk, comments };
}
return { talk };
})
.then(({ talk, comments }) => {
res.render('talk', {
talk,
comments,
uploadCount,
commentCount,
nothingReceived,
isAuthorized,
});
})
.catch(next);
});
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;
log.warn(err, '%s %s Error handler sent', req.method, req.url);
res.status(status).render('error', { status });
});
app.listen(9000, () => {
log.info('App listening on :9000');
});