@friggframework/core 2.0.0--canary.397.e634da9.0 → 2.0.0--canary.398.ad248a6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/README.md +50 -931
  2. package/core/create-handler.js +0 -1
  3. package/database/models/WebsocketConnection.js +5 -0
  4. package/handlers/app-handler-helpers.js +3 -0
  5. package/handlers/backend-utils.js +44 -42
  6. package/handlers/routers/auth.js +14 -3
  7. package/handlers/routers/integration-defined-routers.js +5 -8
  8. package/handlers/routers/middleware/loadUser.js +15 -0
  9. package/handlers/routers/middleware/requireLoggedInUser.js +12 -0
  10. package/handlers/routers/user.js +5 -25
  11. package/handlers/workers/integration-defined-workers.js +3 -6
  12. package/index.js +16 -1
  13. package/integrations/create-frigg-backend.js +31 -0
  14. package/integrations/index.js +5 -0
  15. package/integrations/integration-base.js +46 -142
  16. package/integrations/integration-factory.js +251 -0
  17. package/integrations/integration-router.js +178 -301
  18. package/integrations/integration-user.js +144 -0
  19. package/integrations/options.js +1 -1
  20. package/integrations/test/integration-base.test.js +144 -0
  21. package/module-plugin/auther.js +393 -0
  22. package/module-plugin/entity-manager.js +70 -0
  23. package/{modules → module-plugin}/index.js +8 -0
  24. package/module-plugin/manager.js +169 -0
  25. package/module-plugin/module-factory.js +61 -0
  26. package/{modules → module-plugin}/test/mock-api/api.js +3 -8
  27. package/{modules → module-plugin}/test/mock-api/definition.js +8 -12
  28. package/package.json +5 -5
  29. package/syncs/sync.js +1 -0
  30. package/types/integrations/index.d.ts +6 -2
  31. package/types/module-plugin/index.d.ts +56 -4
  32. package/types/syncs/index.d.ts +2 -0
  33. package/credential/credential-repository.js +0 -42
  34. package/credential/use-cases/get-credential-for-user.js +0 -21
  35. package/credential/use-cases/update-authentication-status.js +0 -15
  36. package/handlers/app-definition-loader.js +0 -38
  37. package/integrations/integration-repository.js +0 -80
  38. package/integrations/integration.js +0 -246
  39. package/integrations/tests/doubles/dummy-integration-class.js +0 -90
  40. package/integrations/tests/doubles/test-integration-repository.js +0 -89
  41. package/integrations/tests/use-cases/create-integration.test.js +0 -124
  42. package/integrations/tests/use-cases/delete-integration-for-user.test.js +0 -143
  43. package/integrations/tests/use-cases/get-integration-for-user.test.js +0 -143
  44. package/integrations/tests/use-cases/get-integration-instance.test.js +0 -169
  45. package/integrations/tests/use-cases/get-integrations-for-user.test.js +0 -169
  46. package/integrations/tests/use-cases/get-possible-integrations.test.js +0 -188
  47. package/integrations/tests/use-cases/update-integration-messages.test.js +0 -142
  48. package/integrations/tests/use-cases/update-integration-status.test.js +0 -103
  49. package/integrations/tests/use-cases/update-integration.test.js +0 -134
  50. package/integrations/use-cases/create-integration.js +0 -71
  51. package/integrations/use-cases/delete-integration-for-user.js +0 -72
  52. package/integrations/use-cases/get-integration-for-user.js +0 -78
  53. package/integrations/use-cases/get-integration-instance-by-definition.js +0 -67
  54. package/integrations/use-cases/get-integration-instance.js +0 -82
  55. package/integrations/use-cases/get-integrations-for-user.js +0 -76
  56. package/integrations/use-cases/get-possible-integrations.js +0 -27
  57. package/integrations/use-cases/index.js +0 -11
  58. package/integrations/use-cases/update-integration-messages.js +0 -31
  59. package/integrations/use-cases/update-integration-status.js +0 -28
  60. package/integrations/use-cases/update-integration.js +0 -91
  61. package/integrations/utils/map-integration-dto.js +0 -36
  62. package/modules/module-factory.js +0 -54
  63. package/modules/module-repository.js +0 -107
  64. package/modules/module.js +0 -221
  65. package/modules/tests/doubles/test-module-factory.js +0 -16
  66. package/modules/tests/doubles/test-module-repository.js +0 -19
  67. package/modules/use-cases/get-entities-for-user.js +0 -32
  68. package/modules/use-cases/get-entity-options-by-id.js +0 -58
  69. package/modules/use-cases/get-entity-options-by-type.js +0 -34
  70. package/modules/use-cases/get-module-instance-from-type.js +0 -31
  71. package/modules/use-cases/get-module.js +0 -56
  72. package/modules/use-cases/process-authorization-callback.js +0 -114
  73. package/modules/use-cases/refresh-entity-options.js +0 -58
  74. package/modules/use-cases/test-module-auth.js +0 -54
  75. package/modules/utils/map-module-dto.js +0 -18
  76. package/user/tests/doubles/test-user-repository.js +0 -72
  77. package/user/tests/use-cases/create-individual-user.test.js +0 -24
  78. package/user/tests/use-cases/create-organization-user.test.js +0 -28
  79. package/user/tests/use-cases/create-token-for-user-id.test.js +0 -19
  80. package/user/tests/use-cases/get-user-from-bearer-token.test.js +0 -64
  81. package/user/tests/use-cases/login-user.test.js +0 -140
  82. package/user/use-cases/create-individual-user.js +0 -61
  83. package/user/use-cases/create-organization-user.js +0 -47
  84. package/user/use-cases/create-token-for-user-id.js +0 -30
  85. package/user/use-cases/get-user-from-bearer-token.js +0 -77
  86. package/user/use-cases/login-user.js +0 -122
  87. package/user/user-repository.js +0 -62
  88. package/user/user.js +0 -77
  89. /package/{modules → module-plugin}/ModuleConstants.js +0 -0
  90. /package/{modules → module-plugin}/credential.js +0 -0
  91. /package/{modules → module-plugin}/entity.js +0 -0
  92. /package/{modules → module-plugin}/requester/api-key.js +0 -0
  93. /package/{modules → module-plugin}/requester/basic.js +0 -0
  94. /package/{modules → module-plugin}/requester/oauth-2.js +0 -0
  95. /package/{modules → module-plugin}/requester/requester.js +0 -0
  96. /package/{modules → module-plugin}/requester/requester.test.js +0 -0
  97. /package/{modules → module-plugin}/test/auther.test.js +0 -0
  98. /package/{modules → module-plugin}/test/mock-api/mocks/hubspot.js +0 -0
