@webresto/graphql 1.3.7 → 1.4.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (142) hide show
  1. package/.gitattributes +2 -0
  2. package/.gitlab-ci.yml +18 -0
  3. package/.vscode/extensions.json +5 -0
  4. package/docs/actions.md +25 -0
  5. package/docs/authorization.md +215 -0
  6. package/docs/captcha.md +71 -0
  7. package/docs/device-id.md +30 -0
  8. package/docs/messages.md +10 -0
  9. package/docs/user.md +54 -0
  10. package/index.d.ts +0 -1
  11. package/index.js +6 -2
  12. package/index.ts +2 -2
  13. package/lib/afterHook.js +8 -0
  14. package/lib/afterHook.ts +9 -0
  15. package/lib/bindTranslations.d.ts +1 -0
  16. package/lib/bindTranslations.js +40 -0
  17. package/lib/bindTranslations.ts +39 -0
  18. package/lib/defaults.d.ts +1 -0
  19. package/lib/defaults.js +49 -10
  20. package/lib/defaults.ts +55 -0
  21. package/lib/eventHelper.d.ts +14 -5
  22. package/lib/eventHelper.js +28 -9
  23. package/lib/eventHelper.ts +41 -8
  24. package/lib/getRecomended.d.ts +1 -0
  25. package/lib/getRecomended.js +29 -0
  26. package/lib/getRecomended.ts +31 -0
  27. package/lib/graphqlHelper.d.ts +3 -4
  28. package/lib/graphqlHelper.js +184 -72
  29. package/lib/graphqlHelper.ts +329 -185
  30. package/lib/jwt.d.ts +10 -0
  31. package/lib/jwt.js +43 -0
  32. package/lib/jwt.ts +61 -0
  33. package/package.json +15 -7
  34. package/src/additionalResolvers.d.ts +72 -9
  35. package/src/additionalResolvers.js +93 -24
  36. package/src/additionalResolvers.ts +105 -34
  37. package/src/graphql.d.ts +5 -3
  38. package/src/graphql.js +170 -37
  39. package/src/graphql.ts +210 -60
  40. package/src/resolvers/bonusProgram.d.ts +32 -0
  41. package/src/resolvers/bonusProgram.js +65 -0
  42. package/src/resolvers/bonusProgram.ts +79 -0
  43. package/src/resolvers/captcha.d.ts +11 -0
  44. package/src/resolvers/captcha.js +19 -0
  45. package/src/resolvers/captcha.ts +16 -0
  46. package/src/resolvers/checkout.d.ts +35 -16
  47. package/src/resolvers/checkout.js +171 -94
  48. package/src/resolvers/checkout.ts +214 -104
  49. package/src/resolvers/dishAndModifier.js +8 -4
  50. package/src/resolvers/dishAndModifier.ts +4 -0
  51. package/src/resolvers/error.d.ts +9 -0
  52. package/src/resolvers/error.js +21 -0
  53. package/src/resolvers/error.ts +21 -0
  54. package/src/resolvers/menu.d.ts +9 -0
  55. package/src/resolvers/menu.js +12 -0
  56. package/src/resolvers/menu.ts +10 -0
  57. package/src/resolvers/order.d.ts +527 -0
  58. package/src/resolvers/order.js +349 -0
  59. package/src/resolvers/order.ts +435 -0
  60. package/src/resolvers/paymentMethod.js +7 -3
  61. package/src/resolvers/paymentMethod.ts +9 -5
  62. package/src/resolvers/pickupPoint.d.ts +1 -0
  63. package/src/resolvers/pickupPoint.js +24 -0
  64. package/src/resolvers/pickupPoint.ts +23 -0
  65. package/src/resolvers/recomended.d.ts +13 -0
  66. package/src/resolvers/recomended.js +80 -0
  67. package/src/resolvers/recomended.ts +86 -0
  68. package/src/resolvers/restrictions.d.ts +37 -1
  69. package/src/resolvers/restrictions.js +100 -15
  70. package/src/resolvers/restrictions.ts +106 -14
  71. package/src/resolvers/streets.d.ts +1 -1
  72. package/src/resolvers/streets.js +1 -4
  73. package/src/resolvers/streets.ts +1 -3
  74. package/src/resolvers/subscriptions.d.ts +4 -4
  75. package/src/resolvers/subscriptions.js +49 -12
  76. package/src/resolvers/subscriptions.ts +59 -14
  77. package/src/resolvers/telemetry.d.ts +14 -0
  78. package/src/resolvers/telemetry.js +25 -0
  79. package/src/resolvers/telemetry.ts +24 -0
  80. package/src/resolvers/user.d.ts +82 -0
  81. package/src/resolvers/user.js +416 -0
  82. package/src/resolvers/user.ts +621 -0
  83. package/src/resolvers/userLocation.d.ts +53 -0
  84. package/src/resolvers/userLocation.js +74 -0
  85. package/src/resolvers/userLocation.ts +125 -0
  86. package/src/resolvers/userOTPrequest.d.ts +21 -0
  87. package/src/resolvers/userOTPrequest.js +57 -0
  88. package/src/resolvers/userOTPrequest.ts +75 -0
  89. package/test/e2e_helper.js +157 -0
  90. package/test/e2e_helper.ts +212 -0
  91. package/test/fixture/config/i18n.js +7 -20
  92. package/test/fixture/config/locales/de.json +1 -0
  93. package/test/fixture/config/locales/en.json +10 -0
  94. package/test/fixture/config/locales/es.json +3 -0
  95. package/test/fixture/config/locales/fr.json +1 -0
  96. package/test/fixture/config/log.js +1 -1
  97. package/test/fixture/package.json +5 -6
  98. package/test/fixture/patches/rttc+10.0.1.patch +17 -0
  99. package/test/integration/captcha.test.js +20 -0
  100. package/test/integration/captcha.test.ts +25 -0
  101. package/test/integration/dish.test.js +35 -0
  102. package/test/integration/dish.test.ts +43 -0
  103. package/test/integration/graphql.test.js +5 -2
  104. package/test/integration/graphql.test.ts +2 -4
  105. package/test/integration/images.test.js +35 -0
  106. package/test/integration/images.test.ts +40 -0
  107. package/test/integration/locale.test.js +26 -0
  108. package/test/integration/locale.test.ts +32 -0
  109. package/test/integration/order.test.js +56 -43
  110. package/test/integration/order.test.ts +59 -59
  111. package/test/integration/subscriptions.test.js +136 -0
  112. package/test/integration/subscriptions.test.ts +162 -0
  113. package/test/integration/user.test.js +249 -0
  114. package/test/integration/user.test.ts +299 -0
  115. package/test/unit/first.test.js +4 -2
  116. package/test/unit/first.test.ts +1 -1
  117. package/test/unit/get-recomended.test.js +56 -0
  118. package/test/unit/get-recomended.test.ts +63 -0
  119. package/translations/de.json +2 -0
  120. package/translations/en.json +3 -0
  121. package/translations/es.json +3 -0
  122. package/translations/fr.json +2 -0
  123. package/translations/ru.json +36 -0
  124. package/tsconfig.json +20 -5
  125. package/types/global.d.ts +30 -0
  126. package/types/global.js +2 -0
  127. package/types/global.ts +31 -0
  128. package/types/primitives.d.ts +19 -0
  129. package/types/references.d.ts +1 -0
  130. package/types/restoGraphQLConfig.d.ts +13 -0
  131. package/lib/afterHook.ts___graphql-transport-ws +0 -138
  132. package/lib/afterHook.ts___graphql-ws +0 -133
  133. package/lib/errorWrapper.d.ts +0 -4
  134. package/lib/errorWrapper.js +0 -13
  135. package/lib/errorWrapper.ts +0 -12
  136. package/notes.md +0 -1976
  137. package/src/resolvers/cart.d.ts +0 -343
  138. package/src/resolvers/cart.js +0 -196
  139. package/src/resolvers/cart.ts +0 -278
  140. package/test/fixture/config/connections.js +0 -9
  141. package/test/integration/sails_not_crash.test.js +0 -3
  142. package/test/integration/sails_not_crash.test.ts +0 -3
