nodester 0.0.1
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/LICENSE +21 -0
- package/Readme.md +125 -0
- package/docs/App.md +13 -0
- package/docs/Queries.md +61 -0
- package/docs/Readme.md +2 -0
- package/docs/Routing.md +34 -0
- package/examples/goal/index.js +23 -0
- package/examples/rest/index.js +25 -0
- package/examples/rest/node_modules/.package-lock.json +40 -0
- package/examples/rest/package-lock.json +72 -0
- package/examples/rest/package.json +14 -0
- package/lib/application/MiddlewareStack.js +125 -0
- package/lib/application/http/request.js +462 -0
- package/lib/application/http/response.js +1107 -0
- package/lib/application/http/utils.js +254 -0
- package/lib/application/index.js +292 -0
- package/lib/constants/ConstantsEnum.js +13 -0
- package/lib/constants/ResponseFormats.js +7 -0
- package/lib/controllers/Controller.js +474 -0
- package/lib/controllers/JWTController.js +240 -0
- package/lib/controllers/ServiceController.js +109 -0
- package/lib/controllers/WebController.js +75 -0
- package/lib/facades/Facade.js +388 -0
- package/lib/facades/FacadeParams.js +11 -0
- package/lib/facades/ServiceFacade.js +17 -0
- package/lib/facades/jwt.facade.js +273 -0
- package/lib/factories/errors/CustomError.js +22 -0
- package/lib/factories/errors/index.js +9 -0
- package/lib/factories/responses/api.js +90 -0
- package/lib/factories/responses/html.js +55 -0
- package/lib/logger/console.js +24 -0
- package/lib/models/DisabledRefreshToken.js +68 -0
- package/lib/models/Extractor.js +320 -0
- package/lib/models/define.js +62 -0
- package/lib/models/mixins.js +369 -0
- package/lib/policies/Role.js +77 -0
- package/lib/policies/RoleExtracting.js +97 -0
- package/lib/preprocessors/BodyPreprocessor.js +61 -0
- package/lib/preprocessors/IncludesPreprocessor.js +55 -0
- package/lib/preprocessors/QueryPreprocessor.js +64 -0
- package/lib/routers/Default/index.js +143 -0
- package/lib/routers/Default/layer.js +50 -0
- package/lib/routers/Main/index.js +10 -0
- package/lib/routers/Roles/index.js +81 -0
- package/lib/services/includes.service.js +79 -0
- package/lib/services/jwt.service.js +147 -0
- package/lib/tools/sql.tool.js +82 -0
- package/lib/utils/dates.util.js +23 -0
- package/lib/utils/forms.util.js +22 -0
- package/lib/utils/json.util.js +49 -0
- package/lib/utils/mappers/Routes/index.js +100 -0
- package/lib/utils/mappers/Routes/utils.js +20 -0
- package/lib/utils/modelAssociations.util.js +44 -0
- package/lib/utils/objects.util.js +69 -0
- package/lib/utils/params.util.js +19 -0
- package/lib/utils/path.util.js +26 -0
- package/lib/utils/queries.util.js +240 -0
- package/lib/utils/sanitizations.util.js +111 -0
- package/lib/utils/sql.util.js +78 -0
- package/lib/utils/strings.util.js +43 -0
- package/lib/utils/types.util.js +26 -0
- package/package.json +63 -0
- package/tests/index.test.js +35 -0
|
@@ -0,0 +1,474 @@
|
|
|
1
|
+
// Constants.
|
|
2
|
+
const VISITOR = 'visitor';
|
|
3
|
+
// Data extractor:
|
|
4
|
+
const Extractor = require('nodester/models/Extractor');
|
|
5
|
+
// Preprocessors:
|
|
6
|
+
const QueryPreprocessor = require('nodester/preprocessors/QueryPreprocessor');
|
|
7
|
+
const BodyPreprocessor = require('nodester/preprocessors/BodyPreprocessor');
|
|
8
|
+
// Reponse protocol generator.
|
|
9
|
+
const APIResponseFactory = require('nodester/factories/responses/api');
|
|
10
|
+
// Custom error.
|
|
11
|
+
const { Err } = require('nodester/factories/errors');
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
module.exports = class Controller {
|
|
15
|
+
constructor({
|
|
16
|
+
modelFacade,
|
|
17
|
+
|
|
18
|
+
queryPreprocessor,
|
|
19
|
+
bodyPreprocessor,
|
|
20
|
+
|
|
21
|
+
apiResponseFactory,
|
|
22
|
+
|
|
23
|
+
// Options.
|
|
24
|
+
withFiles,
|
|
25
|
+
}) {
|
|
26
|
+
if (!modelFacade) {
|
|
27
|
+
throw new Error('"modelFacade" argument is invalid.');
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Main model.
|
|
31
|
+
const model = modelFacade?.model;
|
|
32
|
+
|
|
33
|
+
// Set main services & utils:
|
|
34
|
+
this.extractor = new Extractor(model, { withFiles: !!withFiles });
|
|
35
|
+
this.facade = modelFacade;
|
|
36
|
+
|
|
37
|
+
// Set preprocessors:
|
|
38
|
+
// TODO: includes preprocessor.
|
|
39
|
+
this.queryPreprocessor = queryPreprocessor ?? new QueryPreprocessor();
|
|
40
|
+
this.bodyPreprocessor = bodyPreprocessor ?? null;
|
|
41
|
+
|
|
42
|
+
// Extract plural name of model.
|
|
43
|
+
const modelPluralName = model?.options?.name?.plural;
|
|
44
|
+
// Set private name of this controller.
|
|
45
|
+
this.name = `${modelPluralName ?? '_INVALID_NAME_'}Controller`;
|
|
46
|
+
|
|
47
|
+
// Init standard API response factory.
|
|
48
|
+
const standardAPIResponseFactory = new APIResponseFactory();
|
|
49
|
+
// Set response factory:
|
|
50
|
+
this.createOKResponse = apiResponseFactory?.createOKResponse ??
|
|
51
|
+
standardAPIResponseFactory.createOKResponse.bind(standardAPIResponseFactory);
|
|
52
|
+
this.createErrorResponse = apiResponseFactory?.createErrorResponse ??
|
|
53
|
+
standardAPIResponseFactory.createErrorResponse.bind(standardAPIResponseFactory);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
processError(error, req, res) {
|
|
57
|
+
// Default error message.
|
|
58
|
+
let errorMessage = error?.message ?? 'Internal server error';
|
|
59
|
+
// Default HTTP status code.
|
|
60
|
+
let statusCode = error?.status ?? error?.statusCode ?? 500;
|
|
61
|
+
// Error response object.
|
|
62
|
+
let errorResponse = {};
|
|
63
|
+
|
|
64
|
+
switch(error.name) {
|
|
65
|
+
case('Unauthorized'): {
|
|
66
|
+
statusCode = 401;
|
|
67
|
+
errorResponse.details = { message: 'Unauthorized' };
|
|
68
|
+
break;
|
|
69
|
+
}
|
|
70
|
+
case('NotFound'): {
|
|
71
|
+
statusCode = 404;
|
|
72
|
+
errorResponse.details = { message: errorMessage };
|
|
73
|
+
break;
|
|
74
|
+
}
|
|
75
|
+
case('ValidationError'): {
|
|
76
|
+
statusCode = 406;
|
|
77
|
+
errorResponse.details = error?.details;
|
|
78
|
+
break;
|
|
79
|
+
}
|
|
80
|
+
case('ConflictError'): {
|
|
81
|
+
statusCode = 409;
|
|
82
|
+
errorResponse.details = error?.details ?? error?.message;
|
|
83
|
+
break;
|
|
84
|
+
}
|
|
85
|
+
case('SequelizeUniqueConstraintError'): {
|
|
86
|
+
statusCode = 409;
|
|
87
|
+
errorResponse.details = error?.errors;
|
|
88
|
+
break;
|
|
89
|
+
}
|
|
90
|
+
case('InternalValidationError'): {
|
|
91
|
+
statusCode = 500;
|
|
92
|
+
errorResponse.details = { message:'Error' };
|
|
93
|
+
break;
|
|
94
|
+
}
|
|
95
|
+
default: {
|
|
96
|
+
errorResponse.details = { message:errorMessage };
|
|
97
|
+
break;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// Send error response with provided status code.
|
|
102
|
+
return this.createErrorResponse({
|
|
103
|
+
res,
|
|
104
|
+
error: {
|
|
105
|
+
...errorResponse,
|
|
106
|
+
code: statusCode
|
|
107
|
+
},
|
|
108
|
+
status: statusCode
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/* POST: */
|
|
113
|
+
async createOne(req, res) {
|
|
114
|
+
try {
|
|
115
|
+
// Extract all required info:
|
|
116
|
+
const {
|
|
117
|
+
// query,
|
|
118
|
+
includes
|
|
119
|
+
} = await this.extractQuery(req, res);
|
|
120
|
+
|
|
121
|
+
// Extract request's body.
|
|
122
|
+
const { body } = await this.extractBody(req, res);
|
|
123
|
+
|
|
124
|
+
// Extract new instance data.
|
|
125
|
+
const data = this.extractor.extractInstanceDataFromObject(
|
|
126
|
+
body,
|
|
127
|
+
includes,
|
|
128
|
+
{
|
|
129
|
+
skipIdValidation: true
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
const result = await this.facade.createOne({ data, includes });
|
|
133
|
+
|
|
134
|
+
// Hook.
|
|
135
|
+
await this.afterCreateOne(req, res, result);
|
|
136
|
+
|
|
137
|
+
return this.createOKResponse({
|
|
138
|
+
res,
|
|
139
|
+
content: { ...result }
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
catch(error) {
|
|
143
|
+
console.error(`${ this.name }.createOne error:`, error);
|
|
144
|
+
return this.processError(error, req, res);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
/* POST\ */
|
|
148
|
+
|
|
149
|
+
/* GET: */
|
|
150
|
+
async getOne(req, res) {
|
|
151
|
+
try {
|
|
152
|
+
// Extract all required info:
|
|
153
|
+
const {
|
|
154
|
+
query,
|
|
155
|
+
includes
|
|
156
|
+
} = await this.extractQuery(req, res);
|
|
157
|
+
|
|
158
|
+
const params = {
|
|
159
|
+
query,
|
|
160
|
+
includes,
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// If Query or Params contains main identifier (id),
|
|
164
|
+
// validate it:
|
|
165
|
+
if (!!query.id) {
|
|
166
|
+
// Extract main identifier.
|
|
167
|
+
const { id } = this.extractor.extractInstanceDataFromObject(
|
|
168
|
+
query,
|
|
169
|
+
null,
|
|
170
|
+
{
|
|
171
|
+
skipValidation: true
|
|
172
|
+
});
|
|
173
|
+
params.id = id;
|
|
174
|
+
}
|
|
175
|
+
// If Request's Params contains main identifier (id),
|
|
176
|
+
// validate it:
|
|
177
|
+
else if (!!req.params.id) {
|
|
178
|
+
// Extract main identifier.
|
|
179
|
+
const { id } = this.extractor.extractInstanceDataFromObject(
|
|
180
|
+
req.params,
|
|
181
|
+
null,
|
|
182
|
+
{
|
|
183
|
+
skipValidation: true
|
|
184
|
+
});
|
|
185
|
+
params.id = id;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const result = await this.facade.getOne(params);
|
|
189
|
+
|
|
190
|
+
return this.createOKResponse({
|
|
191
|
+
res,
|
|
192
|
+
content: { ...result }
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
catch(error) {
|
|
196
|
+
console.error(`${ this.name }.getOne error:`, error);
|
|
197
|
+
return this.processError(error, req, res);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
async getMany(req, res) {
|
|
202
|
+
try {
|
|
203
|
+
// Extract all required info:
|
|
204
|
+
const {
|
|
205
|
+
query,
|
|
206
|
+
includes
|
|
207
|
+
} = await this.extractQuery(req, res);
|
|
208
|
+
|
|
209
|
+
const params = {
|
|
210
|
+
query,
|
|
211
|
+
includes,
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// If Query contains main identifier (id),
|
|
215
|
+
// validate it:
|
|
216
|
+
if (!!query.id) {
|
|
217
|
+
// Extract main identifier.
|
|
218
|
+
const { id } = this.extractor.extractInstanceDataFromObject(
|
|
219
|
+
query,
|
|
220
|
+
null,
|
|
221
|
+
{
|
|
222
|
+
skipValidation: true
|
|
223
|
+
});
|
|
224
|
+
params.query.id = id;
|
|
225
|
+
}
|
|
226
|
+
// If Request's Params contains main identifier (id),
|
|
227
|
+
// validate it:
|
|
228
|
+
else if (!!req.params.id) {
|
|
229
|
+
// Extract main identifier.
|
|
230
|
+
const { id } = this.extractor.extractInstanceDataFromObject(
|
|
231
|
+
req.params,
|
|
232
|
+
null,
|
|
233
|
+
{
|
|
234
|
+
skipValidation: true
|
|
235
|
+
});
|
|
236
|
+
params.query.id = id;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
const result = await this.facade.getMany(params);
|
|
240
|
+
|
|
241
|
+
return this.createOKResponse({
|
|
242
|
+
res,
|
|
243
|
+
content: { ...result }
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
catch(error) {
|
|
247
|
+
console.error(`${ this.name }.getMany error:`, error);
|
|
248
|
+
return this.processError(error, req, res);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
/* GET\ */
|
|
252
|
+
|
|
253
|
+
/* PUT: */
|
|
254
|
+
async updateOne(req, res) {
|
|
255
|
+
try {
|
|
256
|
+
// Extract all required info:
|
|
257
|
+
const {
|
|
258
|
+
query,
|
|
259
|
+
includes
|
|
260
|
+
} = await this.extractQuery(req, res);
|
|
261
|
+
|
|
262
|
+
// Extract request's body.
|
|
263
|
+
const { body } = await this.extractBody(req, res);
|
|
264
|
+
|
|
265
|
+
// Init facade params.
|
|
266
|
+
const facadeParams = {
|
|
267
|
+
query,
|
|
268
|
+
includes,
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
// If request params contain main identifier (id),
|
|
272
|
+
// extract & validate it:
|
|
273
|
+
if (!!req.params.id) {
|
|
274
|
+
// Extract main identifier.
|
|
275
|
+
facadeParams.query.id = parseInt(req.params.id);
|
|
276
|
+
}
|
|
277
|
+
// If Query contains main identifier (id),
|
|
278
|
+
// validate it:
|
|
279
|
+
else if (!!query.id) {
|
|
280
|
+
// Extract main identifier.
|
|
281
|
+
const { id } = this.extractor.extractInstanceDataFromObject(
|
|
282
|
+
query,
|
|
283
|
+
null,
|
|
284
|
+
{
|
|
285
|
+
skipValidation: true
|
|
286
|
+
});
|
|
287
|
+
facadeParams.query.id = id;
|
|
288
|
+
}
|
|
289
|
+
// Extract instance data.
|
|
290
|
+
const data = this.extractor.extractInstanceDataFromObject(
|
|
291
|
+
body,
|
|
292
|
+
includes,
|
|
293
|
+
{
|
|
294
|
+
skipIdValidation: true,
|
|
295
|
+
skipValidation: true
|
|
296
|
+
});
|
|
297
|
+
facadeParams.data = data;
|
|
298
|
+
|
|
299
|
+
const result = await this.facade.updateOne(facadeParams);
|
|
300
|
+
|
|
301
|
+
// Hook.
|
|
302
|
+
await this.afterUpdateOne(req, res, result);
|
|
303
|
+
|
|
304
|
+
return this.createOKResponse({
|
|
305
|
+
res,
|
|
306
|
+
content: { ...result }
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
catch(error) {
|
|
310
|
+
console.error(`${ this.name }.updateOne error:`, error);
|
|
311
|
+
return this.processError(error, req, res);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/* ! Warning !
|
|
316
|
+
* Unfinished method
|
|
317
|
+
* Do not use!
|
|
318
|
+
*/
|
|
319
|
+
async updateMany(req, res) {
|
|
320
|
+
try {
|
|
321
|
+
// Extract all required info:
|
|
322
|
+
const {
|
|
323
|
+
query,
|
|
324
|
+
includes
|
|
325
|
+
} = await this.extractQuery(req, res);
|
|
326
|
+
|
|
327
|
+
// If Query contains main identifier (id),
|
|
328
|
+
// extract & validate it:
|
|
329
|
+
if (!!query.id) {
|
|
330
|
+
// Extract main identifier.
|
|
331
|
+
const { id } = this.extractor.extractInstanceDataFromObject(
|
|
332
|
+
query,
|
|
333
|
+
null,
|
|
334
|
+
{
|
|
335
|
+
skipValidation: true
|
|
336
|
+
});
|
|
337
|
+
query.id = id;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
// Extract data array:
|
|
341
|
+
const data = this.extractor.extractArrayDataFromObject(
|
|
342
|
+
req.body,
|
|
343
|
+
{
|
|
344
|
+
skipIdValidation: true,
|
|
345
|
+
skipValidation: true
|
|
346
|
+
});
|
|
347
|
+
|
|
348
|
+
console.log("Controller.updateMany", { data });
|
|
349
|
+
|
|
350
|
+
// TODO: Finish procedure
|
|
351
|
+
return;
|
|
352
|
+
// const result = await this.facade.updateMany({ data, includes });
|
|
353
|
+
|
|
354
|
+
// return this.createOKResponse({
|
|
355
|
+
// res,
|
|
356
|
+
// content: { ...result }
|
|
357
|
+
// });
|
|
358
|
+
}
|
|
359
|
+
catch(error) {
|
|
360
|
+
console.error(`${ this.name }.updateMany error:`, error);
|
|
361
|
+
return this.processError(error, req, res);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
/* PUT\ */
|
|
365
|
+
|
|
366
|
+
/* DELETE: */
|
|
367
|
+
async deleteOne(req, res) {
|
|
368
|
+
try {
|
|
369
|
+
// Extract main identifier.
|
|
370
|
+
const { id } = this.extractor.extractInstanceDataFromObject(
|
|
371
|
+
req.params,
|
|
372
|
+
null,
|
|
373
|
+
{
|
|
374
|
+
skipValidation: true
|
|
375
|
+
});
|
|
376
|
+
|
|
377
|
+
const result = await this.facade.deleteOne({ id });
|
|
378
|
+
|
|
379
|
+
// Hook.
|
|
380
|
+
await this.afterDeleteOne(req, res, result);
|
|
381
|
+
|
|
382
|
+
return this.createOKResponse({
|
|
383
|
+
res,
|
|
384
|
+
content: { ...result }
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
catch(error) {
|
|
388
|
+
console.error(`${ this.name }.deleteOne error:`, error);
|
|
389
|
+
return this.processError(error, req, res);
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
/* DELETE\ */
|
|
393
|
+
|
|
394
|
+
/*
|
|
395
|
+
* Hooks:
|
|
396
|
+
*/
|
|
397
|
+
async afterCreateOne(
|
|
398
|
+
req, res,
|
|
399
|
+
facadeResult
|
|
400
|
+
) {
|
|
401
|
+
// This method is empty, as it should be overwritten.
|
|
402
|
+
const content = { ...facadeResult };
|
|
403
|
+
return Promise.resolve(content);
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
async afterUpdateOne(
|
|
407
|
+
req, res,
|
|
408
|
+
facadeResult
|
|
409
|
+
) {
|
|
410
|
+
// This method is empty, as it should be overwritten.
|
|
411
|
+
const content = { ...facadeResult };
|
|
412
|
+
return Promise.resolve(content);
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
async afterDeleteOne(
|
|
416
|
+
req, res,
|
|
417
|
+
facadeResult
|
|
418
|
+
) {
|
|
419
|
+
// This method is empty, as it should be overwritten.
|
|
420
|
+
const content = { ...facadeResult };
|
|
421
|
+
return Promise.resolve(content);
|
|
422
|
+
}
|
|
423
|
+
/*
|
|
424
|
+
* Hooks\
|
|
425
|
+
*/
|
|
426
|
+
|
|
427
|
+
// Preprocessors:
|
|
428
|
+
async extractQuery(req, res) {
|
|
429
|
+
try {
|
|
430
|
+
// Extract role.
|
|
431
|
+
const role = req?.token?.parsed?.role ?? VISITOR;
|
|
432
|
+
|
|
433
|
+
// Extract query:
|
|
434
|
+
const query = await this.queryPreprocessor.extract(
|
|
435
|
+
req,
|
|
436
|
+
role,
|
|
437
|
+
);
|
|
438
|
+
const { includes } = req.query;
|
|
439
|
+
|
|
440
|
+
return Promise.resolve({
|
|
441
|
+
query,
|
|
442
|
+
includes,
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
catch(error) {
|
|
446
|
+
return Promise.reject(error);
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
async extractBody(req, res, externalBodyObject=null) {
|
|
451
|
+
try {
|
|
452
|
+
// Extract role.
|
|
453
|
+
const role = req?.token?.parsed?.role ?? VISITOR;
|
|
454
|
+
|
|
455
|
+
// Extract body:
|
|
456
|
+
let body = externalBodyObject ?? req.body;
|
|
457
|
+
|
|
458
|
+
if (!!this.bodyPreprocessor) {
|
|
459
|
+
body = await this.bodyPreprocessor.extract(
|
|
460
|
+
req,
|
|
461
|
+
role,
|
|
462
|
+
);
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
return Promise.resolve({
|
|
466
|
+
body,
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
catch(error) {
|
|
470
|
+
return Promise.reject(error);
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
// Preprocessors\
|
|
474
|
+
}
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
// Boilerplate JWT facade.
|
|
2
|
+
const standardJWTFacade = require('nodester/facades/jwt.facade');
|
|
3
|
+
// Data extractor:
|
|
4
|
+
const Extractor = require('nodester/models/Extractor');
|
|
5
|
+
// Reponse protocol generator.
|
|
6
|
+
const APIResponseFactory = require('nodester/factories/responses/api');
|
|
7
|
+
// Utils:
|
|
8
|
+
const { lowerCase } = require('nodester/utils/strings.util');
|
|
9
|
+
const Params = require('nodester/utils/params.util');
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
module.exports = class JWTController {
|
|
13
|
+
constructor({
|
|
14
|
+
jwtFacade,
|
|
15
|
+
apiResponseFactory,
|
|
16
|
+
}) {
|
|
17
|
+
|
|
18
|
+
this.facade = jwtFacade ?? standardJWTFacade;
|
|
19
|
+
this.name = 'JWTController';
|
|
20
|
+
|
|
21
|
+
// Init standard API response factory.
|
|
22
|
+
const standardAPIResponseFactory = new APIResponseFactory();
|
|
23
|
+
|
|
24
|
+
// Set response factory:
|
|
25
|
+
this.createOKResponse = apiResponseFactory?.createOKResponse ??
|
|
26
|
+
standardAPIResponseFactory.createOKResponse.bind(standardAPIResponseFactory);
|
|
27
|
+
this.createErrorResponse = apiResponseFactory?.createErrorResponse ??
|
|
28
|
+
standardAPIResponseFactory.createErrorResponse.bind(standardAPIResponseFactory);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
processError(error, req, res) {
|
|
32
|
+
// Default error message.
|
|
33
|
+
let errorMessage = error?.message ?? 'Internal server error';
|
|
34
|
+
// Default HTTP status code.
|
|
35
|
+
let statusCode = error?.status ?? error?.statusCode ?? 500;
|
|
36
|
+
// Error response object.
|
|
37
|
+
let errorResponse = {};
|
|
38
|
+
|
|
39
|
+
switch(error.name) {
|
|
40
|
+
case('Unauthorized'): {
|
|
41
|
+
statusCode = 406;
|
|
42
|
+
errorResponse.details = { message: 'Email or password are incorrect.' };
|
|
43
|
+
break;
|
|
44
|
+
}
|
|
45
|
+
case('ValidationError'): {
|
|
46
|
+
statusCode = 402;
|
|
47
|
+
errorResponse.details = { message: 'Invalid email OR password input.' };
|
|
48
|
+
break;
|
|
49
|
+
}
|
|
50
|
+
case('InvalidToken'): {
|
|
51
|
+
statusCode = 401;
|
|
52
|
+
errorResponse.details = { message: 'Invalid token or token expired.' };
|
|
53
|
+
break;
|
|
54
|
+
}
|
|
55
|
+
case('UserNotFound'): {
|
|
56
|
+
statusCode = 400;
|
|
57
|
+
errorResponse.details = { message: "Such user doesn't exist." };
|
|
58
|
+
break;
|
|
59
|
+
}
|
|
60
|
+
default: {
|
|
61
|
+
errorResponse.details = { message: 'Could not process request.' };
|
|
62
|
+
break;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Send error response with provided status code.
|
|
67
|
+
return this.createErrorResponse({
|
|
68
|
+
res,
|
|
69
|
+
error: {
|
|
70
|
+
...errorResponse,
|
|
71
|
+
code: statusCode
|
|
72
|
+
},
|
|
73
|
+
status: statusCode
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async login(req, res) {
|
|
78
|
+
try {
|
|
79
|
+
// Extract request input:
|
|
80
|
+
const {
|
|
81
|
+
email,
|
|
82
|
+
password,
|
|
83
|
+
role,
|
|
84
|
+
} = Params(req.body, {
|
|
85
|
+
email: null,
|
|
86
|
+
password: null,
|
|
87
|
+
role: 'user',
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
if (!email|| !password) {
|
|
91
|
+
// If bad input, throw ValidationError:
|
|
92
|
+
const err = new Error('Invalid email OR password input');
|
|
93
|
+
err.name = 'ValidationError';
|
|
94
|
+
throw err;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// Lowercase email.
|
|
98
|
+
const _email = lowerCase(email);
|
|
99
|
+
|
|
100
|
+
const params = {
|
|
101
|
+
email: _email,
|
|
102
|
+
password,
|
|
103
|
+
role
|
|
104
|
+
};
|
|
105
|
+
const result = await this.facade.login(params);
|
|
106
|
+
|
|
107
|
+
// Everything's fine, send response.
|
|
108
|
+
return this.createOKResponse({
|
|
109
|
+
res,
|
|
110
|
+
content: { ...result }
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
catch(error) {
|
|
114
|
+
console.error(`${ this.name }.login error:`, error);
|
|
115
|
+
return this.processError(error, req, res);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async validate(req, res) {
|
|
120
|
+
try {
|
|
121
|
+
const token = this.facade.service.extractTokenFromRequest(req);
|
|
122
|
+
|
|
123
|
+
// Validate token against local seed.
|
|
124
|
+
await this.facade.service.verifyAccessToken(token);
|
|
125
|
+
|
|
126
|
+
// Everything's fine, send response.
|
|
127
|
+
return this.createOKResponse({
|
|
128
|
+
res,
|
|
129
|
+
content: {
|
|
130
|
+
isValid: true,
|
|
131
|
+
message: "Valid Token"
|
|
132
|
+
}
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
catch(error) {
|
|
136
|
+
console.error("JWTController.validate error: ", error);
|
|
137
|
+
|
|
138
|
+
// In any error case, we send token not valid:
|
|
139
|
+
// Create custom error with name InvalidToken.
|
|
140
|
+
const err = new Error('Invalid Token!');
|
|
141
|
+
err.name = 'InvalidToken';
|
|
142
|
+
return this.processError(err, req, res);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
async refresh(req, res) {
|
|
147
|
+
try {
|
|
148
|
+
const refreshToken = this.facade.service.extractRefreshTokenFromRequest(req);
|
|
149
|
+
|
|
150
|
+
// Validate token against local seed.
|
|
151
|
+
const parsedToken = await this.facade.service.verifyRefreshToken(refreshToken);
|
|
152
|
+
|
|
153
|
+
// Everything's ok, issue new one.
|
|
154
|
+
const accessToken = await this.facade.refreshAccessToken({
|
|
155
|
+
refreshToken: refreshToken,
|
|
156
|
+
parsedRefreshToken: parsedToken
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
return this.createOKResponse({
|
|
160
|
+
res,
|
|
161
|
+
content: {
|
|
162
|
+
token: accessToken
|
|
163
|
+
}
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
catch(error) {
|
|
167
|
+
console.error(`${ this.name }.refresh error:`, error);
|
|
168
|
+
|
|
169
|
+
// In any error case, we send token not valid:
|
|
170
|
+
// Create custom error with name InvalidToken.
|
|
171
|
+
const err = new Error('Invalid Token!');
|
|
172
|
+
err.name = 'InvalidToken';
|
|
173
|
+
return this.processError(err, req, res);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
async disableRefreshToken(req, res) {
|
|
178
|
+
try {
|
|
179
|
+
const refreshToken = this.facade.service.extractRefreshTokenFromRequest(req);
|
|
180
|
+
|
|
181
|
+
// Validate refreshToken against local seed.
|
|
182
|
+
const parsedToken = await this.facade.service.verifyRefreshToken(refreshToken);
|
|
183
|
+
|
|
184
|
+
const createdStatus = await this.facade.disableRefreshToken({ refreshToken, parsedToken });
|
|
185
|
+
|
|
186
|
+
return this.createOKResponse({
|
|
187
|
+
res,
|
|
188
|
+
content: {
|
|
189
|
+
success: createdStatus,
|
|
190
|
+
disabled: createdStatus
|
|
191
|
+
}
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
catch(error) {
|
|
195
|
+
console.error(`${ this.name }.disableRefreshToken error:`, error);
|
|
196
|
+
|
|
197
|
+
// In any error case, we send token not valid:
|
|
198
|
+
// Create custom error with name InvalidToken.
|
|
199
|
+
const err = new Error('Invalid Token!');
|
|
200
|
+
err.name = 'InvalidToken';
|
|
201
|
+
return this.processError(err, req, res);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
async logout(req, res) {
|
|
206
|
+
try {
|
|
207
|
+
const refreshToken = this.facade.service.extractRefreshTokenFromRequest(req);
|
|
208
|
+
|
|
209
|
+
if (!refreshToken) {
|
|
210
|
+
const err = new Error('No refreshToken found');
|
|
211
|
+
err.name = 'Unauthorized';
|
|
212
|
+
err.status = 401;
|
|
213
|
+
throw err;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// Verifys and parses token. On failed validation will throw error.
|
|
217
|
+
const parsedToken = await this.facade.service.verifyRefreshToken(refreshToken);
|
|
218
|
+
|
|
219
|
+
// Everything's ok, destroy token.
|
|
220
|
+
const { status } = await this.facade.disableRefreshToken({ refreshToken, parsedToken });
|
|
221
|
+
|
|
222
|
+
return this.createOKResponse({
|
|
223
|
+
res,
|
|
224
|
+
content: {
|
|
225
|
+
status: status,
|
|
226
|
+
loggedIn: status === true
|
|
227
|
+
}
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
catch(error) {
|
|
231
|
+
console.error(`${ this.name }.logout error:`, error);
|
|
232
|
+
|
|
233
|
+
// In any error case, we send token not valid:
|
|
234
|
+
// Create custom error with name InvalidToken.
|
|
235
|
+
const err = new Error('Invalid Token!');
|
|
236
|
+
err.name = 'InvalidToken';
|
|
237
|
+
return this.processError(err, req, res);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
}
|