lesgo 0.7.7 → 1.0.0

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,201 @@
1
+ import app from 'Config/app'; // eslint-disable-line import/no-unresolved
2
+ import {
3
+ successHttpNoOutputResponseAfterHandler,
4
+ errorHttpNoOutputResponseAfterHandler,
5
+ } from '../httpNoOutputMiddleware';
6
+
7
+ describe('MiddlewareGroup: test successHttpNoOutputResponseAfterHandler', () => {
8
+ it('should have no body without debug', async () => {
9
+ const handler = {
10
+ response: {},
11
+ event: {},
12
+ };
13
+
14
+ await successHttpNoOutputResponseAfterHandler(handler, () => {}, {
15
+ response: 'Some message',
16
+ });
17
+ expect(handler.response).toHaveProperty('statusCode', 200);
18
+ expect(handler.response).toHaveProperty('body', '');
19
+ });
20
+
21
+ it('should return the body when debug is enabled via query string parameters', async () => {
22
+ const handler = {
23
+ response: {},
24
+ event: {
25
+ queryStringParameters: {
26
+ debug: '1',
27
+ },
28
+ someEventKey: 'someEventValue',
29
+ },
30
+ };
31
+
32
+ await successHttpNoOutputResponseAfterHandler(handler, () => {}, {
33
+ response: 'Some message',
34
+ });
35
+ expect(handler.response).toHaveProperty('statusCode', 200);
36
+ expect(handler.response).toHaveProperty(
37
+ 'body',
38
+ JSON.stringify({
39
+ status: 'success',
40
+ data: 'Some message',
41
+ _meta: {},
42
+ })
43
+ );
44
+ });
45
+
46
+ it('should have empty body even when enabled when configuration has is disabled', async () => {
47
+ app.debug = false;
48
+
49
+ const handler = {
50
+ response: {},
51
+ event: {
52
+ queryStringParameters: {
53
+ debug: '1',
54
+ },
55
+ someEventKey: 'someEventValue',
56
+ },
57
+ };
58
+
59
+ await successHttpNoOutputResponseAfterHandler(handler, () => {}, {
60
+ response: 'Some message',
61
+ });
62
+ expect(handler.response).toHaveProperty('statusCode', 200);
63
+ expect(handler.response).toHaveProperty('body', '');
64
+ app.debug = true;
65
+ });
66
+
67
+ it.each`
68
+ debug | allowResponse | body
69
+ ${false} | ${() => true} | ${JSON.stringify({ status: 'success', data: 'Some message', _meta: {} })}
70
+ ${true} | ${() => true} | ${JSON.stringify({ status: 'success', data: 'Some message', _meta: {} })}
71
+ ${false} | ${() => false} | ${''}
72
+ ${true} | ${() => false} | ${''}
73
+ ${true} | ${undefined} | ${JSON.stringify({ status: 'success', data: 'Some message', _meta: {} })}
74
+ ${false} | ${undefined} | ${''}
75
+ `(
76
+ 'should return a specific response when allowResponse is $allowResponse and debug is $debug passed via options',
77
+ async ({ debug, allowResponse, body }) => {
78
+ app.debug = debug;
79
+
80
+ const handler = {
81
+ response: {},
82
+ event: {
83
+ someEventKey: 'someEventValue',
84
+ queryStringParameters: {
85
+ debug: 1,
86
+ },
87
+ },
88
+ };
89
+
90
+ await successHttpNoOutputResponseAfterHandler(handler, () => {}, {
91
+ response: 'Some message',
92
+ allowResponse,
93
+ });
94
+ expect(handler.response).toHaveProperty('statusCode', 200);
95
+ expect(handler.response).toHaveProperty('body', body);
96
+
97
+ app.debug = true;
98
+ }
99
+ );
100
+ });
101
+
102
+ describe('MiddlewareGroup: test errorHttpNoOutputResponseAfterHandler', () => {
103
+ it('should have no body without debug', async () => {
104
+ const handler = {
105
+ response: {},
106
+ event: {},
107
+ };
108
+
109
+ await errorHttpNoOutputResponseAfterHandler(handler, () => {}, {
110
+ error: new Error('Test validation error'),
111
+ });
112
+ expect(handler.response).toHaveProperty('statusCode', 200);
113
+ expect(handler.response).toHaveProperty('body', '');
114
+ });
115
+
116
+ it('should return the body when debug is enabled via query string parameters', async () => {
117
+ const handler = {
118
+ response: {},
119
+ event: {
120
+ queryStringParameters: {
121
+ debug: '1',
122
+ },
123
+ someEventKey: 'someEventValue',
124
+ },
125
+ };
126
+
127
+ await errorHttpNoOutputResponseAfterHandler(handler, () => {}, {
128
+ error: new Error('Test validation error'),
129
+ });
130
+ expect(handler.response).toHaveProperty('statusCode', 500);
131
+ expect(handler.response).toHaveProperty(
132
+ 'body',
133
+ JSON.stringify({
134
+ status: 'error',
135
+ data: null,
136
+ error: {
137
+ code: 'UNHANDLED_ERROR',
138
+ message: 'Error: Test validation error',
139
+ details: '',
140
+ },
141
+ _meta: {
142
+ queryStringParameters: {
143
+ debug: '1',
144
+ },
145
+ someEventKey: 'someEventValue',
146
+ },
147
+ })
148
+ );
149
+ });
150
+
151
+ it('should have empty body even when enabled when configuration has is disabled', async () => {
152
+ app.debug = false;
153
+
154
+ const handler = {
155
+ response: {},
156
+ event: {
157
+ queryStringParameters: {
158
+ debug: '1',
159
+ },
160
+ someEventKey: 'someEventValue',
161
+ },
162
+ };
163
+
164
+ await errorHttpNoOutputResponseAfterHandler(handler, () => {}, {
165
+ error: new Error('Test validation error'),
166
+ });
167
+ expect(handler.response).toHaveProperty('statusCode', 200);
168
+ expect(handler.response).toHaveProperty('body', '');
169
+ app.debug = true;
170
+ });
171
+
172
+ it('should have a response when allowResponse override is passed via options', async () => {
173
+ app.debug = false;
174
+
175
+ const handler = {
176
+ response: {},
177
+ event: {
178
+ queryStringParameters: {
179
+ debug: '1',
180
+ },
181
+ someEventKey: 'someEventValue',
182
+ },
183
+ };
184
+
185
+ await errorHttpNoOutputResponseAfterHandler(handler, () => {}, {
186
+ error: new Error('Test validation error'),
187
+ allowResponse: () => true,
188
+ });
189
+ expect(handler.response).toHaveProperty('statusCode', 500);
190
+ expect(JSON.parse(handler.response.body)).toStrictEqual({
191
+ status: 'error',
192
+ data: null,
193
+ error: {
194
+ code: 'UNHANDLED_ERROR',
195
+ message: 'Error: Test validation error',
196
+ details: '',
197
+ },
198
+ _meta: expect.anything(),
199
+ });
200
+ });
201
+ });
@@ -59,6 +59,17 @@ describe('MiddlewareGroup: test disconnectConnections db middleware', () => {
59
59
 
60
60
  expect(end).toHaveBeenCalledTimes(1);
61
61
  });
