forked from sanqianpiao/bearerjs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bearer.js
169 lines (148 loc) · 5.48 KB
/
bearer.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
//Authentication setup
var CryptoJS = require('node-cryptojs-aes').CryptoJS;
function matchPath(mask, path) {
mask = mask.toLowerCase();
path = path.toLowerCase();
if (path.indexOf("?") > 0)
path = path.substring(0, path.indexOf("?"));
var maskArray = mask.split("/");
var pathArray = path.split("/");
if (maskArray.length != pathArray.length) return false;
for (var i = 0; i < maskArray.length; i++) {
if ((maskArray[i] != "*") && (pathArray[i] != maskArray[i])) return false;
}
return true;
}
//Check if route should be authorized and return route setting
function checkUrl(url, method, routes) {
method = method.toLowerCase();
for (var i = 0; i < routes.length; i++) {
var route = routes[i];
if ((matchPath(route.url, url)) && (method == route.method)) return route;
}
return false;
}
function decryptToken(settings) {
var decrypted = CryptoJS.AES.decrypt(settings.bearer, settings.serverKey);
var token;
try {
token = JSON.parse(CryptoJS.enc.Utf8.stringify(decrypted));
} catch (e) {
}
return token;
}
function bearerJS(settings) {
//Check if URL should be authenticated and redirect accordingly
settings.app.use(async function (req, res, next) {
//var bearer=req.get('Authorization');
var bearer = req.get('Authorization');
var token;
if (bearer) {
bearer = bearer.replace('Bearer ', '');
token = decryptToken({
bearer: bearer,
serverKey: settings.serverKey
});
}
var proceed = function () {
req.authToken = token;
req.isAuthenticated = true;
if (settings.onAuthorized) {
settings.onAuthorized(req, token, res);
}
next();
};
var cancel = function (statusCode, errorMessage) {
res.statusCode = (statusCode || 401);
res.statusText = errorMessage;
if (settings.onUnauthorized) {
settings.onUnauthorized(req, token, res, errorMessage);
} else {
res.send({ error: errorMessage });
}
};
var isAuthenticated = false;
var routeCheck = checkUrl(req.url, req.method.toLowerCase(), settings.secureRoutes);
if (routeCheck) {
if (token) {
var tokenValid = await settings.validateToken(req, token);
if (!tokenValid) {
cancel(401, "Token expired or not valid");
} else //Authorized request
{
if (settings.onTokenValid) {
settings.onTokenValid(token, function () {
if (routeCheck.roles) { //if there is a Role based limit to request
settings.userInRole(token, routeCheck.roles, function () { proceed() }, function () { cancel(401, "User role rejected") });
} else {
proceed();
}
}, function () { cancel(401, "User disabled") });
} else {
if (routeCheck.roles) { //if there is a Role based limit to request
settings.userInRole(token, routeCheck.roles, function () { proceed() }, function () { cancel(401, "User role rejected") });
} else {
proceed();
}
}
}
} else {
cancel(401, "Invalid token");
}
} else {
proceed();
}
});
//Extend existing token without validating password again
settings.app.post(settings.extendTokenUrl, function (req, res) {
var proceed = function (token) {
if (!Array.isArray(token)) {
token = [token];
}
const resultTokenArray = [];
for (const singleToken of token) {
resultTokenArray.push(buildJsonToken(singleToken));
}
res.send(resultTokenArray);
}
var cancel = function () {
res.statusCode = 401;
res.send({ error: "Token not provided" });
};
settings.extendToken(req, function (token) { proceed(token); }, function () { cancel() });
});
//get token value
settings.app.post(settings.tokenUrl, function (req, res) {
var proceed = function (token) {
if (!Array.isArray(token)) {
token = [token];
}
const resultTokenArray = [];
for (const singleToken of token) {
resultTokenArray.push(buildJsonToken(singleToken));
}
res.send(resultTokenArray);
}
var cancel = function (data) {
res.statusCode = 401;
res.send({
error: "Login failed",
data: data
});
};
settings.createToken(req, function (token) { proceed(token); }, function (data) { cancel(data) });
});
function buildJsonToken(token) {
var encrypted = CryptoJS.AES.encrypt(JSON.stringify(token), settings.serverKey);
var bearer = encrypted.toString();
var jsonToken = {
access_token: bearer,
expDate: token.expire || token.exp
};
return jsonToken;
}
}
module.exports = {
bearer: bearerJS,
decryptToken: decryptToken
};