@@ -1,22 +1,18 @@
1
1
  "use strict";
2
- /// <reference path="../../core/libs/globalTypes.ts"/>
3
- var _a;
4
2
  Object.defineProperty(exports, "__esModule", { value: true });
5
3
  exports.setWhiteList = exports.addModelResolver = exports.addDirResolvers = exports.addAllSailsModels = exports.addToReplaceList = exports.addCustomField = exports.addToBlackList = exports.getSchema = exports.addResolvers = exports.addType = exports.addModel = void 0;
6
4
  const _ = require("lodash");
7
5
  const worktime_1 = require("@webresto/worktime");
8
- const getEmitter_1 = require("@webresto/core/libs/getEmitter");
9
6
  const WLCriteria = require("waterline-criteria");
10
- const fs = require('fs');
11
- const path = require('path');
7
+ const jwt_1 = require("./jwt");
8
+ const fs = require("fs");
9
+ const path = require("path");
12
10
  const scalarTypes = {
13
11
  string: "String",
14
- text: "String",
15
- date: "String",
16
- datetime: "String",
17
- integer: "Int",
18
- float: "Float",
12
+ number: "Float",
19
13
  boolean: "Boolean",
14
+ // json: "Json",
15
+ // "array": "Array",
20
16
  };
21
17
  /*
22
18
  const typeDefsExample = {
@@ -78,8 +74,8 @@ function addModel(modelName) {
78
74
  models.add(modelName.toLowerCase());
79
75
  }
80
76
  exports.addModel = addModel;
81
- function addType(typeString) {
82
- schemaTypes.push(typeString);
77
+ function addType(type) {
78
+ schemaTypes.push(type);
83
79
  }
84
80
  exports.addType = addType;
85
81
  /**
@@ -87,7 +83,7 @@ exports.addType = addType;
87
83
  *
88
84
  * @param resolvers
89
85
  * resolverExample = {
90
- * def: "user(id: String)",
86
+ * def: "user(id: string)",
91
87
  * fn: function (parent, args, context) {
92
88
  * return User.find({id: args.id})
93
89
  * }
@@ -127,7 +123,7 @@ function addToBlackList(list) {
127
123
  exports.addToBlackList = addToBlackList;
128
124
  /**
129
125
  * Добавляет в указаную модель новое поле
130
- * Пример: addCustomField("Order", "customField: String")
126
+ * Пример: addCustomField("Order", "customField: string")
131
127
  *
132
128
  * @param model string
133
129
  * @param field string
@@ -173,8 +169,7 @@ exports.addDirResolvers = addDirResolvers;
173
169
  */
