gemcap-be-common 1.3.187 → 1.4.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 (43) hide show
  1. package/db/collaterals.db.d.ts +1 -1
  2. package/interfaces/auth-user.interface.d.ts +21 -0
  3. package/interfaces/auth-user.interface.ts +22 -0
  4. package/models/AvailabilitySigns.model.d.ts +3 -3
  5. package/models/AvailabilitySigns.model.ts +3 -3
  6. package/models/ReceivableAvailability.model.d.ts +32 -32
  7. package/models/ReceivableAvailability.model.ts +2 -2
  8. package/models/User.model.d.ts +3 -3
  9. package/models/User.model.ts +3 -3
  10. package/models/_index.d.ts +3 -3
  11. package/package.json +1 -1
  12. package/services/availability.service.d.ts +5 -5
  13. package/services/availability.service.ts +5 -5
  14. package/services/borrowers.db.d.ts +1 -1
  15. package/services/borrowers.db.js +1 -1
  16. package/services/borrowers.db.ts +2 -2
  17. package/services/borrowers.service.d.ts +5 -4
  18. package/services/borrowers.service.js +8 -5
  19. package/services/borrowers.service.ts +9 -5
  20. package/services/compliance-borrowers.service.d.ts +3 -3
  21. package/services/compliance-borrowers.service.ts +2 -2
  22. package/services/loan-payments.service.d.ts +3 -1
  23. package/services/loan-payments.service.js +5 -4
  24. package/services/loan-payments.service.ts +4 -3
  25. package/services/nodemailer.service.d.ts +0 -2
  26. package/services/nodemailer.service.js +0 -28
  27. package/services/nodemailer.service.ts +0 -35
  28. package/services/signs.service.d.ts +4 -4
  29. package/services/signs.service.js +2 -4
  30. package/services/signs.service.ts +8 -11
  31. package/services/uploads.service.d.ts +3 -1
  32. package/services/uploads.service.js +4 -3
  33. package/services/uploads.service.ts +3 -2
  34. package/services/users.service.d.ts +15 -137
  35. package/services/users.service.js +81 -349
  36. package/services/users.service.ts +88 -380
  37. package/tsconfig.tsbuildinfo +1 -1
  38. package/interfaces/keycloak-role.interface.d.ts +0 -14
  39. package/interfaces/keycloak-role.interface.ts +0 -16
  40. package/interfaces/keycloak-user.interface.d.ts +0 -31
  41. package/interfaces/keycloak-user.interface.js +0 -2
  42. package/interfaces/keycloak-user.interface.ts +0 -30
  43. /package/interfaces/{keycloak-role.interface.js → auth-user.interface.js} +0 -0
@@ -5,13 +5,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.UsersService = void 0;
7
7
  const jwt_decode_1 = require("jwt-decode");
8
- const lodash_1 = __importDefault(require("lodash"));
9
8
  const axios_1 = __importDefault(require("axios"));
10
- const dayjs_1 = __importDefault(require("dayjs"));
11
9
  const mongoose_1 = __importDefault(require("mongoose"));
12
- const qs_1 = __importDefault(require("qs"));
13
- const user_logs_db_1 = require("../db/user-logs.db");
14
- const User_model_1 = require("../models/User.model");
15
10
  const BorrowerCompliance_model_1 = require("../models/BorrowerCompliance.model");
16
11
  const UserMobileAccess_model_1 = require("../models/UserMobileAccess.model");
17
12
  const UserLog_model_1 = require("../models/UserLog.model");
