-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
106 lines (74 loc) · 2.26 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
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
/*
Setup
*/
require('dotenv').config()
// Import some basic stuff
const express = require('express'),
app = express(),
basicAuth = require('express-basic-auth'),
bodyParser = require('body-parser'),
rateLimit = require('express-rate-limit'),
noiseRoutes = require('./routes/noiseRoutes'),
typeRoutes = require('./routes/typeRoutes'),
searchRoutes = require('./routes/searchRoutes'),
reporterRoutes = require('./routes/reporterRoutes'),
bookshelf = require('./database');
app.set('trust proxy', 1);
// Set some basic stuff
const ENVIROMENT = process.env.NODE_ENV;
const PORT = process.env.PORT;
const apiLimiter = rateLimit({
windowMs: 5 * 1000, // 5 seconds
max: 1
});
/*
Middleware stack
*/
// headers to fix CORS issues
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// body parser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// rate limiter
app.use('/api/', apiLimiter);
// Catch all api route for api_key authentication
app.all('/api/*', (req, res, next) => {
// Check for API KEY
let keyToCheck = req.query.api_key;
let api_key = process.env.API_KEY;
let editor_key = process.env.EDITOR_KEY;
let admin_key = process.env.ADMIN_KEY;
// If one of the API_KEY does not match send a 403 forbidden error
if (keyToCheck === api_key || keyToCheck === editor_key || keyToCheck === admin_key) {
// If API_KEY matches keep going
next();
}
else {
// Give error if there are no matches to API_KEYs
res.status(403).send('Not allowed.');
return;
}
});
// Mount routes
app.use('/api', noiseRoutes);
app.use('/api', typeRoutes);
app.use('/api', searchRoutes);
app.use('/api', reporterRoutes);
// Authenticate public pages
app.use('/', basicAuth({
users: { 'admin': process.env.SITE_PASSWORD },
challenge: true,
realm: 'zach-noise-api'
}));
// look at public folder for static assets
app.use(express.static(__dirname + '/public'));
/*
Listen
*/
app.listen(PORT, () => {
console.log('Server up on', PORT);
});