@sdflc/backend-helpers 1.0.23 → 1.0.24

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.
@@ -3,9 +3,9 @@ import { ApiContextInterface } from './interfaces';
3
3
  * Creates a GraphQL context object with all available cores.
4
4
  * @returns {object} A context object with all available cores
5
5
  */
6
- export declare const createApiContext: (args: ApiContextInterface) => any;
6
+ export declare const createApiContext: (args: ApiContextInterface) => Promise<any>;
7
7
  /**
8
8
  * Creates default a GraphQL context object with all avilable cores.
9
9
  * @returns {object} A context object with all available cores
10
10
  */
11
- export declare const createContextDefault: (args: any) => any;
11
+ export declare const createContextDefault: (args: any) => Promise<any>;
@@ -10,6 +10,42 @@ var __assign = (this && this.__assign) || function () {
10
10
  };
11
11
  return __assign.apply(this, arguments);
12
12
  };
13
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
+ return new (P || (P = Promise))(function (resolve, reject) {
16
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
20
+ });
21
+ };
22
+ var __generator = (this && this.__generator) || function (thisArg, body) {
23
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
24
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
+ function verb(n) { return function (v) { return step([n, v]); }; }
26
+ function step(op) {
27
+ if (f) throw new TypeError("Generator is already executing.");
28
+ while (_) try {
29
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
30
+ if (y = 0, t) op = [op[0] & 2, t.value];
31
+ switch (op[0]) {
32
+ case 0: case 1: t = op; break;
33
+ case 4: _.label++; return { value: op[1], done: false };
34
+ case 5: _.label++; y = op[1]; op = [0]; continue;
35
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
36
+ default:
37
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41
+ if (t[2]) _.ops.pop();
42
+ _.trys.pop(); continue;
43
+ }
44
+ op = body.call(thisArg, _);
45
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
+ }
48
+ };
13
49
  Object.defineProperty(exports, "__esModule", { value: true });
14
50
  exports.createContextDefault = exports.createApiContext = void 0;
15
51
  var lodash_1 = require("lodash");
@@ -20,75 +56,96 @@ var database_1 = require("./database");
20
56
  * Creates a GraphQL context object with all available cores.
21
57
  * @returns {object} A context object with all available cores
22
58
  */
23
- var createApiContext = function (args) {
24
- var _a = args || {}, cores = _a.cores, req = _a.req, getCoreContext = _a.getCoreContext, extendContext = _a.extendContext, inRequestId = _a.requestId;
25
- var keys = Object.keys(cores || {});
26
- var requestId = inRequestId || (0, uuid_1.v4)();
27
- var coreContext = typeof getCoreContext === 'function' ? getCoreContext({ req: req }) : {};
28
- var context = keys.reduce(function (acc, key) {
29
- acc[(0, lodash_1.camelCase)(key)] = new cores[key](__assign(__assign({}, coreContext), { requestId: requestId }));
30
- return acc;
31
- }, {});
32
- context.requestId = requestId;
33
- if (typeof extendContext === 'function') {
34
- extendContext({ context: context, req: req });
35
- }
36
- return context;
37
- };
59
+ var createApiContext = function (args) { return __awaiter(void 0, void 0, void 0, function () {
60
+ var _a, cores, req, getCoreContext, extendContext, inRequestId, keys, requestId, coreContext, _b, context;
61
+ return __generator(this, function (_c) {
62
+ switch (_c.label) {
63
+ case 0:
64
+ _a = args || {}, cores = _a.cores, req = _a.req, getCoreContext = _a.getCoreContext, extendContext = _a.extendContext, inRequestId = _a.requestId;
65
+ keys = Object.keys(cores || {});
66
+ requestId = inRequestId || (0, uuid_1.v4)();
67
+ if (!(typeof getCoreContext === 'function')) return [3 /*break*/, 2];
68
+ return [4 /*yield*/, getCoreContext({ req: req })];
69
+ case 1:
70
+ _b = _c.sent();
71
+ return [3 /*break*/, 3];
72
+ case 2:
73
+ _b = {};
74
+ _c.label = 3;
75
+ case 3:
76
+ coreContext = _b;
77
+ context = keys.reduce(function (acc, key) {
78
+ acc[(0, lodash_1.camelCase)(key)] = new cores[key](__assign(__assign({}, coreContext), { requestId: requestId }));
79
+ return acc;
80
+ }, {});
81
+ context.requestId = requestId;
82
+ if (!(typeof extendContext === 'function')) return [3 /*break*/, 5];
83
+ return [4 /*yield*/, extendContext({ context: context, req: req })];
84
+ case 4:
85
+ _c.sent();
86
+ _c.label = 5;
87
+ case 5: return [2 /*return*/, context];
88
+ }
89
+ });
90
+ }); };
38
91
  exports.createApiContext = createApiContext;
39
92
  /**
40
93
  * Creates default a GraphQL context object with all avilable cores.
41
94
  * @returns {object} A context object with all available cores
42
95
  */
43
- var createContextDefault = function (args) {
44
- var _a = args || {}, knexConfig = _a.knexConfig, dbSchema = _a.dbSchema, cores = _a.cores, req = _a.req;
45
- var authorization = req.headers['authorization'];
46
- var spaceId = req.headers['x-space-id'];
47
- var apiKey = req.headers['x-api-key'];
48
- var managementApiKey = req.headers['x-management-api-key'];
49
- var accountId = req.headers['x-account-id'];
50
- var roleId = req.headers['x-role-id'];
51
- var userId = req.headers['x-user-id'];
52
- var userAgent = req.headers['user-agent'];
53
- var referer = req.headers['referer'];
54
- var ipAddress = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
55
- var acceptLanguage = req.headers['accept-language'];
56
- var languages = (0, utils_1.extractLanguages)(acceptLanguage);
57
- var requestedLang = req.query['lang'];
58
- var requestId = (0, uuid_1.v4)();
59
- var db = new database_1.Database({
60
- knexConfig: knexConfig,
61
- dbSchema: dbSchema,
62
- });
63
- return (0, exports.createApiContext)({
64
- cores: cores,
65
- req: req,
66
- requestId: requestId,
67
- extendContext: function (_a) {
68
- var context = _a.context /*, req */;
69
- context.db = db;
70
- },
71
- getCoreContext: function ( /*args: any*/) {
72
- // TODO: const { req } = args;
73
- return {
74
- db: db,
75
- context: {
76
- spaceId: spaceId,
77
- apiKey: apiKey,
78
- managementApiKey: managementApiKey,
79
- userAgent: userAgent,
80
- referer: referer,
81
- ipAddress: ipAddress,
82
- acceptLanguage: acceptLanguage,
83
- languages: languages,
84
- requestedLang: requestedLang,
85
- authorization: authorization,
86
- accountId: accountId,
87
- roleId: roleId,
88
- userId: userId,
89
- },
90
- };
91
- },
96
+ var createContextDefault = function (args) { return __awaiter(void 0, void 0, void 0, function () {
97
+ var _a, knexConfig, dbSchema, cores, req, extendContext, getCoreContext, authorization, spaceId, apiKey, managementApiKey, accountId, roleId, userId, userAgent, referer, ipAddress, acceptLanguage, languages, requestedLang, requestId, db;
98
+ return __generator(this, function (_b) {
99
+ switch (_b.label) {
100
+ case 0:
101
+ _a = args || {}, knexConfig = _a.knexConfig, dbSchema = _a.dbSchema, cores = _a.cores, req = _a.req, extendContext = _a.extendContext, getCoreContext = _a.getCoreContext;
102
+ authorization = req.headers['authorization'] ? req.headers['authorization'].replace('Bearer ', '') : undefined;
103
+ spaceId = req.headers['x-space-id'];
104
+ apiKey = req.headers['x-api-key'];
105
+ managementApiKey = req.headers['x-management-api-key'];
106
+ accountId = req.headers['x-account-id'];
107
+ roleId = req.headers['x-role-id'];
108
+ userId = req.headers['x-user-id'];
109
+ userAgent = req.headers['user-agent'];
110
+ referer = req.headers['referer'];
111
+ ipAddress = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
112
+ acceptLanguage = req.headers['accept-language'];
113
+ languages = (0, utils_1.extractLanguages)(acceptLanguage);
114
+ requestedLang = req.query['lang'];
115
+ requestId = (0, uuid_1.v4)();
116
+ db = new database_1.Database({
117
+ knexConfig: knexConfig,
118
+ dbSchema: dbSchema,
119
+ });
120
+ return [4 /*yield*/, (0, exports.createApiContext)({
121
+ cores: cores,
122
+ req: req,
123
+ requestId: requestId,
124
+ extendContext: function (_a) {
125
+ var context = _a.context, req = _a.req;
126
+ context.db = db;
127
+ if (typeof extendContext === 'function') {
128
+ extendContext({ context: context, req: req });
129
+ }
130
+ },
131
+ getCoreContext: function (args) { return __awaiter(void 0, void 0, void 0, function () {
132
+ var extendCoreConext;
133
+ return __generator(this, function (_a) {
134
+ switch (_a.label) {
135
+ case 0:
136
+ extendCoreConext = {};
137
+ if (!(typeof getCoreContext === 'function')) return [3 /*break*/, 2];
138
+ return [4 /*yield*/, getCoreContext(args)];
139
+ case 1:
140
+ extendCoreConext = _a.sent();
141
+ _a.label = 2;
142
+ case 2: return [2 /*return*/, __assign(__assign({ db: db }, extendCoreConext), { context: __assign({ spaceId: spaceId, apiKey: apiKey, managementApiKey: managementApiKey, userAgent: userAgent, referer: referer, ipAddress: ipAddress, acceptLanguage: acceptLanguage, languages: languages, requestedLang: requestedLang, authorization: authorization, accountId: accountId, roleId: roleId, userId: userId }, (extendCoreConext.context || {})) })];
143
+ }
144
+ });
145
+ }); },
146
+ })];
147
+ case 1: return [2 /*return*/, _b.sent()];
148
+ }
92
149
  });
93
- };
150
+ }); };
94
151
  exports.createContextDefault = createContextDefault;
@@ -1,16 +1,21 @@
1
1
  import { Logger } from '@sdflc/utils';
2
2
  import { BaseCoreInterface, BaseCoreDoingWhatInterface, BaseCoreActionsInterface, CoreActionInterface, BaseCoreValidatorsInterface } from './interfaces';
3
+ import { VerifyUserTokenArgs } from './interfaces/VerifyUserTokenArgs';
3
4
  import { BaseGateway } from './baseGateway';
4
5
  import { Database } from './database';
5
6
  declare class BaseCore {
6
7
  protected props: BaseCoreInterface;
7
8
  protected db: Database;
8
9
  protected context: any;
9
- protected gateway?: BaseGateway;
10
10
  protected doingWhat?: BaseCoreDoingWhatInterface;
11
11
  protected logger: Logger;
12
12
  protected name?: string;
13
+ protected gateway?: BaseGateway;
13
14
  protected gateways?: any;
15
+ protected gwSpace?: BaseGateway;
16
+ protected interserviceApiKey?: string;
17
+ protected jwtSecret: string;
18
+ protected verifytokenArgs?: VerifyUserTokenArgs;
14
19
  protected requestId: string;
15
20
  protected validators: BaseCoreValidatorsInterface;
16
21
  protected doAuth: boolean;
@@ -52,6 +57,6 @@ declare class BaseCore {
52
57
  beforeRemoveMany(params: any, opt?: BaseCoreActionsInterface): Promise<any>;
53
58
  afterRemoveMany(params: any, opt?: BaseCoreActionsInterface): Promise<any>;
54
59
  onException(params: any, opt?: BaseCoreActionsInterface): Promise<any>;
55
- authenticate(params: any, opt?: BaseCoreActionsInterface): Promise<any>;
60
+ authenticate(params: any, opt?: BaseCoreActionsInterface): Promise<any[]>;
56
61
  }
57
62
  export { BaseCore };
package/build/baseCore.js CHANGED
@@ -50,6 +50,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
50
50
  exports.BaseCore = void 0;
51
51
  var api_helpers_1 = require("@sdflc/api-helpers");
52
52
  var utils_1 = require("@sdflc/utils");
53
+ var userToken_1 = require("./userToken");
54
+ var baseGateway_1 = require("./baseGateway");
53
55
  var utils_2 = require("./utils");
54
56
  var defaultAfterAndBefore = function (params, opt) {
55
57
  return params;
@@ -69,20 +71,31 @@ var defaultValidators = {
69
71
  remove: defaultValidate,
70
72
  removeMany: defaultValidate,
71
73
  };
72
- var defaultAuth = function (params) {
73
- return [true, ''];
74
- };
75
74
  var BaseCore = /** @class */ (function () {
76
75
  function BaseCore(props) {
76
+ var _this = this;
77
77
  this.validators = defaultValidators;
78
78
  this.props = props || {};
79
79
  this.db = props.db;
80
80
  this.name = props.name || '';
81
81
  this.context = props.context || {};
82
- this.gateway = props.gateway;
83
82
  this.doingWhat = props.doingWhat;
84
83
  this.logger = props.logger || new utils_1.Logger({ level: props.logLevel });
84
+ this.gateway = props.gateway;
85
85
  this.gateways = __assign({ gateway: this.gateway }, (props.gateways || {}));
86
+ if (this.gateway instanceof baseGateway_1.BaseGateway) {
87
+ this.gateway.setCore(this);
88
+ }
89
+ Object.keys(this.gateways).forEach(function (gatewayName) {
90
+ var gateway = _this.gateways[gatewayName];
91
+ if (gateway instanceof baseGateway_1.BaseGateway) {
92
+ gateway.setCore(_this);
93
+ }
94
+ });
95
+ this.gwSpace = props.gwSpace;
96
+ this.interserviceApiKey = props.interserviceApiKey;
97
+ this.jwtSecret = props.jwtSecret || '';
98
+ this.verifytokenArgs = props.verifytokenArgs;
86
99
  this.validators = (0, utils_2.setFunctions)((props === null || props === void 0 ? void 0 : props.validators) || {}, this.validators);
87
100
  this.doAuth = props.doAuth === true;
88
101
  this.requestId = props.requestId || '';
@@ -142,7 +155,7 @@ var BaseCore = /** @class */ (function () {
142
155
  msg = doingWhat['message'];
143
156
  }
144
157
  else {
145
- msg = "Sorry, something went wrong on ".concat(doingWhat, ".").concat(isOpResult ? " Reason: ".concat(ex.getErrorSummary()) : '');
158
+ msg = isOpResult ? ex.getErrorSummary() : "Sorry, something went wrong on ".concat(doingWhat);
146
159
  }
147
160
  this.logger.error(sysMsg, ex);
148
161
  }
@@ -762,11 +775,49 @@ var BaseCore = /** @class */ (function () {
762
775
  });
763
776
  };
764
777
  BaseCore.prototype.authenticate = function (params, opt) {
778
+ var _a;
765
779
  return __awaiter(this, void 0, void 0, function () {
766
- var fn;
767
- return __generator(this, function (_a) {
768
- fn = typeof this.props.authenticate === 'function' ? this.props.authenticate : defaultAuth;
769
- return [2 /*return*/, fn(params, opt)];
780
+ var context, authByToken, verifyResult, token, space;
781
+ return __generator(this, function (_b) {
782
+ switch (_b.label) {
783
+ case 0:
784
+ if (!(typeof this.props.authenticate === 'function')) return [3 /*break*/, 2];
785
+ return [4 /*yield*/, this.props.authenticate(params, opt)];
786
+ case 1:
787
+ // if we have an auth function passed to constructor then use it for the authentication
788
+ return [2 /*return*/, _b.sent()];
789
+ case 2:
790
+ context = this.context;
791
+ authByToken = false;
792
+ if (context.authorization && this.jwtSecret) {
793
+ verifyResult = (0, userToken_1.verifyUserToken)(context.authorization, this.jwtSecret, this.verifytokenArgs);
794
+ if (verifyResult.didFail()) {
795
+ return [2 /*return*/, [false, verifyResult.getErrorSummary('')]];
796
+ }
797
+ token = verifyResult.getDataFirst();
798
+ context.accountId = token.accountId;
799
+ context.roleId = token.roleId;
800
+ context.userId = token.userId;
801
+ context.spaceId = token.spaceId || context.spaceId;
802
+ authByToken = true;
803
+ }
804
+ return [4 /*yield*/, ((_a = this.gwSpace) === null || _a === void 0 ? void 0 : _a.get(context.spaceId || ''))];
805
+ case 3:
806
+ space = _b.sent();
807
+ if (!space) {
808
+ return [2 /*return*/, [false, 'Space Not Found']];
809
+ }
810
+ context.space = space;
811
+ if (!authByToken) {
812
+ if (this.interserviceApiKey && context.apiKey === this.interserviceApiKey) {
813
+ return [2 /*return*/, [true, '']];
814
+ }
815
+ else if (space.apiKey && space.apiKey !== context.apiKey) {
816
+ return [2 /*return*/, [false, 'API Key is invalid']];
817
+ }
818
+ }
819
+ return [2 /*return*/, [true, '']];
820
+ }
770
821
  });
771
822
  });
772
823
  };
@@ -15,7 +15,7 @@ declare class BaseGateway {
15
15
  getDb(): import("./database").Database;
16
16
  getBuilder(): any;
17
17
  getIdField(): any;
18
- getCore(): BaseCore;
18
+ getCore(): BaseCore | undefined;
19
19
  setCore(core: BaseCore): void;
20
20
  get(id: any): Promise<any>;
21
21
  getMany(ids: any[]): Promise<any>;
@@ -1,5 +1,5 @@
1
1
  import { DbFieldAddDefaultInterface } from './interfaces';
2
- declare const dbFieldAddDefaults: (table: any, opt?: DbFieldAddDefaultInterface | undefined) => void;
2
+ export declare const dbFieldAddDefaults: (table: any, opt?: DbFieldAddDefaultInterface | undefined) => void;
3
3
  export declare const addOrderNo: (table: any, opt?: any) => any;
4
4
  export declare const addAmount: (table: any, fieldName: string) => any;
5
5
  export declare const addSpaceId: (table: any, opt?: any) => any;
@@ -7,4 +7,3 @@ export declare const addUserId: (table: any, opt?: any) => any;
7
7
  export declare const defaultFields: (opt?: any) => {
8
8
  [x: number]: string;
9
9
  };
10
- export { dbFieldAddDefaults };
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.dbFieldAddDefaults = exports.defaultFields = exports.addUserId = exports.addSpaceId = exports.addAmount = exports.addOrderNo = void 0;
6
+ exports.defaultFields = exports.addUserId = exports.addSpaceId = exports.addAmount = exports.addOrderNo = exports.dbFieldAddDefaults = void 0;
7
7
  var utils_1 = require("@sdflc/utils");
8
8
  var constants_1 = __importDefault(require("./constants"));
9
9
  var FIELDS = constants_1.default.FIELDS;
package/build/index.d.ts CHANGED
@@ -11,10 +11,9 @@ export { checkArray, createErrorOnCheckError } from './checkItHelpers';
11
11
  export { DataCache } from './dataCache';
12
12
  export { BaseGateway } from './baseGateway';
13
13
  export { BaseCore } from './baseCore';
14
- export { AppBaseCore } from './appBaseCore';
15
14
  export { createApiContext, createContextDefault } from './apiContext';
16
15
  export { BaseController } from './baseController';
17
- export { dbFieldAddDefaults } from './dbTableHelpers';
16
+ export { dbFieldAddDefaults, addOrderNo, addAmount, addSpaceId, addUserId, defaultFields } from './dbTableHelpers';
18
17
  export { buildDefaultResolvers } from './resolversHelpers';
19
18
  export { createUserToken, verifyUserToken } from './userToken';
20
19
  export { constants };
package/build/index.js CHANGED
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.checkPassword = exports.getSaltAndHash = exports.buildDefaultGatewayProps = exports.constants = exports.verifyUserToken = exports.createUserToken = exports.buildDefaultResolvers = exports.dbFieldAddDefaults = exports.BaseController = exports.createContextDefault = exports.createApiContext = exports.AppBaseCore = exports.BaseCore = exports.BaseGateway = exports.DataCache = exports.createErrorOnCheckError = exports.checkArray = exports.createRedisClient = exports.buildKnexConfig = exports.dbSeed = exports.DbMigratorAndSeeder = exports.dbRunMigrations = exports.dbTransformSeedsToObject = exports.dbReset = exports.dbWipe = exports.dbClean = exports.dbListTables = exports.dbCleanTable = exports.Database = exports.buildConfig = void 0;
6
+ exports.checkPassword = exports.getSaltAndHash = exports.buildDefaultGatewayProps = exports.constants = exports.verifyUserToken = exports.createUserToken = exports.buildDefaultResolvers = exports.defaultFields = exports.addUserId = exports.addSpaceId = exports.addAmount = exports.addOrderNo = exports.dbFieldAddDefaults = exports.BaseController = exports.createContextDefault = exports.createApiContext = exports.BaseCore = exports.BaseGateway = exports.DataCache = exports.createErrorOnCheckError = exports.checkArray = exports.createRedisClient = exports.buildKnexConfig = exports.dbSeed = exports.DbMigratorAndSeeder = exports.dbRunMigrations = exports.dbTransformSeedsToObject = exports.dbReset = exports.dbWipe = exports.dbClean = exports.dbListTables = exports.dbCleanTable = exports.Database = exports.buildConfig = void 0;
7
7
  var constants_1 = __importDefault(require("./constants"));
8
8
  exports.constants = constants_1.default;
9
9
  var configBulder_1 = require("./configBulder");
@@ -35,8 +35,6 @@ var baseGateway_1 = require("./baseGateway");
35
35
  Object.defineProperty(exports, "BaseGateway", { enumerable: true, get: function () { return baseGateway_1.BaseGateway; } });
36
36
  var baseCore_1 = require("./baseCore");
37
37
  Object.defineProperty(exports, "BaseCore", { enumerable: true, get: function () { return baseCore_1.BaseCore; } });
38
- var appBaseCore_1 = require("./appBaseCore");
39
- Object.defineProperty(exports, "AppBaseCore", { enumerable: true, get: function () { return appBaseCore_1.AppBaseCore; } });
40
38
  var apiContext_1 = require("./apiContext");
41
39
  Object.defineProperty(exports, "createApiContext", { enumerable: true, get: function () { return apiContext_1.createApiContext; } });
42
40
  Object.defineProperty(exports, "createContextDefault", { enumerable: true, get: function () { return apiContext_1.createContextDefault; } });
@@ -44,6 +42,11 @@ var baseController_1 = require("./baseController");
44
42
  Object.defineProperty(exports, "BaseController", { enumerable: true, get: function () { return baseController_1.BaseController; } });
45
43
  var dbTableHelpers_1 = require("./dbTableHelpers");
46
44
  Object.defineProperty(exports, "dbFieldAddDefaults", { enumerable: true, get: function () { return dbTableHelpers_1.dbFieldAddDefaults; } });
45
+ Object.defineProperty(exports, "addOrderNo", { enumerable: true, get: function () { return dbTableHelpers_1.addOrderNo; } });
46
+ Object.defineProperty(exports, "addAmount", { enumerable: true, get: function () { return dbTableHelpers_1.addAmount; } });
47
+ Object.defineProperty(exports, "addSpaceId", { enumerable: true, get: function () { return dbTableHelpers_1.addSpaceId; } });
48
+ Object.defineProperty(exports, "addUserId", { enumerable: true, get: function () { return dbTableHelpers_1.addUserId; } });
49
+ Object.defineProperty(exports, "defaultFields", { enumerable: true, get: function () { return dbTableHelpers_1.defaultFields; } });
47
50
  var resolversHelpers_1 = require("./resolversHelpers");
48
51
  Object.defineProperty(exports, "buildDefaultResolvers", { enumerable: true, get: function () { return resolversHelpers_1.buildDefaultResolvers; } });
49
52
  var userToken_1 = require("./userToken");
@@ -4,6 +4,7 @@ import { Database } from '../database';
4
4
  import { BaseGateway } from '../baseGateway';
5
5
  import { BaseCoreValidatorsInterface } from './BaseCoreValidatorsInterface';
6
6
  import { BaseCoreDoingWhatInterface } from './BaseCoreDoingWhatInterface';
7
+ import { VerifyUserTokenArgs } from './VerifyUserTokenArgs';
7
8
  export interface BaseCoreInterface {
8
9
  db: Database;
9
10
  context?: any;
@@ -35,4 +36,8 @@ export interface BaseCoreInterface {
35
36
  onException?(params: any, opt?: BaseCoreActionsInterface): any;
36
37
  validators?: BaseCoreValidatorsInterface;
37
38
  authenticate?(params: any, opt?: BaseCoreActionsInterface): Promise<any[]> | any[];
39
+ gwSpace?: BaseGateway;
40
+ interserviceApiKey?: string;
41
+ jwtSecret?: string;
42
+ verifytokenArgs?: VerifyUserTokenArgs;
38
43
  }
@@ -5,7 +5,7 @@ import { LoaderInterface } from './LoaderInterface';
5
5
  import { SortItemInterface } from './SortItemInterface';
6
6
  export interface BaseGatewayInterface {
7
7
  db: Database;
8
- core: BaseCore;
8
+ core?: BaseCore;
9
9
  table?: string;
10
10
  idField?: string;
11
11
  setFields?: string[] | string;
@@ -1,7 +1,4 @@
1
- import { UserTokenParams } from './UserTokenParams';
2
1
  export interface CreateUserTokenArgs {
3
- params: UserTokenParams;
4
- secret: string;
5
2
  algorithm?: any;
6
3
  audience?: string | string[];
7
4
  issuer?: string;
@@ -1,6 +1,4 @@
1
1
  export interface VerifyUserTokenArgs {
2
- token: string;
3
- secret: string;
4
2
  algorithms?: any;
5
3
  audience?: string | string[];
6
4
  issuer?: string | string[];
@@ -5,7 +5,6 @@ export { ListArgsInterface } from './ListArgsInterface';
5
5
  export { SortItemInterface } from './SortItemInterface';
6
6
  export { PaginationInterface } from './PaginationInterface';
7
7
  export { BaseCoreInterface } from './BaseCoreInterface';
8
- export { AppBaseCoreInterface } from './AppBaseCoreInterface';
9
8
  export { CoreActionInterface } from './CoreActionInterface';
10
9
  export { ApiContextInterface } from './ApiContextInterface';
11
10
  export { DbFieldAddDefaultInterface } from './DbFieldAddDefaultInterface';
@@ -1,4 +1,4 @@
1
1
  import { OpResult } from '@sdflc/api-helpers';
2
- import { CreateUserTokenArgs, VerifyUserTokenArgs } from './interfaces';
3
- export declare const createUserToken: (args: CreateUserTokenArgs) => OpResult;
4
- export declare const verifyUserToken: (args: VerifyUserTokenArgs) => OpResult;
2
+ import { UserTokenParams, CreateUserTokenArgs, VerifyUserTokenArgs } from './interfaces';
3
+ export declare const createUserToken: (params: UserTokenParams, secret: string, opt: CreateUserTokenArgs) => OpResult;
4
+ export declare const verifyUserToken: (token: string, secret: string, args?: VerifyUserTokenArgs | undefined) => OpResult;
@@ -6,13 +6,13 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.verifyUserToken = exports.createUserToken = void 0;
7
7
  var jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
8
8
  var api_helpers_1 = require("@sdflc/api-helpers");
9
- var createUserToken = function (args) {
10
- var _a = args || {}, params = _a.params, secret = _a.secret, algorithm = _a.algorithm, audience = _a.audience, issuer = _a.issuer, jwtid = _a.jwtid, subject = _a.subject, noTimestamp = _a.noTimestamp, header = _a.header, keyid = _a.keyid, expiresIn = _a.expiresIn;
11
- if (!args) {
9
+ var createUserToken = function (params, secret, opt) {
10
+ var _a = opt || {}, algorithm = _a.algorithm, audience = _a.audience, issuer = _a.issuer, jwtid = _a.jwtid, subject = _a.subject, noTimestamp = _a.noTimestamp, header = _a.header, keyid = _a.keyid, expiresIn = _a.expiresIn;
11
+ if (!params || !secret) {
12
12
  return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED);
13
13
  }
14
14
  var token = jsonwebtoken_1.default.sign(params, secret, {
15
- algorithm: algorithm,
15
+ algorithm: algorithm || 'HS256',
16
16
  audience: audience,
17
17
  issuer: issuer,
18
18
  jwtid: jwtid,
@@ -25,23 +25,28 @@ var createUserToken = function (args) {
25
25
  return api_helpers_1.OpResult.ok(token);
26
26
  };
27
27
  exports.createUserToken = createUserToken;
28
- var verifyUserToken = function (args) {
29
- var _a = args || {}, token = _a.token, secret = _a.secret, algorithms = _a.algorithms, audience = _a.audience, issuer = _a.issuer, ignoreExpiration = _a.ignoreExpiration, ignoreNotBefore = _a.ignoreNotBefore, subject = _a.subject, clockTolerance = _a.clockTolerance, maxAge = _a.maxAge, clockTimestamp = _a.clockTimestamp, nonce = _a.nonce;
28
+ var verifyUserToken = function (token, secret, args) {
29
+ var _a = args || {}, algorithms = _a.algorithms, audience = _a.audience, issuer = _a.issuer, ignoreExpiration = _a.ignoreExpiration, ignoreNotBefore = _a.ignoreNotBefore, subject = _a.subject, clockTolerance = _a.clockTolerance, maxAge = _a.maxAge, clockTimestamp = _a.clockTimestamp, nonce = _a.nonce;
30
30
  if (!args) {
31
31
  return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED);
32
32
  }
33
- var obj = jsonwebtoken_1.default.verify(token, secret, {
34
- algorithms: algorithms,
35
- audience: audience,
36
- issuer: issuer,
37
- ignoreExpiration: ignoreExpiration,
38
- ignoreNotBefore: ignoreNotBefore,
39
- subject: subject,
40
- clockTolerance: clockTolerance,
41
- maxAge: maxAge,
42
- clockTimestamp: clockTimestamp,
43
- nonce: nonce,
44
- });
45
- return api_helpers_1.OpResult.ok(obj);
33
+ try {
34
+ var obj = jsonwebtoken_1.default.verify(token, secret, {
35
+ algorithms: algorithms || ['HS256'],
36
+ audience: audience,
37
+ issuer: issuer,
38
+ ignoreExpiration: ignoreExpiration,
39
+ ignoreNotBefore: ignoreNotBefore,
40
+ subject: subject,
41
+ clockTolerance: clockTolerance,
42
+ maxAge: maxAge,
43
+ clockTimestamp: clockTimestamp,
44
+ nonce: nonce,
45
+ });
46
+ return api_helpers_1.OpResult.ok(obj);
47
+ }
48
+ catch (ex) {
49
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.UNAUTHORIZED);
50
+ }
46
51
  };
47
52
  exports.verifyUserToken = verifyUserToken;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sdflc/backend-helpers",
3
- "version": "1.0.23",
3
+ "version": "1.0.24",
4
4
  "description": "Set of helper functions and classes to simplify building backend apps within @sdflc ecosystem",
5
5
  "main": "build/index.js",
6
6
  "types": "build/index.d.ts",
@@ -1,9 +0,0 @@
1
- import { AppBaseCoreInterface, BaseCoreActionsInterface } from './interfaces';
2
- import { BaseCore } from './baseCore';
3
- declare class AppBaseCore extends BaseCore {
4
- private gwSpace;
5
- private interserviceApiKey?;
6
- constructor(props: AppBaseCoreInterface);
7
- authenticate(params: any, opt?: BaseCoreActionsInterface): Promise<(string | boolean)[]>;
8
- }
9
- export { AppBaseCore };
@@ -1,91 +0,0 @@
1
- "use strict";
2
- var __extends = (this && this.__extends) || (function () {
3
- var extendStatics = function (d, b) {
4
- extendStatics = Object.setPrototypeOf ||
5
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
- return extendStatics(d, b);
8
- };
9
- return function (d, b) {
10
- if (typeof b !== "function" && b !== null)
11
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
- extendStatics(d, b);
13
- function __() { this.constructor = d; }
14
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
- };
16
- })();
17
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
18
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
19
- return new (P || (P = Promise))(function (resolve, reject) {
20
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
21
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
22
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
23
- step((generator = generator.apply(thisArg, _arguments || [])).next());
24
- });
25
- };
26
- var __generator = (this && this.__generator) || function (thisArg, body) {
27
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
28
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
29
- function verb(n) { return function (v) { return step([n, v]); }; }
30
- function step(op) {
31
- if (f) throw new TypeError("Generator is already executing.");
32
- while (_) try {
33
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
34
- if (y = 0, t) op = [op[0] & 2, t.value];
35
- switch (op[0]) {
36
- case 0: case 1: t = op; break;
37
- case 4: _.label++; return { value: op[1], done: false };
38
- case 5: _.label++; y = op[1]; op = [0]; continue;
39
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
40
- default:
41
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
42
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
43
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
44
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
45
- if (t[2]) _.ops.pop();
46
- _.trys.pop(); continue;
47
- }
48
- op = body.call(thisArg, _);
49
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
50
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
51
- }
52
- };
53
- Object.defineProperty(exports, "__esModule", { value: true });
54
- exports.AppBaseCore = void 0;
55
- var baseCore_1 = require("./baseCore");
56
- var AppBaseCore = /** @class */ (function (_super) {
57
- __extends(AppBaseCore, _super);
58
- function AppBaseCore(props) {
59
- var _this = _super.call(this, props) || this;
60
- _this.gwSpace = props.gwSpace;
61
- _this.interserviceApiKey = props.interserviceApiKey;
62
- return _this;
63
- }
64
- AppBaseCore.prototype.authenticate = function (params, opt) {
65
- return __awaiter(this, void 0, void 0, function () {
66
- var context, space;
67
- return __generator(this, function (_a) {
68
- switch (_a.label) {
69
- case 0:
70
- context = this.context;
71
- return [4 /*yield*/, this.gwSpace.get(context.spaceId || '')];
72
- case 1:
73
- space = _a.sent();
74
- if (!space) {
75
- return [2 /*return*/, [false, 'Space Not Found']];
76
- }
77
- context.space = space;
78
- if (this.interserviceApiKey && context.apiKey === this.interserviceApiKey) {
79
- return [2 /*return*/, [true, '']];
80
- }
81
- else if (space.apiKey && space.apiKey !== context.apiKey) {
82
- return [2 /*return*/, [false, 'API Key is invalid']];
83
- }
84
- return [2 /*return*/, [true, '']];
85
- }
86
- });
87
- });
88
- };
89
- return AppBaseCore;
90
- }(baseCore_1.BaseCore));
91
- exports.AppBaseCore = AppBaseCore;
@@ -1,6 +0,0 @@
1
- import { BaseGateway } from '../baseGateway';
2
- import { BaseCoreInterface } from './BaseCoreInterface';
3
- export interface AppBaseCoreInterface extends BaseCoreInterface {
4
- gwSpace: BaseGateway;
5
- interserviceApiKey?: string;
6
- }
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });