-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
93 lines (82 loc) · 2.41 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
const express = require('express');
const jwt = require('jsonwebtoken');
const sharp = require('sharp');
const download = require('image-downloader');
const jsonpatch = require('json-patch');
const bodyParser = require('body-parser');
const path = require('path');
const morgan = require('morgan');
const app = express();
app.use(express.static('./thumbnails'));
app.use(bodyParser.json());
app.use(morgan('dev'));
// FORMAT OF TOKEN
// Authorization: Bearer <access_token>
function setToken(req, res, next) {
const bearerHeader = req.headers.authorization;
// check if bearer is undefined
if (typeof bearerHeader !== 'undefined') {
// Split at space
const bearer = bearerHeader.split(' ');
// get token from array
const bearerToken = bearer[1];
// set the token
req.token = bearerToken;
// next middleware
next();
} else {
// Forbidden
res.sendStatus(403);
}
}
function verifyToken(req, res, next) {
jwt.verify(req.token, 'the lost world', (err) => {
if(err) {
res.sendStatus(403);
} else {
next();
}
});
}
app.get('/', (req, res) => {
res.json({
message: 'welcome to the microservice: go to /login route and enter username and password'
});
});
app.post('/thumb', setToken, verifyToken, (req, res) => {
const options = {
url: req.body.url,
dest: path.join(__dirname, '/thumbnails/'),
};
download.image(options)
.then(({ filename, image }) => {
sharp(image)
.resize(50, 50)
.toFile(filename, () => {
res.sendFile(filename);
});
}).catch((err) => {
throw err;
});
});
app.post('/ptch', setToken, verifyToken, (req, res) => {
const patch = jsonpatch.apply(req.body, [{ op: 'add', path: '/foo', value: 'bar' },
{ op: 'add', path: '/hello', value: ['world'] },
]);
res.json(patch);
});
app.post('/login', (req, res) => {
const user = {
username: req.body.user,
password: req.body.password,
};
jwt.sign({ user }, 'the lost world', { expiresIn: '120s' }, (err, token) => {
res.json({
token,
});
});
});
module.exports = app;
app.listen(process.env.PORT || 4000, () => {
console.log('server running on port 4000');
});