@@ -1,107 +0,0 @@
1
- const { Entity } = require('./entity');
2
-
3
- class ModuleRepository {
4
- async findEntityById(entityId) {
5
- const entity = await Entity.findById(entityId, undefined, { lean: true }).populate('credential');
6
- if (!entity) {
7
- throw new Error(`Entity ${entityId} not found`);
8
- }
9
-
10
- return {
11
- id: entity._id,
12
- accountId: entity.accountId,
13
- credential: entity.credential,
14
- userId: entity.user.toString(),
15
- name: entity.name,
16
- externalId: entity.externalId,
17
- type: entity.__t,
18
- moduleName: entity.moduleName,
19
- };
20
- }
21
-
22
- async findEntitiesByUserId(userId) {
23
- const entitiesRecords = await Entity.find(
24
- { user: userId },
25
- '',
26
- { lean: true }
27
- ).populate('credential');
28
-
29
- return entitiesRecords.map(e => ({
30
- id: e._id.toString(),
31
- accountId: e.accountId,
32
- credential: e.credential,
33
- userId: e.user.toString(),
34
- name: e.name,
35
- externalId: e.externalId,
36
- type: e.__t,
37
- moduleName: e.moduleName,
38
- }));
39
- }
40
-
41
- async findEntitiesByIds(entitiesIds) {
42
- const entitiesRecords = await Entity.find(
43
- { _id: { $in: entitiesIds } },
44
- '',
45
- { lean: true }
46
- ).populate('credential');
47
-
48
- return entitiesRecords.map(e => ({
49
- id: e._id.toString(),
50
- accountId: e.accountId,
51
- credential: e.credential,
52
- userId: e.user.toString(),
53
- name: e.name,
54
- externalId: e.externalId,
55
- type: e.__t,
56
- moduleName: e.moduleName,
57
- }));
58
- }
59
-
60
- /**
61
- * Remove the credential reference from an Entity document without loading a full Mongoose instance.
62
- * Useful when a credential has been revoked/deleted (e.g. via Module.deauthorize).
63
- * @param {string} entityId
64
- * @returns {Promise<import('mongoose').UpdateWriteOpResult>}
65
- */
66
- async unsetCredential(entityId) {
67
- const result = await Entity.updateOne({ _id: entityId }, { $unset: { credential: "" } });
68
- return result.acknowledged;
69
- }
70
-
71
- async findEntity(filter) {
72
- const entity = await Entity.findOne(filter, undefined, { lean: true }).populate('credential');
73
- if (!entity) {
74
- return null;
75
- }
76
-
77
- return {
78
- id: entity._id.toString(),
79
- accountId: entity.accountId,
80
- credential: entity.credential,
81
- userId: entity.user.toString(),
82
- name: entity.name,
83
- externalId: entity.externalId,
84
- type: entity.__t,
85
- moduleName: entity.moduleName,
86
- };
87
- }
88
-
89
- async createEntity(entityData) {
90
- const entity = await Entity.create(entityData);
91
- await entity.populate('credential');
92
-
93
- return {
94
- id: entity._id.toString(),
95
- accountId: entity.accountId,
96
- credential: entity.credential,
97
- userId: entity.user.toString(),
98
- name: entity.name,
99
- externalId: entity.externalId,
100
- type: entity.__t,
101
- moduleName: entity.moduleName,
102
- };
103
- }
104
-
105
- }
106
-
107
- module.exports = { ModuleRepository };
package/modules/module.js DELETED
@@ -1,221 +0,0 @@
1
- const { Delegate } = require('../core');
2
- const _ = require('lodash');
3
- const { flushDebugLog } = require('../logs');
4
- const { ModuleConstants } = require('./ModuleConstants');
5
-
6
- // todo: this class should be a Domain class, and the Delegate function is preventing us from
7
- // doing that, we probably have to get rid of the Delegate class as well as the event based
8
- // calls since they go against the Domain Driven Design principles (eg. a domain class should not call repository methods or use cases)
9
- class Module extends Delegate {
10
-
11
- //todo: entity should be replaced with actual entity properties
12
- /**
13
- *
14
- * @param {Object} params
15
- * @param {Object} params.definition The definition of the Api Module
16
- * @param {string} params.userId The user id
17
- * @param {Object} params.entity The entity record from the database
18
- */
19
- constructor({ definition, userId = null, entity: entityObj = null }) {
20
- super({ definition, userId, entity: entityObj });
21
-
22
- this.validateDefinition(definition);
23
-
24
- this.userId = userId;
25
- this.entity = entityObj;
26
- this.credential = entityObj?.credential;
27
- this.definition = definition;
28
- this.name = this.definition.moduleName;
29
- this.modelName = this.definition.modelName;
30
- this.apiClass = this.definition.API;
31
-
32
- // Repository used for persistence operations related to credentials.
33
- const { CredentialRepository } = require('../credential/credential-repository');
34
- this.credentialRepository = new CredentialRepository();
35
-
36
- // Repository responsible for entity persistence actions
37
- const { ModuleRepository } = require('./module-repository');
38
- this.moduleRepository = new ModuleRepository();
39
-
40
- Object.assign(this, this.definition.requiredAuthMethods);
41
-
42
- const apiParams = {
43
- ...this.definition.env,
44
- delegate: this,
45
- ...this.apiParamsFromCredential(this.credential),
46
- ...this.apiParamsFromEntity(this.entity),
47
- };
48
- this.api = new this.apiClass(apiParams);
49
- }
50
-
51
- getName() {
52
- return this.name;
53
- }
54
-
55
- getEntityOptions() {
56
- return this.definition.getEntityOptions()
57
- }
58
-
59
- async refreshEntityOptions(options) {
60
- await this.definition.refreshEntityOptions(options);
61
- return this.getEntityOptions();
62
- }
63
-
64
- apiParamsFromCredential(credential) {
65
- return _.pick(credential, ...this.apiPropertiesToPersist?.credential);
66
- }
67
-
68
- apiParamsFromEntity(entity) {
69
- return _.pick(entity, ...this.apiPropertiesToPersist?.entity);
70
- }
71
-
72
- async validateAuthorizationRequirements() {
73
- const requirements = await this.getAuthorizationRequirements();
74
- let valid = true;
75
- if (
76
- ['oauth1', 'oauth2'].includes(requirements.type) &&
77
- !requirements.url
78
- ) {
79
- valid = false;
80
- }
81
- return valid;
82
- }
83
-
84
- async getAuthorizationRequirements(params) {
85
- return this.api.getAuthorizationRequirements();
86
- }
87
-
88
- async testAuth() {
89
- let validAuth = false;
90
- try {
91
- if (await this.testAuthRequest(this.api)) validAuth = true;
92
- } catch (e) {
93
- flushDebugLog(e);
94
- }
95
- return validAuth;
96
- }
97
-
98
- async onTokenUpdate() {
99
- const credentialDetails = await this.getCredentialDetails(
100
- this.api,
101
- this.userId
102
- );
103
- Object.assign(
104
- credentialDetails.details,
105
- this.apiParamsFromCredential(this.api)
106
- );
107
- credentialDetails.details.auth_is_valid = true;
108
-
109
- const persisted = await this.credentialRepository.upsertCredential(credentialDetails);
110
- this.credential = persisted;
111
- }
112
-
113
- async receiveNotification(notifier, delegateString, object = null) {
114
- if (delegateString === this.api.DLGT_TOKEN_UPDATE) {
115
- await this.onTokenUpdate();
116
- } else if (delegateString === this.api.DLGT_TOKEN_DEAUTHORIZED) {
117
- await this.deauthorize();
118
- } else if (delegateString === this.api.DLGT_INVALID_AUTH) {
119
- await this.markCredentialsInvalid();
120
- }
121
- }
122
-
123
- async markCredentialsInvalid() {
124
- if (!this.credential) return;
125
-
126
- // Persist flag change through repository – works even when the
127
- // credential object is a plain JavaScript object (lean query).
128
- const credentialId = this.credential._id || this.credential.id;
129
- if (!credentialId) return;
130
-
131
- await this.credentialRepository.updateAuthenticationStatus(
132
- credentialId,
133
- false
134
- );
135
-
136
- // Keep the in-memory snapshot consistent so that callers can read the
137
- // updated state without another fetch.
138
- this.credential.auth_is_valid = false;
139
- }
140
-
141
- async deauthorize() {
142
- this.api = new this.apiClass();
143
-
144
- // Remove persisted credential (if any)
145
- if (this.entity?.credential) {
146
- const credentialId =
147
- this.entity.credential._id || this.entity.credential.id || this.entity.credential;
148
-
149
- // Delete credential via repository
150
- await this.credentialRepository.deleteCredentialById(credentialId);
151
-
152
- // Unset credential reference on the Entity document
153
- const entityId = this.entity._id || this.entity.id;
154
- if (entityId) {
155
- await this.moduleRepository.unsetCredential(entityId);
156
- }
157
-
158
- // Keep in-memory snapshot consistent
159
- this.entity.credential = undefined;
160
- }
161
- }
162
-
163
- // todo: check if all these props are still up to date
164
- validateDefinition(definition) {
165
- if (!definition) {
166
- throw new Error('Module definition is required');
167
- }
168
- if (!definition.moduleName) {
169
- throw new Error('Module definition requires moduleName');
170
- }
171
- if (!definition.API) {
172
- throw new Error('Module definition requires API class');
173
- }
174
- if (!definition.requiredAuthMethods) {
175
- throw new Error('Module definition requires requiredAuthMethods');
176
- } else {
177
- if (
178
- definition.API.requesterType ===
179
- ModuleConstants.authType.oauth2 &&
180
- !definition.requiredAuthMethods.getToken
181
- ) {
182
- throw new Error(
183
- 'Module definition requires requiredAuthMethods.getToken'
184
- );
185
- }
186
- if (!definition.requiredAuthMethods.getEntityDetails) {
187
- throw new Error(
188
- 'Module definition requires requiredAuthMethods.getEntityDetails'
189
- );
190
- }
191
- if (!definition.requiredAuthMethods.getCredentialDetails) {
192
- throw new Error(
193
- 'Module definition requires requiredAuthMethods.getCredentialDetails'
194
- );
195
- }
196
- if (!definition.requiredAuthMethods.apiPropertiesToPersist) {
197
- throw new Error(
198
- 'Module definition requires requiredAuthMethods.apiPropertiesToPersist'
199
- );
200
- } else if (definition.Credential) {
201
- for (const prop of definition.requiredAuthMethods
202
- .apiPropertiesToPersist?.credential) {
203
- if (
204
- !definition.Credential.schema.paths.hasOwnProperty(prop)
205
- ) {
206
- throw new Error(
207
- `Module definition requires Credential schema to have property ${prop}`
208
- );
209
- }
210
- }
211
- }
212
- if (!definition.requiredAuthMethods.testAuthRequest) {
213
- throw new Error(
214
- 'Module definition requires requiredAuthMethods.testAuth'
215
- );
216
- }
217
- }
218
- }
219
- }
220
-
221
- module.exports = { Module };
@@ -1,16 +0,0 @@
1
- class TestModuleFactory {
2
- constructor() { }
3
-
4
- async getModuleInstance(entityId, userId) {
5
- // return minimal stub module with getName and api property
6
- return {
7
- getName() { return 'stubModule'; },
8
- api: {},
9
- entityId,
10
- userId,
11
- testAuth: async () => true,
12
- };
13
- }
14
- }
15
-
16
- module.exports = { TestModuleFactory };
@@ -1,19 +0,0 @@
1
- class TestModuleRepository {
2
- constructor() {
3
- this.entities = new Map();
4
- }
5
-
6
- addEntity(entity) {
7
- this.entities.set(entity.id, entity);
8
- }
9
-
10
- async findEntityById(id) {
11
- return this.entities.get(id);
12
- }
13
-
14
- async findEntitiesByIds(ids) {
15
- return ids.map((id) => this.entities.get(id));
16
- }
17
- }
18
-
19
- module.exports = { TestModuleRepository };
@@ -1,32 +0,0 @@
1
- const { Module } = require('../module');
2
- const { mapModuleClassToModuleDTO } = require('../utils/map-module-dto');
3
-
4
- class GetEntitiesForUser {
5
- constructor({ moduleRepository, moduleDefinitions }) {
6
- this.moduleRepository = moduleRepository;
7
-
8
- this.definitionMap = new Map();
9
- for (const definition of moduleDefinitions) {
10
- this.definitionMap.set(definition.modelName, definition);
11
- }
12
- }
13
-
14
- async execute(userId) {
15
- const entities = await this.moduleRepository.findEntitiesByUserId(
16
- userId
17
- );
18
-
19
- return entities.map((entity) => {
20
- const definition = this.definitionMap.get(entity.moduleName);
21
-
22
- const moduleInstance = new Module({
23
- userId,
24
- definition: definition,
25
- entity: entity,
26
- });
27
- return mapModuleClassToModuleDTO(moduleInstance);
28
- });
29
- }
30
- }
31
-
32
- module.exports = { GetEntitiesForUser };
@@ -1,58 +0,0 @@
1
- const { Module } = require('../module');
2
-
3
- class GetEntityOptionsById {
4
- /**
5
- * @param {Object} params
6
- * @param {import('../module-repository').ModuleRepository} params.moduleRepository
7
- * @param {} params.moduleDefinitions
8
- */
9
- constructor({ moduleRepository, moduleDefinitions }) {
10
- this.moduleRepository = moduleRepository;
11
- this.moduleDefinitions = moduleDefinitions;
12
- }
13
-
14
- /**
15
- * Retrieve a Module instance for a given user and entity/module type.
16
- * @param {string} userId
17
- * @param {string} entityId
18
- */
19
- async execute(entityId, userId) {
20
- const entity = await this.moduleRepository.findEntityById(
21
- entityId,
22
- userId
23
- );
24
-
25
- if (!entity) {
26
- throw new Error(`Entity ${entityId} not found`);
27
- }
28
-
29
- if (entity.userId !== userId) {
30
- throw new Error(
31
- `Entity ${entityId} does not belong to user ${userId}`
32
- );
33
- }
34
-
35
- const entityType = entity.type;
36
- const moduleDefinition = this.moduleDefinitions.find((def) => {
37
- const modelName = Module.getEntityModelFromDefinition(def).modelName;
38
- return entityType === modelName;
39
- });
40
-
41
- if (!moduleDefinition) {
42
- throw new Error(
43
- `Module definition not found for entity type: ${entityType}`
44
- );
45
- }
46
-
47
- const module = new Module({
48
- userId,
49
- entity,
50
- definition: moduleDefinition,
51
- });
52
-
53
- const entityOptions = await module.getEntityOptions();
54
- return entityOptions;
55
- }
56
- }
57
-
58
- module.exports = { GetEntityOptionsById };
@@ -1,34 +0,0 @@
1
- const { Module } = require('../module');
2
-
3
- class GetEntityOptionsByType {
4
- /**
5
- * @param {Object} params
6
- * @param {} params.moduleDefinitions
7
- */
8
- constructor({ moduleDefinitions }) {
9
- this.moduleDefinitions = moduleDefinitions;
10
- }
11
-
12
- /**
13
- * Retrieve a Module instance for a given user and entity/module type.
14
- * @param {string} userId
15
- * @param {string} type – human-readable module/entity type (e.g. "Hubspot")
16
- */
17
- async execute(userId, type) {
18
- const moduleDefinition = this.moduleDefinitions.find(
19
- (def) => def.getName() === type
20
- );
21
- if (!moduleDefinition) {
22
- throw new Error(`Module definition not found for type: ${type}`);
23
- }
24
- const moduleInstance = new Module({
25
- userId,
26
- definition: moduleDefinition,
27
- });
28
-
29
- const entityOptions = await moduleInstance.getEntityOptions();
30
- return entityOptions;
31
- }
32
- }
33
-
34
- module.exports = { GetEntityOptionsByType };
@@ -1,31 +0,0 @@
1
- const { Module } = require('../module');
2
-
3
- class GetModuleInstanceFromType {
4
- /**
5
- * @param {Object} params
6
- * @param {} params.moduleDefinitions
7
- */
8
- constructor({ moduleDefinitions }) {
9
- this.moduleDefinitions = moduleDefinitions;
10
- }
11
-
12
- /**
13
- * Retrieve a Module instance for a given user and entity/module type.
14
- * @param {string} userId
15
- * @param {string} type – human-readable module/entity type (e.g. "Hubspot")
16
- */
17
- async execute(userId, type) {
18
- const moduleDefinition = this.moduleDefinitions.find(
19
- (def) => def.getName() === type
20
- );
21
- if (!moduleDefinition) {
22
- throw new Error(`Module definition not found for type: ${type}`);
23
- }
24
- return new Module({
25
- userId,
26
- definition: moduleDefinition,
27
- });
28
- }
29
- }
30
-
31
- module.exports = { GetModuleInstanceFromType };
@@ -1,56 +0,0 @@
1
- const { Module } = require('../module');
2
-
3
- class GetModule {
4
- constructor({ moduleRepository, moduleDefinitions }) {
5
- this.moduleRepository = moduleRepository;
6
- this.moduleDefinitions = moduleDefinitions;
7
- }
8
-
9
- async execute(entityId, userId) {
10
- const entity = await this.moduleRepository.findEntityById(
11
- entityId,
12
- userId
13
- );
14
-
15
- if (!entity) {
16
- throw new Error(`Entity ${entityId} not found`);
17
- }
18
-
19
- if (entity.userId !== userId) {
20
- throw new Error(
21
- `Entity ${entityId} does not belong to user ${userId}`
22
- );
23
- }
24
-
25
- const entityType = entity.type;
26
- const moduleDefinition = this.moduleDefinitions.find((def) => {
27
- const modelName = Module.getEntityModelFromDefinition(def).modelName;
28
- return entityType === modelName;
29
- });
30
-
31
- if (!moduleDefinition) {
32
- throw new Error(
33
- `Module definition not found for entity type: ${entityType}`
34
- );
35
- }
36
-
37
- const module = new Module({
38
- userId,
39
- entity,
40
- definition: moduleDefinition,
41
- });
42
-
43
- // todo: this properties should be methods in the Module class
44
- return {
45
- id: module.entity.id,
46
- name: module.entity.name,
47
- type: module.entity.moduleName,
48
- moduleName: module.entity.moduleName,
49
- credential: module.credential,
50
- externalId: module.entity.externalId,
51
- userId: module.entity.user.toString(),
52
- }
53
- }
54
- }
55
-
56
- module.exports = { GetModule };
@@ -1,114 +0,0 @@
1
- const { Module } = require('../module');
2
- const { ModuleConstants } = require('../ModuleConstants');
3
-
4
- class ProcessAuthorizationCallback {
5
- /**
6
- * @param {Object} params - Configuration parameters.
7
- * @param {import('../module-repository').ModuleRepository} params.moduleRepository - Repository for module data operations.
8
- * @param {import('../../credential/credential-repository').CredentialRepository} params.credentialRepository - Repository for credential data operations.
9
- * @param {Array<Object>} params.moduleDefinitions - Array of module definitions.
10
- */
11
- constructor({ moduleRepository, credentialRepository, moduleDefinitions }) {
12
- this.moduleRepository = moduleRepository;
13
- this.credentialRepository = credentialRepository;
14
- this.moduleDefinitions = moduleDefinitions;
15
- }
16
-
17
- async execute(userId, entityType, params, credentialId = null) {
18
- const moduleDefinition = this.moduleDefinitions.find((def) => {
19
- return entityType === def.moduleName;
20
- });
21
-
22
- if (!moduleDefinition) {
23
- throw new Error(
24
- `Module definition not found for entity type: ${entityType}`
25
- );
26
- }
27
-
28
- let credential = null;
29
- let entity = null;
30
-
31
- if (credentialId) {
32
- credential = await this.credentialRepository.findCredentialById(credentialId);
33
- if (!credential) {
34
- throw new Error(`Credential ${credentialId} not found`);
35
- }
36
- }
37
-
38
- const module = new Module({
39
- userId,
40
- entity,
41
- definition: moduleDefinition,
42
- });
43
-
44
- let tokenResponse;
45
- if (module.apiClass.requesterType === ModuleConstants.authType.oauth2) {
46
- tokenResponse = await moduleDefinition.requiredAuthMethods.getToken(module.api, params);
47
- } else {
48
- tokenResponse = await moduleDefinition.requiredAuthMethods.setAuthParams(module.api, params);
49
- await this.onTokenUpdate(module, moduleDefinition, userId);
50
- }
51
-
52
- const authRes = await module.testAuth();
53
- if (!authRes) {
54
- throw new Error('Authorization failed');
55
- }
56
-
57
- const entityDetails = await moduleDefinition.requiredAuthMethods.getEntityDetails(
58
- module.api,
59
- params,
60
- tokenResponse,
61
- userId
62
- );
63
-
64
- Object.assign(
65
- entityDetails.details,
66
- module.apiParamsFromEntity(module.api)
67
- );
68
-
69
- const persistedEntity = await this.findOrCreateEntity(entityDetails, entityType);
70
-
71
- return {
72
- credential_id: module.credential.id,
73
- entity_id: persistedEntity.id,
74
- type: module.getName(),
75
- };
76
- }
77
-
78
- async onTokenUpdate(module, moduleDefinition, userId) {
79
- const credentialDetails = await moduleDefinition.requiredAuthMethods.getCredentialDetails(
80
- module.api,
81
- userId
82
- );
83
-
84
- Object.assign(
85
- credentialDetails.details,
86
- module.apiParamsFromCredential(module.api)
87
- );
88
- credentialDetails.details.auth_is_valid = true;
89
-
90
- await this.credentialRepository.upsertCredential(credentialDetails);
91
- }
92
-
93
- async findOrCreateEntity(entityDetails, entityType) {
94
- const { identifiers, details } = entityDetails;
95
-
96
- const existingEntity = await this.moduleRepository.findEntity({
97
- externalId: identifiers.externalId,
98
- user: identifiers.user,
99
- __t: entityType
100
- });
101
-
102
- if (existingEntity) {
103
- return existingEntity;
104
- }
105
-
106
- return await this.moduleRepository.createEntity({
107
- ...identifiers,
108
- ...details,
109
- __t: entityType
110
- });
111
- }
112
- }
113
-
114
- module.exports = { ProcessAuthorizationCallback };