corebasic 1.0.7 → 1.0.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/libs/app.js +4 -2
- package/libs/session.js +66 -0
- package/package.json +1 -1
package/libs/app.js
CHANGED
package/libs/session.js
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
const jwt = require('jsonwebtoken');
|
|
2
|
+
let app
|
|
3
|
+
|
|
4
|
+
module.exports = {
|
|
5
|
+
start,
|
|
6
|
+
generateAccessToken,
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
const ACCESS_TOKEN_SECRET = process.env.JWT_ACCESS_TOKEN_SECRET || "MY_SECRET_ACCESS_TOKEN";
|
|
12
|
+
const REFRESH_TOKEN_SECRET = process.env.JWT_REFRESH_TOKEN_SECRET || "MY_SECRET_REFRESH_TOKEN";
|
|
13
|
+
|
|
14
|
+
let urlsAllowed = []
|
|
15
|
+
|
|
16
|
+
function start(expressApp, allowedUrls) {
|
|
17
|
+
urlsAllowed = ["/refreshToken"].concat(allowedUrls)
|
|
18
|
+
app = expressApp
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
app.use((req, res, next) => {
|
|
22
|
+
|
|
23
|
+
// return next() // Disable session
|
|
24
|
+
|
|
25
|
+
if (urlsAllowed.includes(req.path))
|
|
26
|
+
return next()
|
|
27
|
+
|
|
28
|
+
try {
|
|
29
|
+
const token = req.header('JWT'); // 'Authorization' for Spring Boot, 'x-access-token' for Node.js Express back-end
|
|
30
|
+
if (jwt.verify(token, ACCESS_TOKEN_SECRET))
|
|
31
|
+
return next()
|
|
32
|
+
throw null;
|
|
33
|
+
} catch (error) {
|
|
34
|
+
return res.status(406).json({ message: 'Unauthorized' })
|
|
35
|
+
}
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
app.post("/refreshToken", (req, res) => {
|
|
39
|
+
try {
|
|
40
|
+
let { userId, clientId, refreshToken } = req.body
|
|
41
|
+
const decoded = jwt.verify(refreshToken, REFRESH_TOKEN_SECRET)
|
|
42
|
+
if (decoded.userId === userId && decoded.clientId === clientId) {
|
|
43
|
+
const accessToken = jwt.sign({ userId, clientId }, ACCESS_TOKEN_SECRET, { expiresIn: '1d' });
|
|
44
|
+
const refreshToken = jwt.sign({ userId, clientId }, REFRESH_TOKEN_SECRET, { expiresIn: '30d' });
|
|
45
|
+
return res.json({ tokens: { accessToken, refreshToken } });
|
|
46
|
+
}
|
|
47
|
+
// Access Denied
|
|
48
|
+
throw null;
|
|
49
|
+
|
|
50
|
+
} catch (error) {
|
|
51
|
+
// Access Denied
|
|
52
|
+
return res.status(406).json({ message: 'Unauthorized' })
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
function generateAccessToken(userId, clientId) {
|
|
59
|
+
let data = { userId, clientId }
|
|
60
|
+
|
|
61
|
+
const accessToken = jwt.sign(data, ACCESS_TOKEN_SECRET, { expiresIn: '1d' });
|
|
62
|
+
const refreshToken = jwt.sign(data, REFRESH_TOKEN_SECRET, { expiresIn: '30d' });
|
|
63
|
+
return { accessToken, refreshToken };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
|