-
Notifications
You must be signed in to change notification settings - Fork 3
/
server.js
81 lines (68 loc) · 2.05 KB
/
server.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
require('dotenv').config({ path: '.env' });
const express = require('express');
const morgan = require('morgan');
const mongoose = require('mongoose');
const cors = require('cors');
const mainRouter = require('./routes');
const app = express();
const Token = require('./models/token');
// Environment variables for database username and password
const dbUser = process.env.atlasUser;
const dbPass = process.env.atlasPassword;
const clusterName = process.env.atlasClusterName;
const dbName = process.env.atlasDBName;
const dbURI = `mongodb+srv://${dbUser}:${dbPass}@${clusterName}/${dbName}?retryWrites=true&w=majority`;
const PORT = 3000;
mongoose.set('strictQuery', false);
// connect to MongoDB
mongoose
.connect(dbURI)
.then((result) => {
app.listen(PORT);
console.log(`Listening on port ${PORT}...`);
})
.catch((err) => {
console.log(err);
});
app.use(express.json());
app.use(morgan('dev'));
// add access control headers from all origins
app.use(
cors({
origin: '*',
})
);
// Token authentication for non GET requests
app.use((req, res, next) => {
if (req.method === 'GET') {
return next();
}
// fetch required token from database
Token.findOne({ name: 'BearerToken' })
.then((requiredToken) => {
// check if token is valid if it exists
if (!req.headers.authorization) {
return res.status(401).json('Token not found');
}
if (
req.headers.authorization.split(' ')[1] !== requiredToken.value
) {
return res.status(401).json('Invalid token');
}
next();
})
.catch((err) => {
console.log(err);
});
});
// health check
app.get('/health-check', (req, res) => res.send('OK'));
// routes
app.use(mainRouter);
// 404 error
app.use((req, res) => res.status(404).json(`Cannot ${req.method} ${req.url}`));
// error handling
app.use((err, req, res, next) => {
console.log(err);
res.status(500).json('Internal server error');
});