-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthMiddleware.js
More file actions
69 lines (64 loc) · 2.21 KB
/
authMiddleware.js
File metadata and controls
69 lines (64 loc) · 2.21 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
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
/*const jwt = require("jsonwebtoken");
const APP_SECRET = "myappsecret";
const USERNAME = "admin";
const PASSWORD = "secret";
module.exports = function (req, res, next) {
if (req.url == "/login" && req.method == "POST") {
if (req.body != null && req.body.name == 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.method != "GET")
|| (req.url.startsWith("/orders") && req.method != "POST")) {
let token = req.headers["authorization"];
if (token != null && token.startsWith("Bearer<")) {
token = token.substring(7, token.length - 1);
try {
jwt.verify(token, APP_SECRET);
next();
return;
} catch (err) { }
}
res.statusCode = 401;
res.end();
return;
}
next();
} */
const jwt = require("jsonwebtoken");
const APP_SECRET = "myappsecret";
const USERNAME = "admin";
const PASSWORD = "secret";
module.exports = function (req, res, next) {
if (req.url == "/login" && req.method == "POST") {
if (req.body != null && req.body.name == 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.method != "GET")
|| (req.url.startsWith("/orders") && req.method != "POST")) {
let token = req.headers["authorization"];
if (token != null && token.startsWith("Bearer<")) {
token = token.substring(7, token.length - 1);
try {
jwt.verify(token, APP_SECRET);
next();
return;
} catch (err) { }
}
res.statusCode = 401;
res.end();
return;
}
next();
}