-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
70 lines (59 loc) · 1.51 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
const express = require('express');
const path = require('path');
const app = express();
const session = require('express-session');
const crypto = require('crypto');
const msgStore = {
getMsgs: code => msgStore[code] || [],
putMsg: (code, msg) => {
if (!msgStore[code]) {
msgStore[code] = [];
}
msgStore[code].push(msg);
}
};
const appSession = session({
secret: 'session secret',
saveUninitialized: true,
resave: true,
});
if (process.env.NODE_ENV === 'production') {
appSession.cookie = {
secure: true,
};
app.set('trust proxy', 1);
}
// redirect all traffic to https
app.use((req, res, next) => {
if (process.env.NODE_ENV === 'production' &&
req.headers['x-forwarded-proto'] != 'https') {
res.redirect('https://' + req.headers.host + req.url);
} else {
next();
}
});
// statics
app.use('/dist',
express.static(path.join(__dirname, 'dist'))
);
app.use(appSession);
app.get('/', (req, res) => {
req.session.code =
req.query.code ||
req.session.code ||
(crypto.randomBytes(16)).toString('hex');
res.sendFile(
path.join(__dirname, 'dist/index.html')
);
});
app.get('/messages', (req, res) => {
res.send(msgStore.getMsgs(req.session.code));
});
app.post('/messages/:msg', (req, res) => {
msgStore.putMsg(req.session.code, req.params.msg);
res.sendStatus(200);
});
app.get('/code', (req, res) => {
res.send(req.session.code);
});
module.exports = app;