@nsshunt/stsutils 1.5.2 → 1.5.5

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.
@@ -0,0 +1,87 @@
1
+ const debug = require('debug')(`stsutils`);
2
+ const colors = require('colors');
3
+ const axios = require('axios');
4
+
5
+ class AuthUtilsBrowser
6
+ {
7
+ constructor()
8
+ {
9
+
10
+ }
11
+
12
+ #GetDurationColour(duration)
13
+ {
14
+ if (duration > 250) {
15
+ return colors.red;
16
+ } else if (duration > 150) {
17
+ return colors.magenta;
18
+ } else if (duration > 50) {
19
+ return colors.blue;
20
+ } else if (duration > 10) {
21
+ return colors.green;
22
+ } else {
23
+ return colors.black;
24
+ }
25
+ }
26
+
27
+ LoginBrowser = async (options) => {
28
+ const { authendpoint, authUserName, authUserEMail, authUserPassword, defaultTimeout, publishDebug } = options;
29
+ try {
30
+ let processStart = performance.now();
31
+ let duration = 0;
32
+ let accessToken = null;
33
+ let payload = { name: authUserName, password: authUserPassword, email: authUserEMail }
34
+ let retVal = await axios({
35
+ url: `${authendpoint}/login`
36
+ ,method: 'post'
37
+ ,data: payload
38
+ ,timeout: defaultTimeout
39
+ });
40
+ duration = (performance.now() - processStart).toFixed(4);
41
+ if (publishDebug) debug(this.#GetDurationColour(duration)(`AuthUtils.LoginBrowser request duration: [${duration}]`));
42
+ accessToken = retVal.data.detail.token;
43
+ return {
44
+ accessToken: accessToken,
45
+ duration: duration
46
+ }
47
+ } catch (error) {
48
+ if (publishDebug) debug(`Error (AuthUtils:LoginBrowser): ${error}`.red);
49
+ throw error;
50
+ }
51
+ };
52
+
53
+ // https://stackoverflow.com/questions/43002444/make-axios-send-cookies-in-its-requests-automatically
54
+ // axios.get('some api url', {withCredentials: true});
55
+ // https://medium.com/@adityasrivast/handling-cookies-with-axios-872790241a9b
56
+ // https://www.codegrepper.com/code-examples/javascript/axios+send+cookies
57
+ // http only cookies
58
+ RefreshAuthTokenBrowser = async (options) => {
59
+ const { authendpoint, defaultTimeout, publishDebug } = options;
60
+ try {
61
+ let processStart = performance.now();
62
+ let duration = 0;
63
+ let accessToken = null;
64
+ // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials
65
+ // https://stackoverflow.com/questions/43002444/make-axios-send-cookies-in-its-requests-automatically
66
+ // axios.get('some api url', {withCredentials: true});
67
+ let retVal = await axios({
68
+ url: `${authendpoint}/refreshtoken`
69
+ ,method: 'post'
70
+ ,timeout: defaultTimeout
71
+ ,withCredentials: true
72
+ });
73
+ duration = (performance.now() - processStart).toFixed(4);
74
+ if (publishDebug) debug(this.#GetDurationColour(duration)(`AuthUtils.RefreshAuthTokenBrowser request duration: [${duration}]`));
75
+ accessToken = retVal.data.detail.token;
76
+ return {
77
+ accessToken: accessToken,
78
+ duration: duration
79
+ }
80
+ } catch (error) {
81
+ if (publishDebug) debug(`Error (AuthUtils:RefreshAuthTokenBrowser): ${error}`.red);
82
+ throw error;
83
+ }
84
+ }
85
+ }
86
+
87
+ module.exports = AuthUtilsBrowser;
package/index.js ADDED
@@ -0,0 +1,6 @@
1
+ let sleep = require('./sleep.js');
2
+ let status = require('./status.js');
3
+ const AuthUtilsBrowser = require('./authutilsbrowser.js');
4
+ const STSOptionsBase = require('./stsoptionsbase.js');
5
+
6
+ module.exports = { sleep, status, STSOptionsBase, AuthUtilsBrowser };
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@nsshunt/stsutils",
3
- "version": "1.5.2",
3
+ "version": "1.5.5",
4
4
  "description": "",
5
- "main": "stsutils.js",
5
+ "main": "index.js",
6
6
  "scripts": {
7
7
  "lint": "eslint . --ext js,jsx,ts,tsx --fix",
8
8
  "test": "jest --detectOpenHandles --no-cache",
package/stsoptionsbase.js CHANGED
@@ -21,4 +21,4 @@ class STSOptionsBase
21
21
  }
22
22
  }
23
23
 
24
- module.exports = { STSOptionsBase };
24
+ module.exports = STSOptionsBase;
package/authutils.js DELETED
@@ -1,298 +0,0 @@
1
- const debug = require('debug')(`stsutils`);
2
- const jwt = require('jsonwebtoken');
3
- const { status } = require('./status');
4
- const fs = require('fs');
5
- const goptions = require('@nsshunt/stsconfig').$options;
6
- const tough = require('tough-cookie');
7
- const Cookie = tough.Cookie;
8
- const cookiejar = new tough.CookieJar();
9
- const colors = require('colors');
10
- const axios = require('axios');
11
- const http = require('http');
12
-
13
- class AuthUtils
14
- {
15
- #privateKey = null;
16
- #publicKey = null;
17
- #httpAgent = null;
18
-
19
- constructor()
20
- {
21
- // On-line key generators
22
- // http://travistidwell.com/jsencrypt/demo/
23
- // https://www.csfieldguide.org.nz/en/interactives/rsa-key-generator/
24
- // https://jwt.io/
25
- }
26
-
27
- // This code is for development / non-prod purposes only.
28
- // For production, the keys to come from a secrets store.
29
- get privateKey()
30
- {
31
- if (this.#privateKey === null) {
32
- this.#privateKey = fs.readFileSync(goptions.asprivatekeypath, 'utf8');
33
- }
34
- return this.#privateKey;
35
- }
36
-
37
- // This code is for development / non-prod purposes only.
38
- // For production, the keys to come from a secrets store.
39
- get publicKey()
40
- {
41
- if (this.#publicKey === null) {
42
- this.#publicKey = fs.readFileSync(goptions.aspublickeypath, 'utf8');
43
- }
44
- return this.#publicKey;
45
- }
46
-
47
- /*
48
- // Source;
49
- // https://github.com/auth0/jwt-decode/issues/53
50
- #assertAlive(decoded)
51
- {
52
- const now = Date.now().valueOf() / 1000
53
- if (typeof decoded.exp !== 'undefined' && decoded.exp < now) {
54
- throw new Error(`token expired: ${JSON.stringify(decoded)}`)
55
- }
56
- if (typeof decoded.nbf !== 'undefined' && decoded.nbf > now) {
57
- throw new Error(`token not yet valid: ${JSON.stringify(decoded)}`)
58
- }
59
- }
60
-
61
- #tokenTimeLeft(decoded)
62
- {
63
- const now = Date.now().valueOf() / 1000;
64
- return now - decoded.exp;
65
- }
66
- */
67
-
68
- async verifyRequestMiddleware(req, res, next)
69
- {
70
- try
71
- {
72
- let authHeader = req.header('Authorization');
73
- if (authHeader === undefined)
74
- {
75
- res.status(status.unauthorized).send( { status: status.unauthorized, error: 'Token not preset', detail: { message: 'The Authorization header not provided.' } } );
76
- return;
77
- }
78
- let authType = authHeader.split(' ')[0];
79
- let token = authHeader.split(' ')[1];
80
-
81
- if (authType !== 'Bearer')
82
- {
83
- res.status(status.unauthorized).send( { status: status.unauthorized, error: 'Token not preset', detail: { message: 'The Authorization type provided is not Bearer.' } } );
84
- return;
85
- }
86
-
87
- let i = 'STS';
88
- //let s = user.id;
89
- //let a = user.email;
90
-
91
- let verifyOptions =
92
- {
93
- issuer: i,
94
- //subject: s,
95
- //audience: a,
96
- //expiresIn: 600, // 10 minutes
97
- algorithm: ["RS256"] // RSASSA [ "RS256", "RS384", "RS512" ]
98
- };
99
-
100
- let retVal = jwt.verify(token, this.publicKey, verifyOptions);
101
-
102
- req.stsuser = {
103
- email: retVal.user.email,
104
- userid: retVal.user.id,
105
- isadmin: false,
106
- firstname: retVal.user.name,
107
- lastname: 'NA'
108
- };
109
-
110
- next();
111
- } catch (error)
112
- {
113
- if (error instanceof jwt.JsonWebTokenError)
114
- {
115
- res.status(status.unauthorized).send( { status: status.unauthorized, error: 'Invalid Token', detail: error } );
116
- } else{
117
- res.status(status.error).send( { status: status.error, error: 'Operation was not successful', detail: error } );
118
- }
119
- }
120
- }
121
-
122
- #GetDurationColour(duration)
123
- {
124
- if (duration > 250) {
125
- return colors.red;
126
- } else if (duration > 150) {
127
- return colors.magenta;
128
- } else if (duration > 50) {
129
- return colors.blue;
130
- } else if (duration > 10) {
131
- return colors.green;
132
- } else {
133
- return colors.black;
134
- }
135
- }
136
-
137
- LoginBrowser = async (options) => {
138
- const { authendpoint, authUserName, authUserEMail, authUserPassword, defaultTimeout, publishDebug } = options;
139
- try {
140
- let processStart = performance.now();
141
- let duration = 0;
142
- let accessToken = null;
143
- let payload = { name: authUserName, password: authUserPassword, email: authUserEMail }
144
- let retVal = await axios({
145
- url: `${authendpoint}/login`
146
- ,method: 'post'
147
- ,data: payload
148
- ,timeout: defaultTimeout
149
- });
150
- duration = (performance.now() - processStart).toFixed(4);
151
- if (publishDebug) debug(this.#GetDurationColour(duration)(`AuthUtils.LoginBrowser request duration: [${duration}]`));
152
- accessToken = retVal.data.detail.token;
153
- return {
154
- accessToken: accessToken,
155
- duration: duration
156
- }
157
- } catch (error) {
158
- if (publishDebug) debug(`Error (AuthUtils:LoginBrowser): ${error}`.red);
159
- throw error;
160
- }
161
- };
162
-
163
- // https://stackoverflow.com/questions/43002444/make-axios-send-cookies-in-its-requests-automatically
164
- // axios.get('some api url', {withCredentials: true});
165
- // https://medium.com/@adityasrivast/handling-cookies-with-axios-872790241a9b
166
- // https://www.codegrepper.com/code-examples/javascript/axios+send+cookies
167
- // http only cookies
168
- RefreshAuthTokenBrowser = async (options) => {
169
- const { authendpoint, defaultTimeout, publishDebug } = options;
170
- try {
171
- let processStart = performance.now();
172
- let duration = 0;
173
- let accessToken = null;
174
- // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials
175
- // https://stackoverflow.com/questions/43002444/make-axios-send-cookies-in-its-requests-automatically
176
- // axios.get('some api url', {withCredentials: true});
177
- let retVal = await axios({
178
- url: `${authendpoint}/refreshtoken`
179
- ,method: 'post'
180
- ,timeout: defaultTimeout
181
- ,withCredentials: true
182
- });
183
- duration = (performance.now() - processStart).toFixed(4);
184
- if (publishDebug) debug(this.#GetDurationColour(duration)(`AuthUtils.RefreshAuthTokenBrowser request duration: [${duration}]`));
185
- accessToken = retVal.data.detail.token;
186
- return {
187
- accessToken: accessToken,
188
- duration: duration
189
- }
190
- } catch (error) {
191
- if (publishDebug) debug(`Error (AuthUtils:RefreshAuthTokenBrowser): ${error}`.red);
192
- throw error;
193
- }
194
- }
195
-
196
- #setCookiesToJar = (authendpoint, headers) =>
197
- {
198
- let cookies = null;
199
- if (headers['set-cookie'] instanceof Array)
200
- cookies = headers['set-cookie'].map(Cookie.parse);
201
- else
202
- cookies = [Cookie.parse(headers['set-cookie'])];
203
-
204
- return cookiejar.setCookie(cookies[0], `${authendpoint}`);
205
- };
206
-
207
- #getCookiesFromJar = (authendpoint) =>
208
- {
209
- return cookiejar.getCookies(`${authendpoint}`);
210
- };
211
-
212
- #getHttpAgent = () =>
213
- {
214
- if (this.#httpAgent === null) {
215
- // https://nodejs.org/api/http.html#class-httpagent
216
- this.#httpAgent = new http.Agent({
217
- keepAlive: true,
218
- maxSockets: 10,
219
- maxTotalSockets: 10,
220
- maxFreeSockets: 10,
221
- timeout: 5000
222
- });
223
- }
224
- return this.#httpAgent;
225
- }
226
-
227
- LoginNode = async (options) =>
228
- {
229
- const { authendpoint, authUserName, authUserEMail, authUserPassword, defaultTimeout, publishDebug } = options;
230
- try {
231
- let processStart = performance.now();
232
- let duration = 0;
233
- let accessToken = null;
234
- let payload = { name: authUserName, password: authUserPassword, email: authUserEMail }
235
- let retVal = await axios({
236
- url: `${authendpoint}/login`
237
- ,method: 'post'
238
- ,data: payload
239
- ,timeout: defaultTimeout
240
- ,httpAgent: this.#getHttpAgent()
241
- // Use below if using a socket endpoint
242
- //,socketPath: '/var/run/sts/stsrest01.sock'
243
- });
244
- duration = (performance.now() - processStart).toFixed(4);
245
- if (publishDebug) debug(this.#GetDurationColour(duration)(`AuthUtils.LoginNode request duration: [${duration}]`));
246
- accessToken = retVal.data.detail.token;
247
- await this.#setCookiesToJar(authendpoint, retVal.headers);
248
- return {
249
- accessToken: accessToken,
250
- duration: duration
251
- }
252
- } catch (error)
253
- {
254
- if (publishDebug) debug(`Error (AuthUtils:LoginNode): ${error}`.red);
255
- throw error;
256
- }
257
- }
258
-
259
- // https://stackoverflow.com/questions/43002444/make-axios-send-cookies-in-its-requests-automatically
260
- // axios.get('some api url', {withCredentials: true});
261
- // https://medium.com/@adityasrivast/handling-cookies-with-axios-872790241a9b
262
- // https://www.codegrepper.com/code-examples/javascript/axios+send+cookies
263
- // http only cookies
264
- RefreshAuthTokenNode = async (options) =>
265
- {
266
- const { authendpoint, defaultTimeout, publishDebug } = options;
267
- try {
268
- let processStart = performance.now();
269
- let duration = 0;
270
- let accessToken = null;
271
- let cookies = await this.#getCookiesFromJar(authendpoint);
272
- let retVal = await axios({
273
- url: `${authendpoint}/refreshtoken`
274
- ,method: 'post'
275
- ,headers: {
276
- Cookie: cookies
277
- }
278
- ,timeout: defaultTimeout
279
- ,httpAgent: this.#httpAgent,
280
- // Use below for socket connections
281
- //,socketPath: '/var/run/sts/stsrest01.sock'
282
- });
283
- duration = (performance.now() - processStart).toFixed(4);
284
- if (publishDebug) debug(this.#GetDurationColour(duration)(`AuthUtils.RefreshAuthTokenBrowser request duration: [${duration}]`));
285
- accessToken = retVal.data.detail.token;
286
- await this.#setCookiesToJar(authendpoint, retVal.headers);
287
- return {
288
- accessToken: accessToken,
289
- duration: duration
290
- }
291
- } catch (error) {
292
- if (publishDebug) debug(`Error (AuthUtils:RefreshAuthTokenBrowser): ${error}`.red);
293
- throw error;
294
- }
295
- }
296
- }
297
-
298
- module.exports = { AuthUtils };
package/stsrouterbase.js DELETED
@@ -1,21 +0,0 @@
1
- const express = require('express');
2
-
3
- const { STSOptionsBase } = require('./stsoptionsbase.js');
4
-
5
- class STSRouterBase extends STSOptionsBase
6
- {
7
- #router = null;
8
-
9
- constructor(options)
10
- {
11
- super(options);
12
- this.#router = express.Router();
13
- }
14
-
15
- get Router()
16
- {
17
- return this.#router;
18
- }
19
- }
20
-
21
- module.exports = { STSRouterBase };
package/stsutils.js DELETED
@@ -1,7 +0,0 @@
1
- let sleep = require('./sleep.js');
2
- let status = require('./status.js');
3
- let authutils = require('./authutils.js');
4
- let stsoptionsbase = require('./stsoptionsbase.js');
5
- let stsrouterbase = require('./stsrouterbase.js');
6
-
7
- module.exports = { sleep, status, authutils, stsoptionsbase, stsrouterbase };