@sdflc/backend-helpers 1.0.105 → 1.0.107

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/build/BaseCore.js CHANGED
@@ -145,7 +145,7 @@ class BaseCore {
145
145
  }
146
146
  }
147
147
  async runAction(opt) {
148
- const { args, validate, doAuth, action, hasTransaction, doingWhat, onException, shouldLogArgs, requireSpace } = opt || {};
148
+ const { args, validate, doAuth, roles, action, hasTransaction, doingWhat, onException, shouldLogArgs, requireSpace, } = opt || {};
149
149
  // If we process action with the same requestId as requestId passed to the constructor it means
150
150
  // we are processing the same request from FE and can skip some of the operations like transactions and etc
151
151
  const sameRequest = !!this.config.context.requestId && args?.requestId === this.config.context.requestId;
@@ -203,6 +203,17 @@ class BaseCore {
203
203
  }
204
204
  }
205
205
  }
206
+ // Check if the action requires simple role verification.
207
+ // If roles are provided but user has no role or user's roles is not included in the allowed roles then return an error
208
+ if (Array.isArray(roles) && roles?.length) {
209
+ const userRoleId = this.getContext().roleId || '';
210
+ if (!userRoleId) {
211
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.FORBIDDEN, [], 'User has not assigned role');
212
+ }
213
+ else if (!roles.includes(userRoleId)) {
214
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.FORBIDDEN, [], 'User role does not allow this operation');
215
+ }
216
+ }
206
217
  let validatedItems = {};
207
218
  if (typeof validate === 'function') {
208
219
  this.measureTool.addCheckpoint('Validate parameters: start');
@@ -310,10 +310,7 @@ class BaseGateway {
310
310
  }
311
311
  const items = await query;
312
312
  const result = shouldUseCache ? await this.getMany(items.map((row) => row.id)) : items;
313
- console.log('=== list.result', result);
314
- const trasnformed = result.map((item) => this.transformOnOut(item));
315
- console.log('=== list.trasnformed', trasnformed);
316
- return result;
313
+ return result.map((item) => this.transformOnOut(item));
317
314
  }
