-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
62 lines (45 loc) · 1.28 KB
/
index.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
const express = require('express');
const jwt = require('jsonwebtoken');
const jwtSecretKey = 'my-private-secret-key';
const generateToken = (req) => {
return jwt.sign({ userId: 1, rule: 'admin' }, jwtSecretKey);
};
const validateToken = (req, res, next) => {
const token = (req.headers.authorization || '').replace(/bearer\s/i, '');
console.log('validate token', {token});
let tokenError = '';
try {
if (token === '')
tokenError = 'Token is required';
else {
const tokenPayload = token && jwt.verify(token, jwtSecretKey);
console.log('token payload', { tokenPayload });
}
}
catch(error) {
tokenError = error.message;
}
if (tokenError) {
res.status(401).send(tokenError);
return;
}
next();
};
const app = express();
app.get('/', (req, res) => {
res.send('public');
});
app.get('/private', validateToken, (req, res) => {
res.send('private');
});
app.get('/login', (req, res) => {
const userOk = true;
if (userOk) {
const token = generateToken(req);
res.send(token);
}
else
res.status(401);
});
const PORT = process.env.PORT || 50001;
app.listen(PORT, e => console.log(`Server started in http://localhost:${PORT}`));