@tsed/formio 8.11.0 → 8.11.2-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (154) hide show
  1. package/lib/esm/FormioModule.js +0 -1
  2. package/lib/esm/builder/FormioMapper.js +0 -1
  3. package/lib/esm/components/AlterActions.js +0 -1
  4. package/lib/esm/components/AlterAudit.js +0 -1
  5. package/lib/esm/components/AlterHost.js +0 -1
  6. package/lib/esm/components/AlterLog.js +0 -1
  7. package/lib/esm/components/AlterSkip.js +0 -1
  8. package/lib/esm/components/AlterTemplateExportSteps.js +0 -1
  9. package/lib/esm/components/AlterTemplateImportSteps.js +0 -1
  10. package/lib/esm/decorators/action.js +0 -1
  11. package/lib/esm/decorators/actionCtx.js +0 -1
  12. package/lib/esm/decorators/alter.js +0 -1
  13. package/lib/esm/decorators/on.js +0 -1
  14. package/lib/esm/decorators/useFormioAuth.js +0 -1
  15. package/lib/esm/domain/AlterHook.js +0 -1
  16. package/lib/esm/domain/Formio.js +0 -1
  17. package/lib/esm/domain/FormioAction.js +0 -1
  18. package/lib/esm/domain/FormioActionsIndex.js +0 -1
  19. package/lib/esm/domain/FormioAuth.js +0 -1
  20. package/lib/esm/domain/FormioBaseModel.js +0 -1
  21. package/lib/esm/domain/FormioConfig.js +0 -1
  22. package/lib/esm/domain/FormioCtxMapper.js +0 -1
  23. package/lib/esm/domain/FormioDecodedToken.js +0 -1
  24. package/lib/esm/domain/FormioErrors.js +0 -1
  25. package/lib/esm/domain/FormioHooks.js +0 -1
  26. package/lib/esm/domain/FormioJs.js +0 -1
  27. package/lib/esm/domain/FormioModels.js +0 -1
  28. package/lib/esm/domain/FormioRouter.js +0 -1
  29. package/lib/esm/domain/FormioSettings.js +0 -1
  30. package/lib/esm/domain/FormioTemplate.js +0 -1
  31. package/lib/esm/domain/FormioTemplateUtil.js +0 -1
  32. package/lib/esm/domain/FormioUpdate.js +0 -1
  33. package/lib/esm/domain/FormioUtils.js +0 -1
  34. package/lib/esm/domain/OnHook.js +0 -1
  35. package/lib/esm/domain/Resource.js +0 -1
  36. package/lib/esm/index.js +0 -1
  37. package/lib/esm/middlewares/FormioAuthMiddleware.js +0 -1
  38. package/lib/esm/services/FormioAuthService.js +0 -1
  39. package/lib/esm/services/FormioDatabase.js +0 -1
  40. package/lib/esm/services/FormioHooksService.js +0 -1
  41. package/lib/esm/services/FormioInstaller.js +0 -1
  42. package/lib/esm/services/FormioRepository.js +0 -1
  43. package/lib/esm/services/FormioService.js +0 -1
  44. package/lib/esm/utils/isMongoId.js +0 -1
  45. package/package.json +13 -10
  46. package/lib/esm/FormioModule.js.map +0 -1
  47. package/lib/esm/builder/FormioMapper.js.map +0 -1
  48. package/lib/esm/components/AlterActions.js.map +0 -1
  49. package/lib/esm/components/AlterAudit.js.map +0 -1
  50. package/lib/esm/components/AlterHost.js.map +0 -1
  51. package/lib/esm/components/AlterLog.js.map +0 -1
  52. package/lib/esm/components/AlterSkip.js.map +0 -1
  53. package/lib/esm/components/AlterTemplateExportSteps.js.map +0 -1
  54. package/lib/esm/components/AlterTemplateImportSteps.js.map +0 -1
  55. package/lib/esm/decorators/action.js.map +0 -1
  56. package/lib/esm/decorators/actionCtx.js.map +0 -1
  57. package/lib/esm/decorators/alter.js.map +0 -1
  58. package/lib/esm/decorators/on.js.map +0 -1
  59. package/lib/esm/decorators/useFormioAuth.js.map +0 -1
  60. package/lib/esm/domain/AlterHook.js.map +0 -1
  61. package/lib/esm/domain/Formio.js.map +0 -1
  62. package/lib/esm/domain/FormioAction.js.map +0 -1
  63. package/lib/esm/domain/FormioActionsIndex.js.map +0 -1
  64. package/lib/esm/domain/FormioAuth.js.map +0 -1
  65. package/lib/esm/domain/FormioBaseModel.js.map +0 -1
  66. package/lib/esm/domain/FormioConfig.js.map +0 -1
  67. package/lib/esm/domain/FormioCtxMapper.js.map +0 -1
  68. package/lib/esm/domain/FormioDecodedToken.js.map +0 -1
  69. package/lib/esm/domain/FormioErrors.js.map +0 -1
  70. package/lib/esm/domain/FormioHooks.js.map +0 -1
  71. package/lib/esm/domain/FormioJs.js.map +0 -1
  72. package/lib/esm/domain/FormioModels.js.map +0 -1
  73. package/lib/esm/domain/FormioRouter.js.map +0 -1
  74. package/lib/esm/domain/FormioSettings.js.map +0 -1
  75. package/lib/esm/domain/FormioTemplate.js.map +0 -1
  76. package/lib/esm/domain/FormioTemplateUtil.js.map +0 -1
  77. package/lib/esm/domain/FormioUpdate.js.map +0 -1
  78. package/lib/esm/domain/FormioUtils.js.map +0 -1
  79. package/lib/esm/domain/OnHook.js.map +0 -1
  80. package/lib/esm/domain/Resource.js.map +0 -1
  81. package/lib/esm/index.js.map +0 -1
  82. package/lib/esm/middlewares/FormioAuthMiddleware.js.map +0 -1
  83. package/lib/esm/services/FormioAuthService.js.map +0 -1
  84. package/lib/esm/services/FormioDatabase.js.map +0 -1
  85. package/lib/esm/services/FormioHooksService.js.map +0 -1
  86. package/lib/esm/services/FormioInstaller.js.map +0 -1
  87. package/lib/esm/services/FormioRepository.js.map +0 -1
  88. package/lib/esm/services/FormioService.js.map +0 -1
  89. package/lib/esm/utils/isMongoId.js.map +0 -1
  90. package/src/FormioModule.spec.ts +0 -113
  91. package/src/FormioModule.ts +0 -130
  92. package/src/builder/FormioMapper.spec.ts +0 -93
  93. package/src/builder/FormioMapper.ts +0 -71
  94. package/src/components/AlterActions.spec.ts +0 -376
  95. package/src/components/AlterActions.ts +0 -136
  96. package/src/components/AlterAudit.spec.ts +0 -19
  97. package/src/components/AlterAudit.ts +0 -12
  98. package/src/components/AlterHost.spec.ts +0 -20
  99. package/src/components/AlterHost.ts +0 -11
  100. package/src/components/AlterLog.spec.ts +0 -19
  101. package/src/components/AlterLog.ts +0 -12
  102. package/src/components/AlterSkip.spec.ts +0 -44
  103. package/src/components/AlterSkip.ts +0 -28
  104. package/src/components/AlterTemplateExportSteps.spec.ts +0 -99
  105. package/src/components/AlterTemplateExportSteps.ts +0 -58
  106. package/src/components/AlterTemplateImportSteps.spec.ts +0 -70
  107. package/src/components/AlterTemplateImportSteps.ts +0 -50
  108. package/src/decorators/action.ts +0 -20
  109. package/src/decorators/actionCtx.spec.ts +0 -25
  110. package/src/decorators/actionCtx.ts +0 -29
  111. package/src/decorators/alter.spec.ts +0 -16
  112. package/src/decorators/alter.ts +0 -19
  113. package/src/decorators/on.spec.ts +0 -16
  114. package/src/decorators/on.ts +0 -19
  115. package/src/decorators/useFormioAuth.spec.ts +0 -15
  116. package/src/decorators/useFormioAuth.ts +0 -12
  117. package/src/domain/AlterHook.ts +0 -3
  118. package/src/domain/Formio.ts +0 -122
  119. package/src/domain/FormioAction.ts +0 -30
  120. package/src/domain/FormioActionsIndex.ts +0 -19
  121. package/src/domain/FormioAuth.ts +0 -83
  122. package/src/domain/FormioBaseModel.ts +0 -14
  123. package/src/domain/FormioConfig.ts +0 -63
  124. package/src/domain/FormioCtxMapper.ts +0 -8
  125. package/src/domain/FormioDecodedToken.ts +0 -13
  126. package/src/domain/FormioErrors.ts +0 -53
  127. package/src/domain/FormioHooks.ts +0 -207
  128. package/src/domain/FormioJs.ts +0 -18
  129. package/src/domain/FormioModels.ts +0 -48
  130. package/src/domain/FormioRouter.ts +0 -10
  131. package/src/domain/FormioSettings.ts +0 -61
  132. package/src/domain/FormioTemplate.ts +0 -9
  133. package/src/domain/FormioTemplateUtil.ts +0 -15
  134. package/src/domain/FormioUpdate.ts +0 -23
  135. package/src/domain/FormioUtils.ts +0 -331
  136. package/src/domain/OnHook.ts +0 -3
  137. package/src/domain/Resource.ts +0 -21
  138. package/src/index.ts +0 -46
  139. package/src/middlewares/FormioAuthMiddleware.spec.ts +0 -61
  140. package/src/middlewares/FormioAuthMiddleware.ts +0 -34
  141. package/src/services/FormioAuthService.spec.ts +0 -396
  142. package/src/services/FormioAuthService.ts +0 -228
  143. package/src/services/FormioDatabase.spec.ts +0 -326
  144. package/src/services/FormioDatabase.ts +0 -165
  145. package/src/services/FormioHooksService.spec.ts +0 -156
  146. package/src/services/FormioHooksService.ts +0 -92
  147. package/src/services/FormioInstaller.spec.ts +0 -146
  148. package/src/services/FormioInstaller.ts +0 -46
  149. package/src/services/FormioRepository.spec.ts +0 -114
  150. package/src/services/FormioRepository.ts +0 -49
  151. package/src/services/FormioService.spec.ts +0 -368
  152. package/src/services/FormioService.ts +0 -134
  153. package/src/utils/isMongoId.ts +0 -3
  154. package/vitest.config.mts +0 -21