318
315
  async create(args) {
319
316
  const objects = (0, lodash_1.castArray)(args);
@@ -16,15 +16,16 @@ class DataCache {
16
16
  redisClient;
17
17
  constructor(props) {
18
18
  const { loaderFn, keyPrefix, context, buildKey, redisClient, table } = props || {};
19
- this.config = {
19
+ const innerProps = {
20
20
  ...props,
21
21
  idField: props?.idField || _1.FIELDS.ID,
22
22
  idFieldAs: props?.idFieldAs || _1.FIELDS.ID,
23
23
  };
24
+ this.config = innerProps;
24
25
  this.redisClient = redisClient;
25
26
  this.buildKey = typeof buildKey === 'function' ? buildKey : utils_1.buildKey;
26
27
  this.batchLoaderDefault = this.batchLoaderDefault.bind(this);
27
- const fn = typeof loaderFn === 'function' ? loaderFn : this.batchLoaderDefault(props);
28
+ const fn = typeof loaderFn === 'function' ? loaderFn : this.batchLoaderDefault(innerProps);
28
29
  const prefixToUse = context?.keyPrefix || keyPrefix || table;
29
30
  this.init(fn, prefixToUse, context);
30
31
  }
@@ -139,7 +139,7 @@ class BaseCore {
139
139
  }
140
140
  }
141
141
  async runAction(opt) {
142
- const { args, validate, doAuth, action, hasTransaction, doingWhat, onException, shouldLogArgs, requireSpace } = opt || {};
142
+ const { args, validate, doAuth, roles, action, hasTransaction, doingWhat, onException, shouldLogArgs, requireSpace, } = opt || {};
143
143
  // If we process action with the same requestId as requestId passed to the constructor it means
144
144
  // we are processing the same request from FE and can skip some of the operations like transactions and etc
145
145
  const sameRequest = !!this.config.context.requestId && args?.requestId === this.config.context.requestId;
@@ -197,6 +197,17 @@ class BaseCore {
197
197
  }
198
198
  }
199
199
  }
200
+ // Check if the action requires simple role verification.
201
+ // If roles are provided but user has no role or user's roles is not included in the allowed roles then return an error
202
+ if (Array.isArray(roles) && roles?.length) {
203
+ const userRoleId = this.getContext().roleId || '';
204
+ if (!userRoleId) {
205
+ return OpResult.fail(OP_RESULT_CODES.FORBIDDEN, [], 'User has not assigned role');
206
+ }
207
+ else if (!roles.includes(userRoleId)) {
208
+ return OpResult.fail(OP_RESULT_CODES.FORBIDDEN, [], 'User role does not allow this operation');
209
+ }
210
+ }
200
211
  let validatedItems = {};
201
212
  if (typeof validate === 'function') {
202
213
  this.measureTool.addCheckpoint('Validate parameters: start');
@@ -304,10 +304,7 @@ class BaseGateway {
304
304
  }
305
305
  const items = await query;
306
306
  const result = shouldUseCache ? await this.getMany(items.map((row) => row.id)) : items;
307
- console.log('=== list.result', result);
308
- const trasnformed = result.map((item) => this.transformOnOut(item));
309
- console.log('=== list.trasnformed', trasnformed);
310
- return result;
307
+ return result.map((item) => this.transformOnOut(item));
311
308
  }
312
309
  async create(args) {
313
310
  const objects = castArray(args);
@@ -10,15 +10,16 @@ class DataCache {
10
10
  redisClient;
11
11
  constructor(props) {
12
12
  const { loaderFn, keyPrefix, context, buildKey, redisClient, table } = props || {};
13
- this.config = {
13
+ const innerProps = {
14
14
  ...props,
15
15
  idField: props?.idField || FIELDS.ID,
16
16
  idFieldAs: props?.idFieldAs || FIELDS.ID,
17
17
  };
18
+ this.config = innerProps;
18
19
  this.redisClient = redisClient;
19
20
  this.buildKey = typeof buildKey === 'function' ? buildKey : defaultBuildKey;
20
21
  this.batchLoaderDefault = this.batchLoaderDefault.bind(this);
21
- const fn = typeof loaderFn === 'function' ? loaderFn : this.batchLoaderDefault(props);
22
+ const fn = typeof loaderFn === 'function' ? loaderFn : this.batchLoaderDefault(innerProps);
22
23
  const prefixToUse = context?.keyPrefix || keyPrefix || table;
23
24
  this.init(fn, prefixToUse, context);
24
25
  }
@@ -4,6 +4,7 @@ export interface CoreActionInterface {
4
4
  actionName?: string;
5
5
  doAuth?: boolean;
6
6
  accessRights?: any[];
7
+ roles?: string[];
7
8
  validate?(args: any, opt: BaseCoreActionsInterface): Promise<any[]> | any[];
8
9
  action(args?: any, opt?: any): any;
9
10
  hasTransaction: boolean;
@@ -9,18 +9,21 @@ const createRedisClient = (args) => {
9
9
  if (!redisHost) {
10
10
  return null;
11
11
  }
12
+ const baseSocketConfig = {
13
+ host: redisHost,
14
+ port: Number(redisPort),
15
+ family: 0,
16
+ connectTimeout: connectionTimeout != undefined ? connectionTimeout : 5000,
17
+ noDelay: true,
18
+ keepAlive: true,
19
+ keepAliveInitialDelay: pingInterval != undefined ? pingInterval : 5000,
20
+ reconnectStrategy: (retries) => Math.min(retries * 50, 500),
21
+ };
22
+ const socketConfig = redisSsl
23
+ ? { ...baseSocketConfig, tls: true, rejectUnauthorized: false }
24
+ : { ...baseSocketConfig, tls: false };
12
25
  const cfg = {
13
- socket: {
14
- host: redisHost,
15
- port: Number(redisPort),
16
- family: 0,
17
- connectTimeout: connectionTimeout != undefined ? connectionTimeout : 5000,
18
- noDelay: true,
19
- keepAlive: pingInterval != undefined ? pingInterval : 5000,
20
- tls: redisSsl,
21
- rejectUnauthorized: false,
22
- reconnectStrategy: (retries) => Math.min(retries * 50, 500),
23
- },
26
+ socket: socketConfig,
24
27
  password: redisPassword || undefined,
25
28
  };
26
29
  const redisClient = createClient(cfg);
@@ -39,16 +39,22 @@ export const createUserToken = (params, secret, opt) => {
39
39
  });
40
40
  return OpResult.ok({ token, fingerprint: params.fingerprint });
41
41
  };
42
+ function toNonEmptyArray(arr) {
43
+ if (!arr || arr.length === 0)
44
+ return undefined;
45
+ return arr;
46
+ }
42
47
  export const verifyUserToken = (token, secret, args) => {
43
48
  const { algorithms, audience, issuer, ignoreExpiration, ignoreNotBefore, subject, clockTolerance, maxAge, clockTimestamp, nonce, fingerprint, } = args || {};
44
49
  if (!args) {
45
50
  return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'Cannot verify user token as there are no parameters specified');
46
51
  }
47
52
  try {
53
+ const issuerToUse = issuer || defaultIssuer;
48
54
  const obj = jwt.verify(token, secret, {
49
55
  algorithms: algorithms || [defaultJwtAlgorithm],
50
- audience,
51
- issuer: issuer || defaultIssuer,
56
+ audience: typeof audience === 'string' ? audience : toNonEmptyArray(audience),
57
+ issuer: typeof issuerToUse === 'string' ? issuerToUse : toNonEmptyArray(issuerToUse),
52
58
  ignoreExpiration,
53
59
  ignoreNotBefore,
54
60
  subject,
@@ -4,6 +4,7 @@ export interface CoreActionInterface {
4
4
  actionName?: string;
5
5
  doAuth?: boolean;
6
6
  accessRights?: any[];
7
+ roles?: string[];
7
8
  validate?(args: any, opt: BaseCoreActionsInterface): Promise<any[]> | any[];
8
9
  action(args?: any, opt?: any): any;
9
10
  hasTransaction: boolean;
@@ -12,18 +12,21 @@ const createRedisClient = (args) => {
12
12
  if (!redisHost) {
13
13
  return null;
14
14
  }
15
+ const baseSocketConfig = {
16
+ host: redisHost,
17
+ port: Number(redisPort),
18
+ family: 0,
19
+ connectTimeout: connectionTimeout != undefined ? connectionTimeout : 5000,
20
+ noDelay: true,
21
+ keepAlive: true,
22
+ keepAliveInitialDelay: pingInterval != undefined ? pingInterval : 5000,
23
+ reconnectStrategy: (retries) => Math.min(retries * 50, 500),
24
+ };
25
+ const socketConfig = redisSsl
26
+ ? { ...baseSocketConfig, tls: true, rejectUnauthorized: false }
27
+ : { ...baseSocketConfig, tls: false };
15
28
  const cfg = {
16
- socket: {
17
- host: redisHost,
18
- port: Number(redisPort),
19
- family: 0,
20
- connectTimeout: connectionTimeout != undefined ? connectionTimeout : 5000,
21
- noDelay: true,
22
- keepAlive: pingInterval != undefined ? pingInterval : 5000,
23
- tls: redisSsl,
24
- rejectUnauthorized: false,
25
- reconnectStrategy: (retries) => Math.min(retries * 50, 500),
26
- },
29
+ socket: socketConfig,
27
30
  password: redisPassword || undefined,
28
31
  };
29
32
  const redisClient = (0, redis_1.createClient)(cfg);
@@ -50,16 +50,22 @@ const createUserToken = (params, secret, opt) => {
50
50
  return api_helpers_1.OpResult.ok({ token, fingerprint: params.fingerprint });
51
51
  };
52
52
  exports.createUserToken = createUserToken;
53
+ function toNonEmptyArray(arr) {
54
+ if (!arr || arr.length === 0)
55
+ return undefined;
56
+ return arr;
57
+ }
53
58
  const verifyUserToken = (token, secret, args) => {
54
59
  const { algorithms, audience, issuer, ignoreExpiration, ignoreNotBefore, subject, clockTolerance, maxAge, clockTimestamp, nonce, fingerprint, } = args || {};
55
60
  if (!args) {
56
61
  return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'Cannot verify user token as there are no parameters specified');
57
62
  }
58
63
  try {
64
+ const issuerToUse = issuer || defaultIssuer;
59
65
  const obj = jsonwebtoken_1.default.verify(token, secret, {
60
66
  algorithms: algorithms || [defaultJwtAlgorithm],
61
- audience,
62
- issuer: issuer || defaultIssuer,
67
+ audience: typeof audience === 'string' ? audience : toNonEmptyArray(audience),
68
+ issuer: typeof issuerToUse === 'string' ? issuerToUse : toNonEmptyArray(issuerToUse),
63
69
  ignoreExpiration,
64
70
  ignoreNotBefore,
65
71
  subject,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sdflc/backend-helpers",
3
- "version": "1.0.105",
3
+ "version": "1.0.107",
4
4
  "description": "Set of helper functions and classes to simplify building backend apps within @sdflc ecosystem",
5
5
  "type": "commonjs",
6
6
  "exports": {
@@ -31,48 +31,48 @@
31
31
  "author": "Sergey Demidenko",
32
32
  "license": "ISC",
33
33
  "devDependencies": {
34
- "@types/bcrypt": "^5.0.2",
34
+ "@types/bcrypt": "^6.0.0",
35
35
  "@types/bluebird": "^3.5.42",
36
36
  "@types/check-types": "^11.2.2",
37
- "@types/dotenv-safe": "^8.1.6",
37
+ "@types/dotenv-safe": "^9.1.0",
38
38
  "@types/is-uuid": "^1.0.2",
39
- "@types/jest": "^29.5.14",
40
- "@types/jsonwebtoken": "^9.0.8",
41
- "@types/lodash": "^4.17.15",
42
- "@types/node": "^22.13.4",
39
+ "@types/jest": "^30.0.0",
40
+ "@types/jsonwebtoken": "^9.0.10",
41
+ "@types/lodash": "^4.17.21",
42
+ "@types/node": "^25.0.0",
43
43
  "@types/uuid": "^10.0.0",
44
- "@typescript-eslint/eslint-plugin": "^8.30.1",
45
- "@typescript-eslint/parser": "^8.30.1",
46
- "eslint": "^9.20.1",
47
- "eslint-config-prettier": "^10.1.2",
48
- "eslint-plugin-jest": "^28.11.0",
49
- "eslint-plugin-prettier": "^5.2.6",
44
+ "@typescript-eslint/eslint-plugin": "^8.49.0",
45
+ "@typescript-eslint/parser": "^8.49.0",
46
+ "eslint": "^9.39.1",
47
+ "eslint-config-prettier": "^10.1.8",
48
+ "eslint-plugin-jest": "^29.2.1",
49
+ "eslint-plugin-prettier": "^5.5.4",
50
50
  "husky": "^9.1.7",
51
- "jest": "^29.7.0",
52
- "prettier": "^3.5.3",
53
- "rimraf": "^6.0.1",
51
+ "jest": "^30.2.0",
52
+ "prettier": "^3.7.4",
53
+ "rimraf": "^6.1.2",
54
54
  "run-script-os": "^1.1.6",
55
- "ts-jest": "^29.3.2",
55
+ "ts-jest": "^29.4.6",
56
56
  "ts-node": "^10.9.2",
57
- "typescript": "^5.8.3"
57
+ "typescript": "^5.9.3"
58
58
  },
59
59
  "dependencies": {
60
60
  "@sdflc/api-helpers": "^1.1.13",
61
61
  "@sdflc/utils": "^1.0.24",
62
- "bcrypt": "^5.1.1",
62
+ "bcrypt": "^6.0.0",
63
63
  "bluebird": "^3.7.2",
64
64
  "check-types": "^11.2.3",
65
65
  "checkit": "^0.7.0",
66
66
  "dataloader": "^2.2.3",
67
- "dayjs": "^1.11.13",
67
+ "dayjs": "^1.11.19",
68
68
  "dotenv-safe": "^9.1.0",
69
69
  "is-uuid": "^1.0.2",
70
- "json-stable-stringify": "^1.2.1",
71
- "jsonwebtoken": "^9.0.2",
70
+ "json-stable-stringify": "^1.3.0",
71
+ "jsonwebtoken": "^9.0.3",
72
72
  "knex": "^3.1.0",
73
73
  "lodash": "^4.17.21",
74
- "pg": "^8.14.1",
75
- "redis": "^4.7.0",
76
- "uuid": "^11.1.0"
74
+ "pg": "^8.16.3",
75
+ "redis": "^5.10.0",
76
+ "uuid": "^13.0.0"
77
77
  }
78
78
  }