174
170
  function getSchema() {
175
171
  Object.keys(whiteList).forEach(modelname => {
176
- var _a, _b;
177
- if (((_b = (_a = sails.models[modelname]) === null || _a === void 0 ? void 0 : _a.graphql) === null || _b === void 0 ? void 0 : _b.public) !== false) {
172
+ if (sails.models[modelname]?.graphql?.public !== false) {
178
173
  addModelResolver(modelname);
179
174
  }
180
175
  });
@@ -208,25 +203,34 @@ function createType(model) {
208
203
  }
209
204
  let scalarType;
210
205
  if (attributes[prop].type) {
211
- if (scalarTypes[attributes[prop].type.toLowerCase()]) {
212
- scalarType = scalarTypes[attributes[prop].type.toLowerCase()];
206
+ // TODO: make method add AddModelFieldType(path, type) for pass custom type for specific model
207
+ if (modelName.toLowerCase() === "user" && prop === "phone") {
208
+ scalarType = "Phone";
213
209
  }
214
210
  else {
215
- scalarType = firstLetterToUpperCase(attributes[prop].type);
216
- schemaScalars.add(scalarType);
211
+ if (scalarTypes[attributes[prop].type.toLowerCase()]) {
212
+ scalarType = scalarTypes[attributes[prop].type.toLowerCase()];
213
+ }
214
+ else {
215
+ scalarType = firstLetterToUpperCase(attributes[prop].type);
216
+ schemaScalars.add(scalarType);
217
+ }
217
218
  }
218
219
  type += ' ' + prop + ': ' + scalarType + '\n';
219
220
  }
220
221
  // MODEL SCHEMA GENERATION
221
222
  if (attributes[prop].model) {
222
223
  let relationModel = sails.models[attributes[prop].model.toLowerCase()];
223
- scalarType = scalarTypes[relationModel.attributes[relationModel.primaryKey].type];
224
+ scalarType = scalarTypes[relationModel.attributes[relationModel.primaryKey].type.toLowerCase()];
224
225
  const name = sails.models[attributes[prop].model.toLowerCase()].globalId;
225
226
  type += ` ${prop}: ${name}\n`;
227
+ // Virtual Id field
228
+ type += ` ${prop}Id: ${scalarType}\n`;
226
229
  }
227
230
  // COLLECTION SCHEMA GENERATION
228
231
  if (attributes[prop].collection) {
229
- scalarType = scalarTypes[attributes[sails.models[attributes[prop].collection.toLowerCase()].primaryKey].type.toLowerCase()];
232
+ let collectionModel = sails.models[attributes[prop].collection.toLowerCase()];
233
+ scalarType = scalarTypes[collectionModel.attributes[collectionModel.primaryKey].type.toLowerCase()];
230
234
  const name = sails.models[attributes[prop].collection.toLowerCase()].globalId;
231
235
  type += ` ${prop}: [${name}]\n`;
232
236
  }
@@ -235,7 +239,7 @@ function createType(model) {
235
239
  type += ` ${customFields[modelName]}\n`;
236
240
  }
237
241
  if (!attributes.customData) {
238
- type += '""" autogenerated """ customData: Json';
242
+ type += `""" [autogenerated] ${isAuthRequired(modelName) ? '\n[auth required]' : ''}""" customData: Json`;
239
243
  }
240
244
  type += '}\n';
241
245
  return type;
@@ -299,9 +303,8 @@ function createSchema(typeDefsObj) {
299
303
  const whiteList = {
300
304
  // group: ['subscription', 'query'] // order - modelname , 'subscription' - resolver type
301
305
  };
302
- const userAuth = typeof ((_a = sails.config.restographql) === null || _a === void 0 ? void 0 : _a.authService) === 'function' ? sails.config.restographql.authService : null;
303
306
  let modelsResolvers = { Query: {} };
304
- const { withFilter } = require("apollo-server");
307
+ const apollo_server_1 = require("apollo-server");
305
308
  /**
306
309
  * Патчит waterline criteria во время автогенерации
307
310
  *
@@ -360,38 +363,60 @@ function addModelResolver(modelname) {
360
363
  models.add(modelname); // make schema Type for Model
361
364
  const methodName = firstLetterToLowerCase(modelName);
362
365
  let resolverQuery = {
363
- def: `""" autogenerated """ ${methodName}(criteria: Json): [${modelName}]`,
366
+ def: `""" [autogenerated] ${isAuthRequired(modelname) ? '\n[auth required]' : ''}""" ${methodName}(criteria: Json, skip: Int, limit: Int, sort: String): [${modelName}]`,
364
367
  fn: async function (parent, args, context) {
365
368
  let criteria = args.criteria || {};
366
369
  criteria = sanitizeCriteria(modelname, criteria);
367
370
  // If model has User field need auth
368
- if (sails.models[modelname].attributes.user) {
369
- if (userAuth) {
370
- let user = await userAuth(context.connectionParams.authorization);
371
- if (user.id) {
372
- criteria.user = user.id;
371
+ if (isAuthRequired(modelName)) {
372
+ let auth = await jwt_1.JWTAuth.verify(context.connectionParams.authorization);
373
+ if (auth.userId && UserDevice.checkSession(auth.sessionId, auth.userId, { lastIP: "IP", userAgent: context.connectionParams["user-agent"] })) {
374
+ if (modelName.toLowerCase() === "user") {
375
+ criteria.id = auth.userId;
376
+ }
377
+ else {
378
+ criteria.user = auth.userId;
373
379
  }
374
- else
375
- return null;
376
380
  }
377
381
  else {
378
- return null;
382
+ throw 'Authorization failed';
379
383
  }
380
384
  }
381
- let query = { where: criteria };
385
+ let query;
386
+ if (criteria.where === undefined) {
387
+ query = { where: criteria };
388
+ }
389
+ else {
390
+ query = criteria;
391
+ }
382
392
  //sorting
383
- if (sails.models[modelname].attributes.order) {
384
- query.sort = 'order ASC';
393
+ if (sails.models[modelname].attributes.sortOrder) {
394
+ query.sort = 'sortOrder ASC';
385
395
  }
386
- let result = await sails.models[modelname].find(query);
387
- getEmitter_1.default().emit(`graphql-query-${modelname}`, result);
388
- //workTime filter
389
- if (sails.models[modelname].attributes.workTime) {
396
+ let ORMrequest = sails.models[modelname].find(query);
397
+ if (args.skip) {
398
+ ORMrequest.skip(args.skip);
399
+ }
400
+ if (args.limit) {
401
+ ORMrequest.limit(args.limit);
402
+ }
403
+ if (args.sort) {
404
+ ORMrequest.sort(args.sort);
405
+ }
406
+ else {
407
+ if (sails.models[modelname].attributes.sortOrder) {
408
+ ORMrequest.sort('sortOrder ASC');
409
+ }
410
+ }
411
+ let result = await ORMrequest;
412
+ emitter.emit(`graphql-query-${modelname}`, result);
413
+ //worktime filter
414
+ if (sails.models[modelname].attributes.worktime) {
390
415
  result = result.filter(record => {
391
- if (!record.workTime)
416
+ if (!record.worktime)
392
417
  return true;
393
418
  try {
394
- return (worktime_1.WorkTimeValidator.isWorkNow({ workTime: record.workTime })).workNow;
419
+ return (worktime_1.WorkTimeValidator.isWorkNow({ worktime: record.worktime })).workNow;
395
420
  }
396
421
  catch (error) {
397
422
  sails.log.error("Graphql > helper > error: ", error);
@@ -399,12 +424,58 @@ function addModelResolver(modelname) {
399
424
  });
400
425
  }
401
426
  result.forEach(item => {
402
- getEmitter_1.default().emit(`http-api:before-send-${modelname.toLowerCase()}`, item);
427
+ emitter.emit(`http-api:before-send-${modelname.toLowerCase()}`, item);
403
428
  });
404
429
  return result;
405
430
  },
406
431
  };
407
432
  modelsResolvers.Query[methodName] = resolverQuery;
433
+ let resolverQueryCount = {
434
+ def: `""" [autogenerated] ${isAuthRequired(modelname) ? '\n[auth required]' : ''}""" ${methodName}Count(criteria: Json): Int`,
435
+ fn: async function (parent, args, context) {
436
+ let criteria = args.criteria || {};
437
+ criteria = sanitizeCriteria(modelname, criteria);
438
+ // If model has User field need auth
439
+ if (isAuthRequired(modelName)) {
440
+ let auth = await jwt_1.JWTAuth.verify(context.connectionParams.authorization);
441
+ if (auth.userId && UserDevice.checkSession(auth.sessionId, auth.userId, { lastIP: "IP", userAgent: context.connectionParams["user-agent"] })) {
442
+ if (modelName.toLowerCase() === "user") {
443
+ criteria.id = auth.userId;
444
+ }
445
+ else {
446
+ criteria.user = auth.userId;
447
+ }
448
+ }
449
+ else {
450
+ throw 'Authorization failed';
451
+ }
452
+ }
453
+ let query;
454
+ if (criteria.where === undefined) {
455
+ query = { where: criteria };
456
+ }
457
+ else {
458
+ query = criteria;
459
+ }
460
+ let ORMrequest = sails.models[modelname].find(query);
461
+ let result = await ORMrequest;
462
+ //worktime filter
463
+ if (sails.models[modelname].attributes.worktime) {
464
+ result = result.filter(record => {
465
+ if (!record.worktime)
466
+ return true;
467
+ try {
468
+ return (worktime_1.WorkTimeValidator.isWorkNow({ worktime: record.worktime })).workNow;
469
+ }
470
+ catch (error) {
471
+ sails.log.error("Graphql > helper > error: ", error);
472
+ }
473
+ });
474
+ }
475
+ return result.length;
476
+ },
477
+ };
478
+ modelsResolvers.Query[`${methodName}Count`] = resolverQueryCount;
408
479
  }
409
480
  // Model fields resolvers
410
481
  let resolvers = {};
@@ -434,37 +505,74 @@ function addModelResolver(modelname) {
434
505
  case "model":
435
506
  resolvers[key] = async (parent, args, context) => {
436
507
  criteria[relationKey] = parent[key];
508
+ // Check access rights
509
+ if (isAuthRequired(modelAttribute[modelRelationType])) {
510
+ let auth = await jwt_1.JWTAuth.verify(context.connectionParams.authorization);
511
+ if (auth.userId && UserDevice.checkSession(auth.sessionId, auth.userId, { lastIP: "IP", userAgent: context.connectionParams["user-agent"] })) {
512
+ if (modelName.toLowerCase() === "user") {
513
+ criteria["id"] = auth.userId;
514
+ }
515
+ else {
516
+ criteria["user"] = auth.userId;
517
+ }
518
+ }
519
+ else {
520
+ throw 'Authorization failed';
521
+ }
522
+ }
437
523
  let result = await sails.models[modelAttribute[modelRelationType]].findOne(criteria);
438
524
  // TODO: this need only for support legacy patching (discount)
439
- getEmitter_1.default().emit(`http-api:before-send-${modelAttribute.model.toLowerCase()}`, result);
525
+ emitter.emit(`http-api:before-send-${modelAttribute.model.toLowerCase()}`, result);
440
526
  // celan if not work time
441
- if (result && result.workTime && !worktime_1.WorkTimeValidator.isWorkNow({ workTime: result.workTime }).workNow) {
527
+ if (result && result.worktime && !worktime_1.WorkTimeValidator.isWorkNow({ worktime: result.worktime }).workNow) {
442
528
  result = null;
443
529
  }
530
+ return result;
531
+ };
532
+ // add virtual ids
533
+ resolvers[`${key}Id`] = async (parent, args, context) => {
534
+ return parent && parent[key];
444
535
  };
445
536
  return;
446
537
  case "collection":
447
538
  resolvers[key] = async (parent, args, context) => {
448
- let subcriteria = {};
449
- let subquery = { where: criteria };
450
- //sorting
451
- if (sails.models[modelname].attributes.order) {
452
- subquery.sort = 'order ASC';
539
+ let parentPrimaryKey = sails.models[modelname].primaryKey;
540
+ let criteria = {};
541
+ criteria[relationKey] = parent[parentPrimaryKey];
542
+ // Check access rights
543
+ if (isAuthRequired(modelAttribute[modelRelationType])) {
544
+ let auth = await jwt_1.JWTAuth.verify(context.connectionParams.authorization);
545
+ if (auth.userId && UserDevice.checkSession(auth.sessionId, auth.userId, { lastIP: "IP", userAgent: context.connectionParams["user-agent"] })) {
546
+ if (modelName.toLowerCase() === "user") {
547
+ criteria["id"] = auth.userId;
548
+ }
549
+ else {
550
+ criteria["user"] = auth.userId;
551
+ }
552
+ }
553
+ else {
554
+ throw 'Authorization failed';
555
+ }
556
+ }
557
+ let result = null;
558
+ result = (await sails.models[modelname].findOne({ id: parent.id }).populate(key))[key];
559
+ if (result && sails.models[modelAttribute[modelRelationType]].attributes.sortOrder) {
560
+ result.sort((a, b) => a.sortOrder - b.sortOrder);
453
561
  }
454
- let result = (await sails.models[modelname].findOne({ id: parent.id }).populate(key, subquery));
455
- result = result ? result[key] : null;
562
+ if (!result)
563
+ result = [];
456
564
  // TODO: this need only for support legacy patching (discount)
457
565
  if (result && result.length) {
458
566
  result.forEach(item => {
459
- getEmitter_1.default().emit(`http-api:before-send-${modelAttribute.collection.toLowerCase()}`, item);
567
+ emitter.emit(`http-api:before-send-${modelAttribute.collection.toLowerCase()}`, item);
460
568
  });
461
569
  }
462
- if (sails.models[modelname].attributes.workTime && Array.isArray(result)) {
570
+ if (sails.models[modelAttribute[modelRelationType]].attributes.worktime && Array.isArray(result) && result.length > 0) {
463
571
  result = result.filter(record => {
464
- if (!record.workTime)
572
+ if (!record.worktime)
465
573
  return true;
466
574
  try {
467
- return (worktime_1.WorkTimeValidator.isWorkNow({ workTime: record.workTime })).workNow;
575
+ return (worktime_1.WorkTimeValidator.isWorkNow({ worktime: record.worktime })).workNow;
468
576
  }
469
577
  catch (error) {
470
578
  sails.log.error("Graphql > helper > error: ", error);
@@ -489,25 +597,25 @@ function addModelResolver(modelname) {
489
597
  models.add(modelname);
490
598
  const methodName = `${firstLetterToLowerCase(modelName)}`;
491
599
  let subscription = {
492
- def: `""" Generated """ ${methodName}(criteria: Json): ${modelName}`,
600
+ def: `""" [autogenerated] ${isAuthRequired(modelname) ? '\n[auth required]' : ''} """ ${methodName}(criteria: Json): ${modelName} `,
493
601
  fn: {
494
- subscribe: withFilter((rootValue, args, context, info) => context.pubsub.asyncIterator(modelName), async (payload, args, context, info) => {
602
+ subscribe: (0, apollo_server_1.withFilter)((rootValue, args, context, info) => context.pubsub.asyncIterator(modelName), async (payload, args, context, info) => {
495
603
  // For User models
496
- if (sails.models[modelname].attributes.user) {
497
- if (userAuth) {
498
- let user = await userAuth(context.connectionParams.authorization);
499
- if (user.id === payload.user) {
500
- if (args.criteria) {
501
- checkCriteria(payload, args.criteria);
502
- }
503
- else {
504
- return true;
505
- }
604
+ if (sails.models[modelname].attributes.user || modelname === 'user') {
605
+ let auth = await jwt_1.JWTAuth.verify(context.connectionParams.authorization);
606
+ if (!args.criteria) {
607
+ args.criteria = {};
608
+ }
609
+ if (auth.userId) {
610
+ if (modelName.toLowerCase() === "user") {
611
+ args.criteria.id = auth.userId;
612
+ }
613
+ else {
614
+ args.criteria.user = auth.userId;
506
615
  }
507
- ;
508
616
  }
509
617
  else {
510
- return false;
618
+ throw 'Authorization failed';
511
619
  }
512
620
  }
513
621
  return checkCriteria(payload, args.criteria);
@@ -569,12 +677,16 @@ function modelPublishExtend(modelname) {
569
677
  publish: async function (id) {
570
678
  let data = await sails.models[modelname].findOne(id);
571
679
  // `http-api:request-${modelAttribute.collection.toLowerCase()}model-list`,
572
- getEmitter_1.default().emit(`http-api:before-send-${modelname.toLowerCase()}`, data);
680
+ emitter.emit(`http-api:before-send-${modelname.toLowerCase()}`, data);
573
681
  sails.graphql.pubsub.publish(modelName, data);
574
682
  },
575
683
  };
576
684
  _.merge(sails.models[modelname], modelPublishExtendObj);
577
685
  }
686
+ function isAuthRequired(modelname) {
687
+ modelname = modelname.toLowerCase();
688
+ return sails.models[modelname].attributes.user !== undefined || modelname === 'user';
689
+ }
578
690
  exports.default = {
579
691
  addModel,
580
692
  addType,