-
Notifications
You must be signed in to change notification settings - Fork 1
/
auth-middleware.js
38 lines (34 loc) · 1008 Bytes
/
auth-middleware.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
const jwt = require('jsonwebtoken');
const app_secret = 'myAppSecret';
const username = 'admin';
const password = 'secret';
module.exports = (req, res, next) => {
if (req.url === '/login' && req.method === 'POST') {
if (req.body.username === username && req.body.password === password) {
let token = jwt.sign({data: username, expiresIn: '1h'}, app_secret);
res.json({success: true, token: token});
} else {
res.json({success: false});
}
res.end();
return;
} else {
if ((req.url.startsWith("/products") || req.url.startsWith("/categories")) && (req.method != 'GET')) {
let token = req.headers['authorization'];
if (token != null) {
// down function Bearer<TOKEN> -> TOKEN
token = token.substring(7, token.length-1);
try {
jwt.verify(token, app_secret);
next();
return;
}
catch (err) { }
}
res.statusCode = 401;
res.end();
return;
}
}
next();
};