@@ -1,396 +0,0 @@
1
- import {catchAsyncError} from "@tsed/core";
2
- import {BadRequest} from "@tsed/exceptions";
3
- import {PlatformTest} from "@tsed/platform-http/testing";
4
-
5
- import {FormioAuthService} from "./FormioAuthService.js";
6
- import {FormioHooksService} from "./FormioHooksService.js";
7
- import {FormioService} from "./FormioService.js";
8
-
9
- function createSubmissionModelFixture(): any {
10
- return class {
11
- static findOne = vi.fn().mockReturnThis();
12
- static updateOne = vi.fn().mockResolvedValue({});
13
- static lean = vi.fn().mockReturnThis();
14
- static exec = vi.fn().mockReturnThis();
15
- save = vi.fn().mockReturnThis();
16
-
17
- constructor(public ctrOptions: any) {}
18
-
19
- get form(): string {
20
- return this.ctrOptions.form;
21
- }
22
-
23
- set form(form: string) {
24
- this.ctrOptions.form = form;
25
- }
26
-
27
- toObject() {
28
- return this.ctrOptions;
29
- }
30
- };
31
- }
32
-
33
- function createFormModelFixture(): any {
34
- return class {
35
- static findOne = vi.fn().mockReturnThis();
36
- static lean = vi.fn().mockReturnThis();
37
- static exec = vi.fn();
38
- };
39
- }
40
-
41
- function createRoleModelFixture(): any {
42
- return class {
43
- static find = vi.fn().mockReturnThis();
44
- static sort = vi.fn().mockReturnThis();
45
- static lean = vi.fn().mockReturnThis();
46
- static exec = vi.fn().mockResolvedValue({});
47
- };
48
- }
49
-
50
- async function createServiceFixture() {
51
- const formioService = {
52
- audit: vi.fn(),
53
- auth: {
54
- tempToken: vi.fn(),
55
- logout: vi.fn(),
56
- currentUser: vi.fn().mockImplementation((req, res, next) => next()),
57
- getToken: vi.fn().mockReturnValue("auth_token")
58
- },
59
- mongoose: {
60
- models: {
61
- submission: createSubmissionModelFixture(),
62
- form: createFormModelFixture(),
63
- role: createRoleModelFixture()
64
- }
65
- },
66
- util: {
67
- idToBson: vi.fn().mockImplementation((f) => f),
68
- errorCodes: {
69
- role: {EROLESLOAD: "EROLESLOAD"}
70
- }
71
- }
72
- };
73
-
74
- const formioHooksService = {
75
- alter: vi.fn().mockImplementation((event: string, value: any) => value),
76
- alterAsync: vi.fn().mockImplementation((event: string, value: any) => Promise.resolve(value))
77
- };
78
-
79
- const service = await PlatformTest.invoke<FormioAuthService>(FormioAuthService, [
80
- {
81
- token: FormioService,
82
- use: formioService
83
- },
84
- {
85
- token: FormioHooksService,
86
- use: formioHooksService
87
- }
88
- ]);
89
-
90
- return {service, formioService, formioHooksService};
91
- }
92
-
93
- describe("FormioAuthService", () => {
94
- beforeEach(() => PlatformTest.create());
95
- afterEach(PlatformTest.reset);
96
-
97
- describe("createUser()", () => {
98
- it("should create a user submission", async () => {
99
- const {service} = await createServiceFixture();
100
-
101
- const submission = await service.createUser({
102
- form: "formId",
103
- data: {
104
- fullname: "fullname"
105
- }
106
- });
107
-
108
- expect(submission.form).toEqual("formId");
109
- expect(submission.data).toEqual({
110
- fullname: "fullname"
111
- });
112
- });
113
- });
114
- describe("updateUser()", () => {
115
- it("should update a user submission", async () => {
116
- const {service, formioService} = await createServiceFixture();
117
-
118
- const result = await service.updateUser({
119
- _id: "id",
120
- form: "formId",
121
- data: {
122
- fullname: "fullname"
123
- }
124
- });
125
-
126
- expect(result).toEqual({
127
- _id: "id",
128
- form: "formId",
129
- data: {
130
- fullname: "fullname"
131
- }
132
- });
133
- expect(formioService.mongoose.models.submission.updateOne).toHaveBeenCalledWith(
134
- {_id: "id"},
135
- {$set: {_id: "id", data: {fullname: "fullname"}, form: "formId"}}
136
- );
137
- });
138
- });
139
- describe("getRoles()", () => {
140
- it("should return all formio roles", async () => {
141
- const {service, formioService} = await createServiceFixture();
142
-
143
- formioService.mongoose.models.role.exec.mockResolvedValue([{name: "administrator"}]);
144
-
145
- const roles = await service.getRoles({} as any);
146
-
147
- expect(roles).toEqual([{name: "administrator"}]);
148
- expect(formioService.mongoose.models.role.find).toHaveBeenCalledWith({deleted: {$eq: null}});
149
- expect(formioService.mongoose.models.role.sort).toHaveBeenCalledWith({title: 1});
150
- expect(formioService.mongoose.models.role.lean).toHaveBeenCalledWith();
151
- });
152
-
153
- it("should throw an error", async () => {
154
- const {service, formioService} = await createServiceFixture();
155
-
156
- vi.mocked(formioService.mongoose.models.role.exec).mockRejectedValue(new Error("test"));
157
-
158
- const error = await catchAsyncError(() => service.getRoles({} as any));
159
- expect(error).toBeInstanceOf(BadRequest);
160
- expect(error?.message).toEqual("EROLESLOAD");
161
- });
162
- });
163
- describe("updateUserRole()", () => {
164
- it("should update the role associated to the submission", async () => {
165
- const {service, formioService, formioHooksService} = await createServiceFixture();
166
- const submission = {
167
- _id: "submissionId",
168
- save: vi.fn()
169
- };
170
-
171
- formioService.mongoose.models.submission.exec = vi.fn().mockResolvedValue(submission);
172
-
173
- const user = await service.updateUserRole("submissionId", "roleId", {} as any);
174
-
175
- expect(formioHooksService.alter).toHaveBeenCalledWith("submissionQuery", {_id: "submissionId", deleted: {$eq: null}}, {});
176
- expect(formioService.mongoose.models.submission.findOne).toHaveBeenCalledWith({_id: "submissionId", deleted: {$eq: null}});
177
- expect(user.save).toHaveBeenCalledWith();
178
- expect(user.roles).toEqual(["roleId"]);
179
- });
180
-
181
- it("should update the role associated to the submission without save", async () => {
182
- const {service, formioService, formioHooksService} = await createServiceFixture();
183
- const submission = {
184
- _id: "submissionId"
185
- };
186
-
187
- formioService.mongoose.models.submission.exec = vi.fn().mockResolvedValue(submission);
188
-
189
- const user = await service.updateUserRole("submissionId", "roleId", {} as any);
190
-
191
- expect(formioHooksService.alter).toHaveBeenCalledWith("submissionQuery", {_id: "submissionId", deleted: {$eq: null}}, {});
192
- expect(formioService.mongoose.models.submission.findOne).toHaveBeenCalledWith({_id: "submissionId", deleted: {$eq: null}});
193
- expect(user.roles).toEqual(["roleId"]);
194
- });
195
- it("should throw an error when submission doesn't exists", async () => {
196
- const {service, formioService} = await createServiceFixture();
197
-
198
- formioService.mongoose.models.submission.exec = vi.fn().mockResolvedValue(null);
199
-
200
- const error = await catchAsyncError(() => service.updateUserRole("submissionId", "roleId", {} as any));
201
-
202
- expect(error).toBeInstanceOf(BadRequest);
203
- });
204
- });
205
- describe("setCurrentUser()", () => {
206
- it("should set current user", async () => {
207
- const {service} = await createServiceFixture();
208
- const ctx = PlatformTest.createRequestContext();
209
- ctx.getRequest().submission = {};
210
- const user = {
211
- _id: "id",
212
- data: {}
213
- };
214
-
215
- const token = {
216
- decoded: {
217
- form: {
218
- _id: "id"
219
- },
220
- user: {
221
- _id: "id"
222
- }
223
- },
224
- token: "token"
225
- };
226
-
227
- service.setCurrentUser(user as any, token, ctx);
228
-
229
- expect(ctx.getRequest().submission).toEqual({data: {}});
230
- expect(ctx.getRequest().user).toEqual({_id: "id", data: {}});
231
- expect(ctx.getRequest().token).toEqual({
232
- form: {
233
- _id: "id"
234
- },
235
- user: {
236
- _id: "id"
237
- }
238
- });
239
- expect(ctx.getResponse().token).toEqual("token");
240
- expect(ctx.getRequest()["x-jwt-token"]).toEqual("token");
241
- });
242
- });
243
- describe("generatePayloadToken()", () => {
244
- it("should return the payload token", async () => {
245
- const {service, formioService, formioHooksService} = await createServiceFixture();
246
- const ctx = PlatformTest.createRequestContext();
247
- const user = {
248
- _id: "id",
249
- form: "605f0d40fe971372e448bcad",
250
- data: {}
251
- };
252
- const form = {
253
- _id: "605f0d40fe971372e448bcad"
254
- };
255
-
256
- const payload = {
257
- user: {
258
- _id: user._id
259
- },
260
- form: {
261
- _id: form._id
262
- }
263
- };
264
-
265
- formioService.mongoose.models.form.exec.mockResolvedValue(form);
266
-
267
- const result = await service.generatePayloadToken(user as any, ctx);
268
-
269
- expect(result).toEqual({
270
- token: {
271
- decoded: payload,
272
- token: "auth_token"
273
- },
274
- user: {
275
- _id: "id",
276
- data: {},
277
- form: "605f0d40fe971372e448bcad"
278
- }
279
- });
280
- expect(formioHooksService.alter).toHaveBeenCalledWith("token", payload, form, ctx.getRequest());
281
- expect(formioHooksService.alter).toHaveBeenCalledWith("tokenDecode", payload, ctx.getRequest());
282
- expect(formioHooksService.alterAsync).toHaveBeenCalledWith("user", user);
283
- expect(formioHooksService.alterAsync).toHaveBeenCalledWith("login", user, ctx.getRequest());
284
- });
285
- it("should throw error when the getForm throw error", async () => {
286
- const {service, formioService} = await createServiceFixture();
287
- const ctx = PlatformTest.createRequestContext();
288
- const user = {
289
- _id: "id",
290
- form: "605f0d40fe971372e448bcad",
291
- data: {}
292
- };
293
-
294
- formioService.mongoose.models.form.exec.mockRejectedValue(new Error("message"));
295
-
296
- const error = await catchAsyncError(() => service.generatePayloadToken(user as any, ctx));
297
-
298
- expect(error?.name).toEqual("Error");
299
- expect(formioService.audit).toHaveBeenCalledWith(
300
- "EAUTH_USERFORM",
301
- {...ctx.request.raw, userId: user._id},
302
- "605f0d40fe971372e448bcad",
303
- error
304
- );
305
- });
306
- it("should throw error when the form isn't found", async () => {
307
- const {service, formioService} = await createServiceFixture();
308
- const ctx = PlatformTest.createRequestContext();
309
- const user = {
310
- _id: "id",
311
- form: "605f0d40fe971372e448bcad",
312
- data: {}
313
- };
314
-
315
- formioService.mongoose.models.form.exec.mockResolvedValue(null);
316
-
317
- const error = await catchAsyncError(() => service.generatePayloadToken(user as any, ctx));
318
-
319
- expect(error?.name).toEqual("NOT_FOUND");
320
- expect(formioService.audit).toHaveBeenCalledWith(
321
- "EAUTH_USERFORM",
322
- {...ctx.request.raw, userId: user._id},
323
- "605f0d40fe971372e448bcad",
324
- {
325
- message: "User form not found"
326
- }
327
- );
328
- });
329
- });
330
- describe("generateSession()", () => {
331
- it("should generate session", async () => {
332
- const {service, formioService} = await createServiceFixture();
333
- const ctx = PlatformTest.createRequestContext();
334
- const user = {
335
- _id: "id",
336
- form: "605f0d40fe971372e448bcad",
337
- data: {}
338
- };
339
-
340
- vi.spyOn(service, "setCurrentUser").mockReturnValue(undefined as any);
341
- vi.spyOn(service, "generatePayloadToken").mockResolvedValue({
342
- user,
343
- token: {
344
- token: "token"
345
- }
346
- } as any);
347
-
348
- await service.generateSession(user as any, ctx);
349
-
350
- expect(service.setCurrentUser).toHaveBeenCalledWith(
351
- user,
352
- {
353
- token: "token"
354
- },
355
- ctx
356
- );
357
- expect(service.setCurrentUser).toHaveBeenCalledWith(
358
- user,
359
- {
360
- token: "token"
361
- },
362
- ctx
363
- );
364
- expect(formioService.auth.currentUser).toHaveBeenCalledWith(ctx.getRequest(), ctx.getResponse(), expect.any(Function));
365
- });
366
- it("should throw an error when an action isn't permitted", async () => {
367
- const {service} = await createServiceFixture();
368
- const ctx = PlatformTest.createRequestContext();
369
- const user = {
370
- _id: "id",
371
- form: "605f0d40fe971372e448bcad",
372
- data: {}
373
- };
374
-
375
- vi.spyOn(service, "setCurrentUser").mockReturnValue(undefined as any);
376
- vi.spyOn(service, "generatePayloadToken").mockRejectedValue(new Error("Not found"));
377
-
378
- const error = await catchAsyncError(() => service.generateSession(user as any, ctx));
379
- expect(error?.message).toEqual("Not found");
380
- });
381
- });
382
- describe("tempToken()", () => {
383
- it("should return tempToken", async () => {
384
- const {service, formioService} = await createServiceFixture();
385
-
386
- expect(service.tempToken).toEqual(formioService.auth.tempToken);
387
- });
388
- });
389
- describe("logout()", () => {
390
- it("should return logout", async () => {
391
- const {service, formioService} = await createServiceFixture();
392
-
393
- expect(service.logout).toEqual(formioService.auth.logout);
394
- });
395
- });
396
- });
@@ -1,228 +0,0 @@
1
- import {promisify} from "node:util";
2
-
3
- import {isFunction} from "@tsed/core";
4
- import {Inject, Injectable} from "@tsed/di";
5
- import {BadRequest, NotFound, Unauthorized} from "@tsed/exceptions";
6
- import {PlatformContext, Req} from "@tsed/platform-http";
7
-
8
- import {FormioPayloadToken} from "../domain/FormioDecodedToken.js";
9
- import {FormioForm, FormioSubmission, WithID} from "../domain/FormioModels.js";
10
- import {FormioDatabase} from "./FormioDatabase.js";
11
- import {FormioHooksService} from "./FormioHooksService.js";
12
- import {FormioService} from "./FormioService.js";
13
-
14
- @Injectable()
15
- export class FormioAuthService {
16
- @Inject()
17
- formio: FormioService;
18
-
19
- @Inject()
20
- hooks: FormioHooksService;
21
-
22
- @Inject()
23
- db: FormioDatabase;
24
-
25
- get currentUser() {
26
- return promisify(this.formio.auth.currentUser);
27
- }
28
-
29
- get getToken() {
30
- return this.formio.auth.getToken;
31
- }
32
-
33
- get tempToken() {
34
- return this.formio.auth.tempToken;
35
- }
36
-
37
- get logout() {
38
- return this.formio.auth.logout;
39
- }
40
-
41
- setCurrentUser<User = any>(user: WithID<FormioSubmission<User>>, token: FormioPayloadToken, ctx: PlatformContext) {
42
- const request = ctx.getRequest();
43
- const response = ctx.getResponse();
44
-
45
- request.submission.data = user.data;
46
- request.user = user;
47
- request.token = token.decoded;
48
- response.token = token.token;
49
- request["x-jwt-token"] = token.token;
50
-
51
- return this;
52
- }
53
-
54
- /**
55
- * Generate the payload token for the session
56
- * @param user
57
- * @param ctx
58
- */
59
- async generatePayloadToken<User = any>(
60
- user: WithID<FormioSubmission<User>>,
61
- ctx: PlatformContext
62
- ): Promise<{user: WithID<FormioSubmission<User>>; token: FormioPayloadToken}> {
63
- const req = ctx.getRequest();
64
- const audit = this.formio.audit;
65
- let form: FormioForm | null;
66
-
67
- try {
68
- form = (await this.db.getForm(user.form)) as any;
69
- } catch (err) {
70
- audit(
71
- "EAUTH_USERFORM",
72
- {
73
- ...req,
74
- userId: user._id
75
- },
76
- user.form,
77
- err
78
- );
79
- throw err;
80
- }
81
-
82
- if (!form) {
83
- audit(
84
- "EAUTH_USERFORM",
85
- {
86
- ...req,
87
- userId: user._id
88
- },
89
- user.form,
90
- {message: "User form not found"}
91
- );
92
-
93
- throw new NotFound("User form not found.");
94
- }
95
-
96
- try {
97
- user = await this.hooks.alterAsync("user", user);
98
- } catch (err) {
99
- // istanbul ignore next
100
- ctx.logger.debug(err);
101
- }
102
-
103
- await this.hooks.alterAsync("login", user, req);
104
-
105
- // Allow anyone to hook and modify the token.
106
- const token = this.hooks.alter(
107
- "token",
108
- {
109
- user: {
110
- _id: user._id
111
- },
112
- form: {
113
- _id: form?._id
114
- }
115
- },
116
- form,
117
- req
118
- );
119
-
120
- const decoded = this.hooks.alter("tokenDecode", token, req);
121
-
122
- return {
123
- user,
124
- token: {
125
- token: this.getToken(token) as string,
126
- decoded
127
- }
128
- };
129
- }
130
-
131
- /**
132
- * Generate session from the given authenticated user.
133
- * @param user
134
- * @param ctx
135
- */
136
- async generateSession<User = any>(user: WithID<FormioSubmission<User>>, ctx: PlatformContext) {
137
- try {
138
- const {user: userSession, token} = await this.generatePayloadToken(user, ctx);
139
- this.setCurrentUser(userSession, token, ctx);
140
-
141
- await this.currentUser(ctx.getRequest(), ctx.getResponse());
142
- } catch (err) {
143
- ctx.logger.error({event: "Error on OAuthActions", error: err});
144
- throw new Unauthorized(err.message);
145
- }
146
- }
147
-
148
- /**
149
- * Retrieve roles
150
- * @param req
151
- */
152
- async getRoles(req?: Req) {
153
- try {
154
- const query = this.hooks.alter("roleQuery", {deleted: {$eq: null}}, req);
155
- return await this.db.roleModel.find(query).sort({title: 1}).lean().exec();
156
- } catch (err) {
157
- throw new BadRequest(this.formio.util.errorCodes.role.EROLESLOAD);
158
- }
159
- }
160
-
161
- /**
162
- * Update the role of the current user submission
163
- * @param _id
164
- * @param role
165
- * @param req
166
- */
167
- async updateUserRole(_id: string | any, role: string, req?: Req) {
168
- const query = this.hooks.alter(
169
- "submissionQuery",
170
- {
171
- _id: this.formio.util.idToBson(_id),
172
- deleted: {$eq: null}
173
- },
174
- req
175
- );
176
-
177
- const user = await this.db.submissionModel.findOne(query).exec();
178
-
179
- if (!user) {
180
- throw new BadRequest("No Submission was found with the given setting `submission`.");
181
- }
182
-
183
- user.roles = [this.formio.util.idToBson(role)];
184
-
185
- if (isFunction(user.save)) {
186
- await user.save();
187
- }
188
-
189
- return user;
190
- }
191
-
192
- /**
193
- * Create a user submission in formio
194
- * @param user
195
- */
196
- async createUser<User = any>(user: Partial<FormioSubmission<User>>) {
197
- const submission = new this.db.submissionModel({
198
- owner: null,
199
- deleted: null,
200
- roles: [],
201
- externalsIds: [],
202
- ...user,
203
- created: new Date().toISOString(),
204
- modified: new Date().toISOString()
205
- });
206
-
207
- user.form && (submission.form = this.db.idToBson(user.form));
208
-
209
- await submission.save();
210
-
211
- return submission.toObject();
212
- }
213
-
214
- /**
215
- * Update user submission in formio
216
- * @param user
217
- */
218
- async updateUser<User = any>(user: WithID<FormioSubmission<User>>) {
219
- await this.db.submissionModel.updateOne(
220
- {
221
- _id: user._id
222
- },
223
- {$set: user}
224
- );
225
-
226
- return user;
227
- }
228
- }