-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthMiddleware.js
More file actions
30 lines (29 loc) · 1.13 KB
/
authMiddleware.js
File metadata and controls
30 lines (29 loc) · 1.13 KB
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
const jwt = require("jsonwebtoken");
const APP_SECRET = "myappsecret", USERNAME = "admin", PASSWORD = "secret";
const anonOps = [{ method: "GET", urls: ["/api/products", "/api/categories"] }, { method: "POST", urls: ["/api/orders"] }];
module.exports = function (req, res, next) {
if (anonOps.find(op => op.method === req.method
&& op.urls.find(url => req.url.startsWith(url)))) {
next();
} else if (req.url === "/login" && req.method === "POST") {
if (req.body[0].username === USERNAME && req.body[1].password === PASSWORD) {
res.json({
success: true,
token: jwt.sign({ data: USERNAME, expiresIn: "1h" }, APP_SECRET)
});
} else {
res.json({ success: false, reqBody: req.body });
}
res.end();
} else {
let token = req.headers["authorization"];
if (token != null && token.startsWith("Bearer<")) {
token = token.substring(7, token.length - 1);
jwt.verify(token, APP_SECRET);
next();
} else {
res.statusCode = 401;
res.end();
}
}
}