-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
68 lines (55 loc) · 1.63 KB
/
server.js
File metadata and controls
68 lines (55 loc) · 1.63 KB
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
const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('db.json');
const middlewares = jsonServer.defaults();
// Generate access token
function makeToken(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
// Use default middlewares (e.g. cors, logger)
server.use(middlewares);
// Parse json from request body
server.use(jsonServer.bodyParser);
// Protect admin paths
server.use((req, res, next) => {
let authorized = false;
if (req.method === 'GET' || req.path === '/login') {
next();
} else {
const token = req.headers.authorization;
router.db.get('tokens').value().forEach((_token) => {
if (token === 'Bearer ' + _token) {
authorized = true;
next();
}
});
if (!authorized) res.sendStatus(401);
}
});
// Admin authorization
server.post('/login', (req, res) => {
const credentials = req.body;
router.db.get('users').value().forEach((user) => {
if (user.login === credentials.login && user.password === credentials.password) {
// Generate token
const token = makeToken(100);
// Add token to DB
router.db.get('tokens').push(token).write();
res.json({
accessToken: token
});
}
});
});
// Default json-server behaviour
server.use(router);
// Launch server
server.listen(5500, () => {
console.log('JSON server is running');
});