-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbooks.js
81 lines (68 loc) · 1.64 KB
/
books.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
const { response } = require('express');
const express = require('express');
const jwt = require('express-jwt');
const jsonwebtoken = require('jsonwebtoken');
const app = express();
const books = [
{
"author": "Chinua Achebe",
"country": "Nigeria",
"language": "English",
"pages": 209,
"title": "Things Fall Apart",
"year": 1958
},
{
"author": "Hans Christian Andersen",
"country": "Denmark",
"language": "Danish",
"pages": 784,
"title": "Fairy tales",
"year": 1836
},
{
"author": "Dante Alighieri",
"country": "Italy",
"language": "Italian",
"pages": 928,
"title": "The Divine Comedy",
"year": 1315
},
];
const accessTokenSecret = 'asfdlkjgwoagagwgwegwegwe';
const authenticateJWT = (req, res, next) =>
{
const authHeader = req.headers.authorization;
if (authHeader)
{
const token = authHeader.split(' ')[1];
jwt.verify(token, accessTokenSecret, (err, user) =>
{
if (err) {
return res.sendStatus(403);
}
req.user = user;
next();
});
}
else
{
res.sendStatus(401);
}
};
app.get('/books', (req, res) => {
res.json(books);
});
app.post('/books', authenticateJWT, (req, res) => {
const { role } = req.user;
if (role !== 'admin')
{
return res.sendStatus(403);
}
const book = req.body;
books.push(book);
res.send('Book added successfully');
});
app.listen(4000, () => {
console.log('Books service started on port 4000');
});