-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson-server.js
55 lines (47 loc) · 1.31 KB
/
json-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
const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('db.json');
const middlewares = jsonServer.defaults();
const bodyParser = require('body-parser');
const jwtToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiU2l0ZVBvaW50IFJ' +
'lYWRlciJ9.sS4aPcmnYfm3PQlTtH14az9CGjWkjnsDyG_1ats4yYg';
// Use default middlewares (CORS, static, etc)
server.use(middlewares);
// Make sure JSON bodies are parsed correctly
server.use(bodyParser.json());
// Handle sign-in requests
server.post('/sign-in', (req, res) => {
const username = req.body.username;
const password = req.body.password;
if(username === 'WitFlash' && password === 'admin') {
res.json({
name: 'My Todos App',
token: jwtToken
});
}
res.send(422, 'Invalid username and/or password');
});
// Protect other routes
server.use((req, res, next) => {
if (isAuthorized(req)) {
console.log('Access granted');
next();
} else {
console.log('Access denied, invalid Token');
res.sendStatus(401);
}
});
// API routes
server.use(router);
// Start server
server.listen(3000, () => {
console.log('JSON Server is running');
});
// Check whether request is allowed
function isAuthorized(req) {
let bearer = req.get('Authorization');
if (bearer === 'Bearer ' + jwtToken) {
return true;
}
return false;
}