62
+
63
+ it('should return exception if failure is detected', async () => {
64
+ const end = jest.fn().mockImplementationOnce(() => {
65
+ throw new Error('Test Error');
66
+ });
67
+ await disconnectConnections({
68
+ db: {
69
+ end,
70
+ },
71
+ });
72
+ });
62
73
  });
63
74
 
64
75
  describe('MiddlewareGroup: test disconnectConnections dbRead middleware', () => {
@@ -69,6 +80,13 @@ describe('MiddlewareGroup: test disconnectConnections dbRead middleware', () =>
69
80
  expect(end).toHaveBeenCalledTimes(0);
70
81
  });
71
82
 
83
+ it('should not call anything whenever no options is passed', async () => {
84
+ const end = jest.fn().mockResolvedValue();
85
+ await disconnectConnections();
86
+
87
+ expect(end).toHaveBeenCalledTimes(0);
88
+ });
89
+
72
90
  it('should call dbRead.end() whenever a dbRead options is set', async () => {
73
91
  const end = jest.fn().mockResolvedValue();
74
92
  await disconnectConnections({
@@ -73,6 +73,19 @@ describe('MiddlewareGroup: test successHttpResponseHandler middleware', () => {
73
73
  });
74
74
  });
75
75
 
76
+ it('test with formatSuccess argument', async () => {
77
+ const data = await successHttpResponseHandler({
78
+ response: 'Some message',
79
+ formatSuccess: options => {
80
+ return options.response;
81
+ },
82
+ });
83
+
84
+ expect(data.statusCode).toBe(200);
85
+
86
+ expect(data.body).toBe('Some message');
87
+ });
88
+
76
89
  it('test with configurable header', async () => {
77
90
  const data = await successHttpResponseHandler({
78
91
  response: 'Some message',
@@ -1,6 +1,7 @@
1
1
  import config from 'Config/jwt'; // eslint-disable-line import/no-unresolved
2
- import { verifyJwtMiddlewareBeforeHandler } from '../verifyJwtMiddleware';
3
- import LesgoException from '../../exceptions/LesgoException';
2
+ import verifyJwtMiddleware, {
3
+ verifyJwtMiddlewareBeforeHandler,
4
+ } from '../verifyJwtMiddleware';
4
5
 
5
6
  describe('MiddlewareGroup: test verifyJwtMiddleware middleware', () => {
6
7
  const handler = {
@@ -11,17 +12,35 @@ describe('MiddlewareGroup: test verifyJwtMiddleware middleware', () => {
11
12
  },
12
13
  };
13
14
 
14
- it('test without authorization header', () => {
15
- expect(() => verifyJwtMiddlewareBeforeHandler(handler, () => {})).toThrow(
16
- new LesgoException(
17
- 'Authorization Header is required!',
18
- 'JWT_MISSING_AUTHORIZATION_HEADER',
19
- 403
20
- )
21
- );
15
+ it('should return before object', () => {
16
+ const newHandler = {
17
+ event: {
18
+ ...handler.event,
19
+ headers: {
20
+ Authorization:
21
+ 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJpc3MiOiJkb21haW4uY29tIiwiZGVwYXJ0bWVudF9pZCI6MX0.pa2TBRqdVSFUhmiglB8SD8ImthqhqZBn0stAdNRcJ3w',
22
+ },
23
+ },
24
+ };
25
+ const result = verifyJwtMiddleware(newHandler, () => {});
26
+
27
+ expect(result).toHaveProperty('before');
28
+ });
29
+
30
+ it('test without authorization header', async () => {
31
+ try {
32
+ expect(
33
+ await verifyJwtMiddlewareBeforeHandler(handler, () => {})
34
+ ).toThrow();
35
+ } catch (e) {
36
+ expect(e.name).toEqual('LesgoException');
37
+ expect(e.message).toEqual('Authorization Header is required!');
38
+ expect(e.code).toEqual('JWT_MISSING_AUTHORIZATION_HEADER');
39
+ expect(e.statusCode).toEqual(403);
40
+ }
22
41
  });
23
42
 
24
- it('test with missing bearer token', () => {
43
+ it('test with missing bearer token', async () => {
25
44
  const newHandler = {
26
45
  event: {
27
46
  ...handler.event,
@@ -31,18 +50,19 @@ describe('MiddlewareGroup: test verifyJwtMiddleware middleware', () => {
31
50
  },
32
51
  };
33
52
 
34
- expect(() =>
35
- verifyJwtMiddlewareBeforeHandler(newHandler, () => {})
36
- ).toThrow(
37
- new LesgoException(
38
- 'Authorization Header is required!',
39
- 'JWT_MISSING_AUTHORIZATION_HEADER',
40
- 403
41
- )
42
- );
53
+ try {
54
+ expect(
55
+ await verifyJwtMiddlewareBeforeHandler(newHandler, () => {})
56
+ ).toThrow();
57
+ } catch (e) {
58
+ expect(e.name).toEqual('LesgoException');
59
+ expect(e.message).toEqual('Authorization Header is required!');
60
+ expect(e.code).toEqual('JWT_MISSING_AUTHORIZATION_HEADER');
61
+ expect(e.statusCode).toEqual(403);
62
+ }
43
63
  });
44
64
 
45
- it('test with invalid token', () => {
65
+ it('test with invalid token', async () => {
46
66
  const newHandler = {
47
67
  event: {
48
68
  ...handler.event,
@@ -52,18 +72,19 @@ describe('MiddlewareGroup: test verifyJwtMiddleware middleware', () => {
52
72
  },
53
73
  };
54
74
 
55
- expect(() =>
56
- verifyJwtMiddlewareBeforeHandler(newHandler, () => {})
57
- ).toThrow(
58
- new LesgoException(
59
- 'Missing Bearer token!',
60
- 'JWT_MISSING_BEARER_TOKEN',
61
- 403
62
- )
63
- );
75
+ try {
76
+ expect(
77
+ await verifyJwtMiddlewareBeforeHandler(newHandler, () => {})
78
+ ).toThrow();
79
+ } catch (e) {
80
+ expect(e.name).toEqual('LesgoException');
81
+ expect(e.message).toEqual('Missing Bearer token!');
82
+ expect(e.code).toEqual('JWT_MISSING_BEARER_TOKEN');
83
+ expect(e.statusCode).toEqual(403);
84
+ }
64
85
  });
65
86
 
66
- it('test with malformed token', () => {
87
+ it('test with malformed token', async () => {
67
88
  const newHandler = {
68
89
  event: {
69
90
  ...handler.event,
@@ -73,12 +94,19 @@ describe('MiddlewareGroup: test verifyJwtMiddleware middleware', () => {
73
94
  },
74
95
  };
75
96
 
76
- expect(() =>
77
- verifyJwtMiddlewareBeforeHandler(newHandler, () => {})
78
- ).toThrow(new LesgoException('jwt malformed', 'JWT_ERROR', 403));
97
+ try {
98
+ expect(
99
+ await verifyJwtMiddlewareBeforeHandler(newHandler, () => {})
100
+ ).toThrow();
101
+ } catch (e) {
102
+ expect(e.name).toEqual('LesgoException');
103
+ expect(e.message).toEqual('jwt malformed');
104
+ expect(e.code).toEqual('JWT_ERROR');
105
+ expect(e.statusCode).toEqual(403);
106
+ }
79
107
  });
80
108
 
81
- it('test with incorrect secret key', () => {
109
+ it('test with incorrect secret key', async () => {
82
110
  const newHandler = {
83
111
  event: {
84
112
  ...handler.event,
@@ -89,12 +117,19 @@ describe('MiddlewareGroup: test verifyJwtMiddleware middleware', () => {
89
117
  },
90
118
  };
91
119
 
92
- expect(() =>
93
- verifyJwtMiddlewareBeforeHandler(newHandler, () => {})
94
- ).toThrow(new LesgoException('invalid signature', 'JWT_ERROR', 403));
120
+ try {
121
+ expect(
122
+ await verifyJwtMiddlewareBeforeHandler(newHandler, () => {})
123
+ ).toThrow();
124
+ } catch (e) {
125
+ expect(e.name).toEqual('LesgoException');
126
+ expect(e.message).toEqual('invalid signature');
127
+ expect(e.code).toEqual('JWT_ERROR');
128
+ expect(e.statusCode).toEqual(403);
129
+ }
95
130
  });
96
131
 
97
- it('test with invalid ISS', () => {
132
+ it('test with invalid ISS', async () => {
98
133
  const newHandler = {
99
134
  event: {
100
135
  ...handler.event,
@@ -105,18 +140,19 @@ describe('MiddlewareGroup: test verifyJwtMiddleware middleware', () => {
105
140
  },
106
141
  };
107
142
 
108
- expect(() =>
109
- verifyJwtMiddlewareBeforeHandler(newHandler, () => {})
110
- ).toThrow(
111
- new LesgoException(
112
- "Token's [iss] is not valid!",
113
- 'JWT_ISS_NOT_VALID',
114
- 403
115
- )
116
- );
143
+ try {
144
+ expect(
145
+ await verifyJwtMiddlewareBeforeHandler(newHandler, () => {})
146
+ ).toThrow();
147
+ } catch (e) {
148
+ expect(e.name).toEqual('LesgoException');
149
+ expect(e.message).toEqual("Token's [iss] is not valid!");
150
+ expect(e.code).toEqual('JWT_ISS_NOT_VALID');
151
+ expect(e.statusCode).toEqual(403);
152
+ }
117
153
  });
118
154
 
119
- it('test with missing custom claim', () => {
155
+ it('test with missing custom claim', async () => {
120
156
  const newHandler = {
121
157
  event: {
122
158
  ...handler.event,
@@ -127,18 +163,21 @@ describe('MiddlewareGroup: test verifyJwtMiddleware middleware', () => {
127
163
  },
128
164
  };
129
165
 
130
- expect(() =>
131
- verifyJwtMiddlewareBeforeHandler(newHandler, () => {})
132
- ).toThrow(
133
- new LesgoException(
134
- `Token's custom claim [${config.customClaims.data[0]}] not found!`,
135
- 'JWT_CUSTOM_CLAIM_NOT_FOUND',
136
- 403
137
- )
138
- );
166
+ try {
167
+ expect(
168
+ await verifyJwtMiddlewareBeforeHandler(newHandler, () => {})
169
+ ).toThrow();
170
+ } catch (e) {
171
+ expect(e.name).toEqual('LesgoException');
172
+ expect(e.message).toEqual(
173
+ `Token's custom claim [${config.customClaims.data[0]}] not found!`
174
+ );
175
+ expect(e.code).toEqual('JWT_CUSTOM_CLAIM_NOT_FOUND');
176
+ expect(e.statusCode).toEqual(403);
177
+ }
139
178
  });
140
179
 
141
- it('test with expired token', () => {
180
+ it('test with expired token', async () => {
142
181
  const newHandler = {
143
182
  event: {
144
183
  ...handler.event,
@@ -149,12 +188,19 @@ describe('MiddlewareGroup: test verifyJwtMiddleware middleware', () => {
149
188
  },
150
189
  };
151
190
 
152
- expect(() =>
153
- verifyJwtMiddlewareBeforeHandler(newHandler, () => {})
154
- ).toThrow(new LesgoException('jwt expired', 'JWT_EXPIRED', 403));
191
+ try {
192
+ expect(
193
+ await verifyJwtMiddlewareBeforeHandler(newHandler, () => {})
194
+ ).toThrow();
195
+ } catch (e) {
196
+ expect(e.name).toEqual('LesgoException');
197
+ expect(e.message).toEqual('jwt expired');
198
+ expect(e.code).toEqual('JWT_EXPIRED');
199
+ expect(e.statusCode).toEqual(403);
200
+ }
155
201
  });
156
202
 
157
- it('test with valid token', () => {
203
+ it('test with valid token', async () => {
158
204
  const newHandler = {
159
205
  event: {
160
206
  ...handler.event,
@@ -165,7 +211,84 @@ describe('MiddlewareGroup: test verifyJwtMiddleware middleware', () => {
165
211
  },
166
212
  };
167
213
 
168
- verifyJwtMiddlewareBeforeHandler(newHandler, () => {});
214
+ await verifyJwtMiddlewareBeforeHandler(newHandler, () => {});
215
+ expect(newHandler.event.decodedJwt).toMatchObject({
216
+ sub: '1234567890',
217
+ iss: config.iss.data[0],
218
+ });
219
+ });
220
+
221
+ it('test with secret as a function argument', async () => {
222
+ const { secret } = config;
223
+ config.secret = secretHandler => {
224
+ return `111${secretHandler.key}`;
225
+ };
226
+ const newHandler = {
227
+ key: '1',
228
+ event: {
229
+ ...handler.event,
230
+ headers: {
231
+ Authorization:
232
+ 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJpc3MiOiJkb21haW4uY29tIiwiZGVwYXJ0bWVudF9pZCI6MX0.7RdbXJhzrn_yV7CPqkuX0Yvtms0xaIw1q4LPe8O0BDY',
233
+ },
234
+ },
235
+ };
236
+
237
+ await verifyJwtMiddlewareBeforeHandler(newHandler, () => {});
238
+ expect(newHandler.event.decodedJwt).toMatchObject({
239
+ sub: '1234567890',
240
+ iss: config.iss.data[0],
241
+ });
242
+
243
+ config.secret = secret;
244
+ });
245
+
246
+ it('test with callback argument', async () => {
247
+ const callback = jest.fn();
248
+ config.callback = callback;
249
+ const newHandler = {
250
+ event: {
251
+ ...handler.event,
252
+ headers: {
253
+ Authorization:
254
+ 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJpc3MiOiJkb21haW4uY29tIiwiZGVwYXJ0bWVudF9pZCI6MX0.pa2TBRqdVSFUhmiglB8SD8ImthqhqZBn0stAdNRcJ3w',
255
+ },
256
+ },
257
+ };
258
+
259
+ await verifyJwtMiddlewareBeforeHandler(newHandler, () => {});
260
+ expect(newHandler.event.decodedJwt).toMatchObject({
261
+ sub: '1234567890',
262
+ iss: config.iss.data[0],
263
+ });
264
+ expect(callback).toHaveBeenCalledWith(newHandler);
265
+ });
266
+
267
+ it('test with custom config', async () => {
268
+ const newHandler = {
269
+ event: {
270
+ ...handler.event,
271
+ headers: {
272
+ Authorization:
273
+ 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJpc3MiOiJkb21haW4uY29tIiwiZGVwYXJ0bWVudF9pZCI6MX0.pa2TBRqdVSFUhmiglB8SD8ImthqhqZBn0stAdNRcJ3w',
274
+ },
275
+ },
276
+ };
277
+
278
+ await verifyJwtMiddlewareBeforeHandler(newHandler, () => {}, {
279
+ jwtConfig: {
280
+ secret:
281
+ 'c4156b94c80b7f163feabd4ff268c99eb11ce8995df370a4fd872afb4377b273',
282
+ iss: {
283
+ validate: true,
284
+ data: ['domain.com'],
285
+ },
286
+ customClaims: {
287
+ validate: true,
288
+ data: ['department_id'],
289
+ },
290
+ },
291
+ });
169
292
  expect(newHandler.event.decodedJwt).toMatchObject({
170
293
  sub: '1234567890',
171
294
  iss: config.iss.data[0],