@@ -20,8 +15,25 @@ class UsersService {
20
15
  constructor(config) {
21
16
  this.config = config;
22
17
  }
23
- async getUserByKeyCloakId(keycloakUserId) {
24
- return User_model_1.UserModel.findOne({ keycloakUserId }).lean();
18
+ async getUserAccessByRequest(req) {
19
+ const authorization = req.get('Authorization');
20
+ if (!authorization) {
21
+ return null;
22
+ }
23
+ const { sub } = (0, jwt_decode_1.jwtDecode)(authorization);
24
+ const user = await this.getUserById(sub);
25
+ if (!user) {
26
+ return null;
27
+ }
28
+ return user;
29
+ }
30
+ async getUserById(userId) {
31
+ const { data } = await axios_1.default.get(`${this.config.baseUrl}/users/by-id/${userId}`);
32
+ return data ?? null;
33
+ }
34
+ async getUserByUsername(username) {
35
+ const { data } = await axios_1.default.get(`${this.config.baseUrl}/users/by-username/${username}`);
36
+ return data ?? null;
25
37
  }
26
38
  async getUserByToken(req) {
27
39
  const authorization = req.get('Authorization');
@@ -29,367 +41,87 @@ class UsersService {
29
41
  return null;
30
42
  }
31
43
  const { sub: keycloakUserId } = (0, jwt_decode_1.jwtDecode)(authorization);
32
- return this.getUserByKeyCloakId(keycloakUserId);
44
+ return this.getUserById(keycloakUserId);
33
45
  }
34
46
  async getUserIdByToken(req) {
35
47
  const user = await this.getUserByToken(req);
36
48
  if (user) {
37
- return user._id.toString();
49
+ return user.id;
38
50
  }
39
51
  return null;
40
52
  }
41
- async getUserRepresentationById(authorization, userId) {
42
- const options = {
43
- method: 'GET',
44
- url: `${this.config.keycloakHost}/admin/realms/${this.config.realm}/users/${userId}`,
45
- headers: {
46
- 'Content-Type': 'application/json',
47
- Authorization: `Bearer ${authorization}`,
48
- },
49
- };
50
- const result = await axios_1.default.request(options);
51
- return result.data;
52
- }
53
- async getUserRepresentationByUsername(authorization, username) {
54
- const options = {
55
- method: 'GET',
56
- url: `${this.config.keycloakHost}/admin/realms/${this.config.realm}/users?username=${username}`,
57
- headers: {
58
- 'Content-Type': 'application/json',
59
- Authorization: `Bearer ${authorization}`,
60
- },
61
- };
62
- const result = await axios_1.default.request(options);
63
- const users = result.data;
64
- return users.find((user) => user.username === username);
53
+ async getUserList() {
54
+ const { data } = await axios_1.default.get(`${this.config.baseUrl}/users/users`);
55
+ return data ?? null;
65
56
  }
66
- async getKeyCloakAdminBearer() {
67
- const url = `${this.config.keycloakHost}/realms/master/protocol/openid-connect/token`;
68
- const data = qs_1.default.stringify({
69
- username: this.config.adminUser,
70
- password: this.config.adminPass,
71
- client_id: 'admin-cli',
72
- grant_type: 'password',
73
- });
74
- const headers = {
75
- 'Content-Type': 'application/x-www-form-urlencoded',
76
- };
77
- const response = await axios_1.default.post(url, data, { headers });
78
- return response.data;
79
- }
80
- async getUserList(authorization) {
81
- const options = {
82
- method: 'GET',
83
- url: `${this.config.keycloakHost}/admin/realms/${this.config.realm}/users`,
84
- headers: {
85
- 'Content-Type': 'application/json',
86
- Authorization: `Bearer ${authorization}`,
87
- },
88
- };
89
- const result = await axios_1.default.request(options);
90
- return result.data;
91
- }
92
- async getUsersWithRoles(authorization) {
93
- const users = await this.getUserList(authorization);
94
- const usersWithNames = users.map((user) => ({ firstName: '', lastName: '', ...user }));
95
- const usersWithRoles = await this
96
- .mapRolesToUsers(authorization, usersWithNames.sort((a, b) => a.createdTimestamp - b.createdTimestamp));
97
- const usersAndAccess = (await this.addUserAccess(usersWithRoles)).filter((user) => !!user);
98
- const newUser = usersAndAccess.find((user) => user.username === '!new user');
99
- if (newUser) {
100
- return [newUser, ...usersAndAccess.slice(0, usersAndAccess.length - 1)];
101
- }
102
- return usersAndAccess;
103
- }
104
- async getUserRoles(authorization, userId) {
105
- const options = {
106
- method: 'GET',
107
- url: `${this.config.keycloakHost}/admin/realms/${this.config.realm}/users/${userId}/role-mappings`,
108
- headers: {
109
- 'Content-Type': 'application/json',
110
- Authorization: `Bearer ${authorization}`,
111
- },
112
- };
113
- const result = await axios_1.default.request(options);
114
- return result.data;
115
- }
116
- async createUser(authorization, user) {
117
- const options = {
118
- method: 'POST',
119
- url: `${this.config.keycloakHost}/admin/realms/${this.config.realm}/users`,
120
- headers: {
121
- 'Content-Type': 'application/json',
122
- Authorization: `Bearer ${authorization}`,
123
- },
124
- data: {
125
- ...user,
126
- },
127
- };
128
- const result = await axios_1.default.request(options);
129
- return result.data;
130
- }
131
- async updateUser(authorization, userId, keyValue) {
132
- const options = {
133
- method: 'PUT',
134
- url: `${this.config.keycloakHost}/admin/realms/${this.config.realm}/users/${userId}`,
135
- headers: {
136
- 'Content-Type': 'application/json',
137
- Authorization: `Bearer ${authorization}`,
138
- },
139
- data: keyValue,
140
- };
141
- const result = await axios_1.default.request(options);
142
- return result.data;
57
+ async getUserRoles(userId) {
58
+ const user = await this.getUserById(userId);
59
+ return user.roles;
143
60
  }
144
61
  async updateMobileUser(userId, keyValue) {
145
62
  await UserMobileAccess_model_1.UserMobileAccess.findOneAndUpdate({ keycloakUserId: userId }, keyValue, { upsert: true });
146
63
  }
147
- async updateUserAccess(keycloakUserId, userAccess) {
148
- await User_model_1.UserModel
149
- .findOneAndUpdate({ keycloakUserId }, userAccess);
150
- }
151
- async removeUserRoles(authorization, userId, roles) {
152
- const options = {
153
- method: 'DELETE',
154
- url: `${this.config.keycloakHost}/admin/realms/${this.config.realm}/users/${userId}/role-mappings/realm`,
155
- headers: {
156
- 'Content-Type': 'application/json',
157
- Authorization: `Bearer ${authorization}`,
158
- },
159
- data: [...roles],
160
- };
161
- const result = await axios_1.default.request(options);
162
- return result.data;
163
- }
164
- async addUserRoles(authorization, userId, roles) {
165
- const options = {
166
- method: 'POST',
167
- url: `${this.config.keycloakHost}/admin/realms/${this.config.realm}/users/${userId}/role-mappings/realm`,
168
- headers: {
169
- 'Content-Type': 'application/json',
170
- Authorization: `Bearer ${authorization}`,
171
- },
172
- data: [...roles],
173
- };
174
- const result = await axios_1.default.request(options);
175
- return result.data;
176
- }
177
- async resetPassword(authorization, userId, temporaryPassword) {
178
- const options = {
179
- method: 'PUT',
180
- url: `${this.config.keycloakHost}/admin/realms/${this.config.realm}/users/${userId}/reset-password`,
181
- headers: {
182
- 'Content-Type': 'application/json',
183
- Authorization: `Bearer ${authorization}`,
184
- },
185
- data: { value: temporaryPassword, temporary: true },
186
- };
187
- const result = await axios_1.default.request(options);
188
- return result.data;
189
- }
190
- async createNewPasswordWithEmail(authorization, userId, newPassword) {
191
- const options = {
192
- method: 'PUT',
193
- url: `${this.config.keycloakHost}/admin/realms/${this.config.realm}/users/${userId}/reset-password`,
194
- headers: {
195
- 'Content-Type': 'application/json',
196
- Authorization: `Bearer ${authorization}`,
197
- },
198
- data: {
199
- type: 'password',
200
- value: newPassword,
201
- temporary: false,
202
- },
203
- };
204
- const response = await axios_1.default.request(options);
205
- return response;
206
- }
207
- async deleteUser(authorization, userId) {
208
- const deletedUser = await this.getUserRepresentationById(authorization, userId);
209
- const url = `${this.config.keycloakHost}/admin/realms/${this.config.realm}/users/${userId}`;
210
- const options = {
211
- method: 'DELETE',
212
- url,
213
- headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${authorization}` },
214
- };
215
- try {
216
- await axios_1.default.request(options);
217
- const update = {
218
- isDeleted: true,
219
- firstName: deletedUser.firstName ?? deletedUser.username,
220
- lastName: deletedUser.lastName ?? '',
221
- };
222
- await User_model_1.UserModel.findOneAndUpdate({ keycloakUserId: userId }, update);
223
- }
224
- catch (error) {
225
- console.log(error);
226
- }
227
- }
228
- async getRoleList(authorization) {
229
- const options = {
230
- method: 'GET',
231
- url: `${this.config.keycloakHost}/admin/realms/${this.config.realm}/roles`,
232
- headers: {
233
- 'Content-Type': 'application/json',
234
- Authorization: `Bearer ${authorization}`,
235
- },
236
- };
237
- const result = await axios_1.default.request(options);
238
- return result.data;
239
- }
240
- groupRoles(roles) {
241
- return roles.reduce((acc, role) => {
242
- const [module, roleName] = role.name.split('/');
243
- if (!roleName) {
244
- return acc;
245
- }
246
- const addedRoles = acc[module] ?? [];
247
- return { ...acc, [module]: [...addedRoles, { ...role, representation: roleName }] };
248
- }, {});
249
- }
250
- mapRolesToUsers(authorization, users) {
251
- const usersWithRolesPromise = users.map(async (user) => {
252
- const roles = await this.getUserRoles(authorization, user.id);
253
- return { ...user, roles: this.groupRoles(roles.realmMappings) };
254
- });
255
- return Promise.all(usersWithRolesPromise);
256
- }
257
- addUserAccess(users) {
258
- const usersWithRolesPromise = users.map(async (user) => {
259
- const foundUser = await User_model_1.UserModel.findOne({ keycloakUserId: user.id }).lean();
260
- const foundMobileUser = await UserMobileAccess_model_1.UserMobileAccess.findOne({ keycloakUserId: user.id }).lean();
261
- if (!foundUser) {
262
- return null;
263
- }
264
- return {
265
- ...(lodash_1.default.omit(user, ['id'])),
266
- keycloakUserId: user.id,
267
- _id: foundUser._id,
268
- allBorrowers: foundUser.allBorrowers,
269
- borrowersAccess: foundUser.borrowersAccess,
270
- lastLogin: foundUser.lastLogin,
271
- mobileAccess: {
272
- hasAccess: foundMobileUser?.hasAccess ?? false,
273
- canSignDocument: foundMobileUser?.canSignDocument ?? false,
274
- },
275
- };
276
- });
277
- return Promise.all(usersWithRolesPromise);
278
- }
279
- async getUserAccess(keycloakUserId) {
280
- const foundUser = await User_model_1.UserModel.findOne({ keycloakUserId }).lean();
281
- const borrowersAccess = foundUser.borrowersAccess.map((b) => ({ borrower: b.borrower }));
282
- const complianceBorrowersAccess = (await BorrowerCompliance_model_1.BorrowerCompliance.find({ 'borrower': { $in: borrowersAccess.map((b) => b.borrower) } }))
64
+ async getUserAccess(userId) {
65
+ const foundUser = await this.getUserById(userId);
66
+ const borrowersAccess = foundUser.borrowersAccess;
67
+ const complianceBorrowersAccess = (await BorrowerCompliance_model_1.BorrowerCompliance.find({ 'borrower': { $in: borrowersAccess } }))
283
68
  .map((b) => ({ borrower: b._id.toString() }));
284
69
  return { allBorrowers: foundUser.allBorrowers, borrowersAccess, complianceBorrowersAccess };
285
70
  }
286
- async getUserAccessByRequest(req) {
287
- const authorization = req.get('Authorization');
288
- if (!authorization) {
289
- return null;
290
- }
291
- const { sub: keycloakUserId } = (0, jwt_decode_1.jwtDecode)(authorization);
292
- return await this.getUserAccess(keycloakUserId);
293
- }
294
- async updateUserLastLogin(authorization) {
295
- const allUsers = await User_model_1.UserModel.find({}).lean();
296
- await Promise.all(allUsers.map(async (user) => {
297
- const reqUrl = `${this.config.keycloakHost}/admin/realms/${this.config.realm}/events?type=LOGIN&user=${user.keycloakUserId}&max=1`;
298
- const options = {
299
- method: 'GET',
300
- url: reqUrl,
301
- headers: {
302
- 'Content-Type': 'application/json',
303
- Authorization: `Bearer ${authorization}`,
304
- },
305
- };
306
- const result = await axios_1.default.request(options);
307
- if (result.data.length > 0) {
308
- await User_model_1.UserModel.findByIdAndUpdate(user._id, { lastLogin: new Date(result.data[0].time) });
309
- }
310
- }));
311
- }
312
71
  async createUserLoginLog() {
313
- const { access_token } = await this.getKeyCloakAdminBearer();
314
- const dateFrom = (0, dayjs_1.default)().subtract(1, 'day').format('YYYY-MM-DD');
315
- const reqUrl = `${this.config.keycloakHost}/admin/realms/${this.config.realm}/events?type=LOGIN&dateFrom=${dateFrom}&max=10000`;
316
- const options = {
317
- method: 'GET',
318
- url: reqUrl,
319
- headers: {
320
- 'Content-Type': 'application/json',
321
- Authorization: `Bearer ${access_token}`,
322
- },
323
- };
324
- try {
325
- const result = await axios_1.default.request(options);
326
- const userDates = {};
327
- result.data.forEach((log) => {
328
- const timestamp = new Date(log.time);
329
- const formattedDate = timestamp.getFullYear() +
330
- '-' + ('0' + (timestamp.getMonth() + 1)).slice(-2) +
331
- '-' + ('0' + timestamp.getDate()).slice(-2) +
332
- 'T' + ('0' + timestamp.getHours()).slice(-2) +
333
- ':' + ('0' + timestamp.getMinutes()).slice(-2);
334
- const userId = log.userId;
335
- if (!userDates[userId]) {
336
- userDates[userId] = new Set();
337
- }
338
- userDates[userId].add(formattedDate);
339
- });
340
- await Promise.all(Object.entries(userDates).map(async ([userId, dateSet]) => {
341
- const user = await User_model_1.UserModel.findOne({ keycloakUserId: userId });
342
- if (!user) {
343
- return;
344
- }
345
- await Promise.all(Array.from(dateSet).map(async (date) => {
346
- const existingLog = await this.getUserLogByDate(String(user._id), new Date(date));
347
- if (!existingLog) {
348
- const newLog = {
349
- action: UserLog_model_1.ELogActionType.CREATE,
350
- timestamp: new Date(date),
351
- logType: UserLog_model_1.ELogType.LOGIN,
352
- userId: String(user._id),
353
- details: {},
354
- };
355
- await (0, user_logs_db_1.createLog)(newLog);
356
- }
357
- }));
358
- }));
359
- }
360
- catch (e) {
361
- console.error(e);
362
- }
72
+ // const { access_token } = await this.getKeyCloakAdminBearer();
73
+ // const dateFrom = dayjs().subtract(1, 'day').format('YYYY-MM-DD');
74
+ // const reqUrl = `${this.config.keycloakHost}/admin/realms/${this.config.realm}/events?type=LOGIN&dateFrom=${dateFrom}&max=10000`;
75
+ // const options = {
76
+ // method: 'GET',
77
+ // url: reqUrl,
78
+ // headers: {
79
+ // 'Content-Type': 'application/json',
80
+ // Authorization: `Bearer ${access_token}`,
81
+ // },
82
+ // };
83
+ // try {
84
+ // const result = await axios.request(options);
85
+ // const userDates: { [userId: string]: Set<string> } = {};
86
+ // result.data.forEach((log: { userId: string, time: number }) => {
87
+ // const timestamp = new Date(log.time);
88
+ // const formattedDate = timestamp.getFullYear() +
89
+ // '-' + ('0' + (timestamp.getMonth() + 1)).slice(-2) +
90
+ // '-' + ('0' + timestamp.getDate()).slice(-2) +
91
+ // 'T' + ('0' + timestamp.getHours()).slice(-2) +
92
+ // ':' + ('0' + timestamp.getMinutes()).slice(-2);
93
+ //
94
+ // const userId = log.userId;
95
+ // if (!userDates[userId]) {
96
+ // userDates[userId] = new Set<string>();
97
+ // }
98
+ // userDates[userId].add(formattedDate);
99
+ // });
100
+ // await Promise.all(Object.entries(userDates).map(async ([userId, dateSet]) => {
101
+ // const user = await UserModel.findOne({ keycloakUserId: userId });
102
+ // if (!user) {
103
+ // return;
104
+ // }
105
+ // await Promise.all(Array.from(dateSet).map(async (date) => {
106
+ // const existingLog = await this.getUserLogByDate(String(user._id), new Date(date));
107
+ // if (!existingLog) {
108
+ // const newLog: ICreateLogParams = {
109
+ // action: ELogActionType.CREATE,
110
+ // timestamp: new Date(date),
111
+ // logType: ELogType.LOGIN,
112
+ // userId: String(user._id),
113
+ // details: {},
114
+ // };
115
+ // await createLog(newLog);
116
+ // }
117
+ // }));
118
+ // }));
119
+ // } catch (e) {
120
+ // console.error(e);
121
+ // }
363
122
  }
364
123
  async getUserLogByDate(userId, date) {
365
124
  return UserLog_model_1.UserLog.findOne({ userId: new mongoose_1.default.Types.ObjectId(userId), timestamp: date }).lean();
366
125
  }
367
- async getUserSecrets(keycloakUserId, adminAccessToken) {
368
- const reqUrl = `${this.config.keycloakHost}/admin/realms/${this.config.realm}/users/${keycloakUserId}/credentials`;
369
- const options = {
370
- method: 'GET',
371
- url: reqUrl,
372
- headers: {
373
- 'Content-Type': 'application/json',
374
- Authorization: `Bearer ${adminAccessToken}`,
375
- },
376
- };
377
- const result = await axios_1.default.request(options);
378
- console.log(result.data);
379
- }
380
- async updateUserNames() {
381
- const { access_token } = await this.getKeyCloakAdminBearer();
382
- const keycloakUsers = await this.getUserList(access_token);
383
- const users = await User_model_1.UserModel.find({}).lean();
384
- await Promise.all(users.map(async (user) => {
385
- const keycloakUser = keycloakUsers.find((u) => u.id === user.keycloakUserId);
386
- if (keycloakUser) {
387
- await User_model_1.UserModel.findByIdAndUpdate(user._id, {
388
- firstName: keycloakUser.firstName,
389
- lastName: keycloakUser.lastName,
390
- });
391
- }
392
- }));
393
- }
394
126
  }
395
127
  exports.UsersService = UsersService;