-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinitApp.js
64 lines (54 loc) · 1.96 KB
/
initApp.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
const bodyparser = require('body-parser');
const jwtExpress = require('express-jwt');
const jwt = require('jsonwebtoken');
const path = require('path');
module.exports = (app, controller, config, redisClient, rateLimiter) => {
const view = () => {
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname + '/index.html'));
});
}
const initUnprotected = () => {
app.post('/authenticate', (req, res) =>
controller.verifyUser(req.body.user, req.body.password)
.then((userData) => {
delete userData.password;
res.json({
message: 'Enjoy your token!',
token: jwt.sign(userData, config.app.secretKey , { expiresIn: 60 * 60 })
})
})
.catch((error) => res.status(401).send({ error }))
);
};
const initProtected = () => {
app.use(jwtExpress({ secret: config.app.secretKey }));
app.use(checkRate);
app.use(updateRateHeaders);
app.get('/index', (req, res) => {
controller.getData(req.query)
.then((data) => { res.json(data) })
});
app.get('/indexes', (req, res) => {
controller.getValues(req.user)
.then((data) => { res.json(data) })
});
};
const checkRate = rateLimiter.middleware({
redis: redisClient,
key: (req) => req.user.id,
rate: config.rateLimiter.rate
});
const updateRateHeaders = (req,res,next) => {
res.append('X-Rate-Limit', config.rateLimiter.rate);
redisClient.get('ratelimit:'+req.user.id, (err, reply) => {
res.append('X-Rate-Limit-Remaining', config.rateLimiter.number - reply);
next();
});
}
app.use(bodyparser.urlencoded({ extended: true }));
app.use(bodyparser.json());
view();
initUnprotected();
initProtected();
};