-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathapi.service.ts
More file actions
667 lines (635 loc) · 22.8 KB
/
Copy pathapi.service.ts
File metadata and controls
667 lines (635 loc) · 22.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
import {
Error,
LoginResponse,
User,
UUID,
} from '@fusionauth/typescript-client';
import ClientResponse from '@fusionauth/typescript-client/build/src/ClientResponse';
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import {
RefreshTokenResult,
ResponseCode,
ResponseStatus,
SignupResponse,
UserRegistration,
UsersResponse,
} from './api.interface';
import { FusionauthService } from './fusionauth/fusionauth.service';
import { OtpService } from './otp/otp.service';
import { v4 as uuidv4 } from 'uuid';
import { ConfigResolverService } from './config.resolver.service';
import { RefreshRequest } from '@fusionauth/typescript-client/build/src/FusionAuthClient';
import { FAStatus } from '../user/fusionauth/fusionauth.service';
import { ChangePasswordDTO } from '../user/dto/changePassword.dto';
import { SMSResponseStatus } from '../user/sms/sms.interface';
import { LoginDto } from '../user/dto/login.dto';
import { FusionAuthUserRegistration } from '../admin/admin.interface';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const CryptoJS = require('crypto-js');
// eslint-disable-next-line @typescript-eslint/no-var-requires
const AES = require('crypto-js/aes');
import Flagsmith from 'flagsmith-nodejs';
const jwksClient = require('jwks-rsa');;
CryptoJS.lib.WordArray.words;
@Injectable()
export class ApiService {
encodedBase64Key;
parsedBase64Key;
constructor(
private configService: ConfigService,
private readonly fusionAuthService: FusionauthService,
private readonly otpService: OtpService,
private readonly configResolverService: ConfigResolverService,
) {}
private readonly jwksClient = jwksClient({
jwksUri: this.configService.get('JWKS_URI'),
cache: true,
cacheMaxEntries: 5,
cacheMaxAge: 86400000,
});
login(user: any, authHeader: string): Promise<SignupResponse> {
return this.fusionAuthService
.login(user, authHeader)
.then(async (resp: ClientResponse<LoginResponse>) => {
let fusionAuthUser: any = resp.response;
if (fusionAuthUser.user === undefined) {
fusionAuthUser = fusionAuthUser.loginResponse.successResponse;
}
if (
fusionAuthUser?.user?.registrations?.filter((registration) => {
return registration.applicationId == user.applicationId;
}).length == 0
) {
// User is not registered in the requested application. Let's throw error.
const response: SignupResponse = new SignupResponse().init(uuidv4());
response.responseCode = ResponseCode.FAILURE;
response.params.err = 'INVALID_REGISTRATION';
response.params.errMsg =
'User registration not found in the given application.';
response.params.status = ResponseStatus.failure;
return response;
}
// if (fusionAuthUser.user.data.accountName === undefined) {
// if (fusionAuthUser.user.fullName == undefined) {
// if (fusionAuthUser.user.firstName === undefined) {
// if(encStatus){
// fusionAuthUser['user']['data']['accountName'] = this.decrypt(
// user.loginId, this.parsedBase64Key
// );
// }else {
// fusionAuthUser['user']['data']['accountName'] = user.loginId;
// }
// } else {
// fusionAuthUser['user']['data']['accountName'] =
// fusionAuthUser.user.firstName;
// }
// } else {
// fusionAuthUser['user']['data']['accountName'] =
// fusionAuthUser.user.fullName;
// }
// }
const response: SignupResponse = new SignupResponse().init(uuidv4());
response.responseCode = ResponseCode.OK;
response.result = {
responseMsg: 'Successful Logged In',
accountStatus: null,
data: {
user: fusionAuthUser,
},
};
if(
this.configService.get('USE_FLAGSMITH') === 'true' &&
this.configService.get('FLAGSMITH_ENVIRONMENT_KEY')
){
let flagsmith = new Flagsmith({
environmentKey: this.configService.get("FLAGSMITH_ENVIRONMENT_KEY")
});
await flagsmith.getIdentityFlags(fusionAuthUser.user.username, ['role']);
}
return response;
})
.catch((errorResponse: ClientResponse<LoginResponse>): SignupResponse => {
// console.log(errorResponse);
const response: SignupResponse = new SignupResponse().init(uuidv4());
if (errorResponse.statusCode === 404) {
response.responseCode = ResponseCode.FAILURE;
response.params.err = 'INVALID_USERNAME_PASSWORD';
response.params.errMsg = 'Invalid Username/Password';
response.params.status = ResponseStatus.failure;
} else if (errorResponse.statusCode === 409) {
response.responseCode = ResponseCode.FAILURE;
response.params.err = 'ACCOUNT_LOCKED';
response.params.errMsg = 'Multiple failed login attempts. Please retry again later.';
response.params.status = ResponseStatus.failure;
} else {
response.responseCode = ResponseCode.FAILURE;
response.params.err = 'UNCAUGHT_EXCEPTION';
response.params.errMsg = 'Server Failure';
response.params.status = ResponseStatus.failure;
}
return response;
});
}
loginByPin(user: any, authHeader: string): Promise<SignupResponse> {
this.encodedBase64Key = this.configResolverService.getEncryptionKey(
user.applicationId,
);
this.parsedBase64Key =
this.encodedBase64Key === undefined
? CryptoJS.enc.Base64.parse('bla')
: CryptoJS.enc.Base64.parse(this.encodedBase64Key);
return this.fusionAuthService
.login(user, authHeader)
.then(async (resp: ClientResponse<LoginResponse>) => {
let fusionAuthUser: any = resp.response;
if (fusionAuthUser.user === undefined) {
fusionAuthUser = fusionAuthUser.loginResponse.successResponse;
}
// if (fusionAuthUser.user.data.accountName === undefined) {
// if (fusionAuthUser.user.fullName == undefined) {
// if (fusionAuthUser.user.firstName === undefined) {
// fusionAuthUser['user']['data']['accountName'] = this.decrypt(
// user.loginId, this.parsedBase64Key
// );
// } else {
// fusionAuthUser['user']['data']['accountName'] =
// fusionAuthUser.user.firstName;
// }
// } else {
// fusionAuthUser['user']['data']['accountName'] =
// fusionAuthUser.user.fullName;
// }
// }
const response: SignupResponse = new SignupResponse().init(uuidv4());
response.responseCode = ResponseCode.OK;
response.result = {
responseMsg: 'Successful Logged In',
accountStatus: null,
data: {
user: fusionAuthUser,
},
};
return response;
})
.catch((errorResponse: ClientResponse<LoginResponse>): SignupResponse => {
console.log(errorResponse);
const response: SignupResponse = new SignupResponse().init(uuidv4());
if (errorResponse.statusCode === 404) {
response.responseCode = ResponseCode.FAILURE;
response.params.err = 'INVALID_USERNAME_PASSWORD';
response.params.errMsg = 'Invalid Username/Password';
response.params.status = ResponseStatus.failure;
} else {
response.responseCode = ResponseCode.FAILURE;
response.params.err = 'UNCAUGHT_EXCEPTION';
response.params.errMsg = 'Server Failure';
response.params.status = ResponseStatus.failure;
}
return response;
});
}
async fetchUsers(
applicationId: string,
startRow?: number,
numberOfResults?: number,
authHeader?: string,
): Promise<UsersResponse> {
const { total, users }: { total: number; users: Array<User> } =
await this.fusionAuthService.getUsers(
applicationId,
startRow,
numberOfResults,
authHeader,
);
const response: UsersResponse = new UsersResponse().init(uuidv4());
if (users != null) {
response.responseCode = ResponseCode.OK;
response.params.status = ResponseStatus.success;
response.result = { total, users };
} else {
response.responseCode = ResponseCode.FAILURE;
response.params.status = ResponseStatus.failure;
response.params.errMsg = 'No users found';
response.params.err = 'NO_USERS_FOUND';
}
return response;
}
async updatePassword(
data: { loginId: string; password: string },
applicationId: string,
authHeader?: string,
): Promise<any> {
return this.fusionAuthService.updatePasswordWithLoginId(
data,
applicationId,
authHeader,
);
}
async createUser(
data: UserRegistration,
applicationId: string,
authHeader?: string,
): Promise<SignupResponse> {
const { userId, user, err }: { userId: UUID; user: User; err: Error } =
await this.fusionAuthService.createAndRegisterUser(
data,
applicationId,
authHeader,
);
if (userId == null || user == null) {
throw new HttpException(err, HttpStatus.BAD_REQUEST);
}
const response: SignupResponse = new SignupResponse().init(uuidv4());
response.result = user;
return response;
}
async createUserByPin(
data: UserRegistration,
applicationId: string,
authHeader?: string,
): Promise<SignupResponse> {
const encodedBase64Key =
this.configResolverService.getEncryptionKey(applicationId);
const parsedBase64Key =
encodedBase64Key === undefined
? CryptoJS.enc.Base64.parse('bla')
: CryptoJS.enc.Base64.parse(encodedBase64Key);
data.user.password = this.encrypt(data.user.password, parsedBase64Key);
const { userId, user, err }: { userId: UUID; user: User; err: Error } =
await this.fusionAuthService.createAndRegisterUser(
data,
applicationId,
authHeader,
);
if (userId == null || user == null) {
throw new HttpException(err, HttpStatus.BAD_REQUEST);
}
const response: SignupResponse = new SignupResponse().init(uuidv4());
response.result = user;
return response;
}
async updateUser(
userId: string,
data: User,
applicationId: string,
authHeader?: string,): Promise<any> {
const registrations: Array<FusionAuthUserRegistration> = data?.registrations
? data.registrations
: [];
delete data.registrations; // delete the registrations key
const { _userId, user, err }: { _userId: UUID; user: User; err: Error } =
await this.fusionAuthService.updateUser(
userId,
{ user: data },
applicationId,
authHeader,
);
if (_userId == null || user == null) {
throw new HttpException(err, HttpStatus.BAD_REQUEST);
}
// if there are registrations Array, we'll update the registrations too
for (const registration of registrations) {
console.log(`Updating registration: ${JSON.stringify(registration)}`);
await this.updateUserRegistration(applicationId, authHeader, userId, registration); // calling patch registration API
}
const response: SignupResponse = new SignupResponse().init(uuidv4());
response.result = user;
return response;
}
async fetchUsersByString(
queryString: string,
startRow: number,
numberOfResults: number,
applicationId: string,
authHeader?: string,
): Promise<UsersResponse> {
const { total, users }: { total: number; users: Array<User> } =
await this.fusionAuthService.getUsersByString(
queryString,
startRow,
numberOfResults,
applicationId,
authHeader,
);
const response: UsersResponse = new UsersResponse().init(uuidv4());
if (users != null) {
response.responseCode = ResponseCode.OK;
response.params.status = ResponseStatus.success;
response.result = { total, users };
} else {
response.responseCode = ResponseCode.FAILURE;
response.params.status = ResponseStatus.failure;
response.params.errMsg = 'No users found';
response.params.err = 'NO_USERS_FOUND';
}
return response;
}
encrypt(plainString: any, key: string): any {
return AES.encrypt(plainString, key, {
mode: CryptoJS.mode.ECB,
}).toString();
}
decrypt(encryptedString: any, key: string): any {
return AES.decrypt(encryptedString, key, {
mode: CryptoJS.mode.ECB,
}).toString(CryptoJS.enc.Utf8);
}
async refreshToken(
applicationId: string,
refreshRequest: RefreshRequest,
authHeader?: string,
): Promise<UsersResponse> {
const refreshTokenResponse: RefreshTokenResult =
await this.fusionAuthService.refreshToken(
applicationId,
refreshRequest,
authHeader,
);
const response: UsersResponse = new UsersResponse().init(uuidv4());
if (refreshTokenResponse.user.token !== null) {
response.responseCode = ResponseCode.OK;
response.params.status = ResponseStatus.success;
response.result = refreshTokenResponse;
} else {
response.responseCode = ResponseCode.FAILURE;
response.params.status = ResponseStatus.failure;
response.params.errMsg =
'Failed to refresh token. Please ensure the input you have provided is correct';
response.params.err = 'REFRESH_TOKEN_FAILED';
}
return response;
}
async deactivateUserById(
userId: string,
hardDelete: boolean,
applicationId: string,
authHeader?: string,
): Promise<any> {
const activationResponse: { userId: UUID; err: Error } =
await this.fusionAuthService.deactivateUserById(
userId,
hardDelete,
applicationId,
authHeader,
);
if (activationResponse.userId == null) {
throw new HttpException(activationResponse.err, HttpStatus.BAD_REQUEST);
}
// fetch the latest user info now & respond
const userResponse = await this.fusionAuthService.getUserById(
userId,
applicationId,
authHeader,
);
const response: SignupResponse = new SignupResponse().init(uuidv4());
response.result = userResponse.user;
return response;
}
async activateUserById(
userId: string,
applicationId: string,
authHeader?: string,
): Promise<any> {
const activationResponse: { userId: UUID; err: Error } =
await this.fusionAuthService.activateUserById(
userId,
applicationId,
authHeader,
);
if (activationResponse.userId == null) {
throw new HttpException(activationResponse.err, HttpStatus.BAD_REQUEST);
}
// fetch the latest user info now & respond
const userResponse = await this.fusionAuthService.getUserById(
userId,
applicationId,
authHeader,
);
const response: SignupResponse = new SignupResponse().init(uuidv4());
response.result = userResponse.user;
return response;
}
async changePasswordOTP(
username: string,
applicationId: UUID,
authHeader: null | string,
): Promise<SignupResponse> {
// Get Phone No from username
const {
statusFA,
userId,
user,
}: { statusFA: FAStatus; userId: UUID; user: User } =
await this.fusionAuthService.getUser(username, applicationId, authHeader);
const response: SignupResponse = new SignupResponse().init(uuidv4());
// If phone number is valid => Send OTP
if (statusFA === FAStatus.USER_EXISTS) {
const re = /^[6-9]{1}[0-9]{9}$/;
if (re.test(user.mobilePhone)) {
const result = await this.otpService.sendOTP(user.mobilePhone);
response.result = {
data: result,
responseMsg: `OTP has been sent to ${user.mobilePhone}.`,
};
response.responseCode = ResponseCode.OK;
response.params.status = ResponseStatus.success;
} else {
response.responseCode = ResponseCode.FAILURE;
response.params.err = 'INVALID_PHONE_NUMBER';
response.params.errMsg = 'Invalid Phone number';
response.params.status = ResponseStatus.failure;
}
} else {
response.responseCode = ResponseCode.FAILURE;
response.params.err = 'INVALID_USERNAME';
response.params.errMsg = 'No user with this Username exists';
response.params.status = ResponseStatus.failure;
}
return response;
}
async changePassword(
data: ChangePasswordDTO,
applicationId: UUID,
authHeader: null | string,
): Promise<SignupResponse> {
// Verify OTP
const {
statusFA,
userId,
user,
}: { statusFA: FAStatus; userId: UUID; user: User } =
await this.fusionAuthService.getUser(
data.username,
applicationId,
authHeader,
);
const response: SignupResponse = new SignupResponse().init(uuidv4());
if (statusFA === FAStatus.USER_EXISTS) {
const verifyOTPResult = await this.otpService.verifyOTP({
phone: user.mobilePhone,
otp: data.OTP,
});
if (verifyOTPResult.status === SMSResponseStatus.success) {
const result = await this.fusionAuthService.updatePassword(
userId,
data.password,
applicationId,
authHeader,
);
if (result.statusFA == FAStatus.SUCCESS) {
response.result = {
responseMsg: 'Password updated successfully',
};
response.responseCode = ResponseCode.OK;
response.params.status = ResponseStatus.success;
} else {
response.responseCode = ResponseCode.FAILURE;
response.params.err = 'UNCAUGHT_EXCEPTION';
response.params.errMsg = 'Server Error';
response.params.status = ResponseStatus.failure;
}
} else {
response.responseCode = ResponseCode.FAILURE;
response.params.err = 'INVALID_OTP_USERNAME_PAIR';
response.params.errMsg = 'OTP and Username did not match.';
response.params.status = ResponseStatus.failure;
}
} else {
response.responseCode = ResponseCode.FAILURE;
response.params.err = 'INVALID_USERNAME';
response.params.errMsg = 'No user with this Username exists';
response.params.status = ResponseStatus.failure;
}
return response;
}
async loginWithOtp(loginDto: LoginDto, authHeader: null | string): Promise<SignupResponse> {
/* Execution flow
1. Verify OTP
2. If invalid OTP, throw error; else continue with next steps
3. Check if user exists for the given applicationId.
3.1. If existing user, reset the password.
3.2. If new user, register to this application.
4. Send login response with the token
*/
const salt = this.configResolverService.getSalt(loginDto.applicationId);
let verifyOTPResult;
if(
this.configService.get("ALLOW_DEFAULT_OTP") === 'true' &&
this.configService.get("DEFAULT_OTP_USERS")
){
if(JSON.parse(this.configService.get("DEFAULT_OTP_USERS")).indexOf(loginDto.loginId)!=-1){
if(loginDto.password == this.configService.get("DEFAULT_OTP"))
verifyOTPResult = {status: SMSResponseStatus.success}
else
verifyOTPResult = {status: SMSResponseStatus.failure}
}
} else {
verifyOTPResult = await this.otpService.verifyOTP({
phone: loginDto.loginId,
otp: loginDto.password, // existing OTP
});
}
loginDto.password = salt + loginDto.password; // mix OTP with salt
if (verifyOTPResult.status === SMSResponseStatus.success) {
const {
statusFA,
userId,
user,
}: { statusFA: FAStatus; userId: UUID; user: User } =
await this.fusionAuthService.getUser(
loginDto.loginId,
loginDto.applicationId,
authHeader,
);
if (statusFA === FAStatus.USER_EXISTS) {
let registrationId = null;
if (user.registrations) {
user.registrations.map((item) => {
if (item.applicationId == loginDto.applicationId) {
registrationId = item.id;
}
});
}
// now resetting user's password for the new OTP
await this.updateUser(
userId,
{
password: loginDto.password,
registrations: [
{
applicationId: loginDto.applicationId,
roles: loginDto.roles ?? [],
id: registrationId,
},
],
},
loginDto.applicationId,
authHeader,
);
return this.login(loginDto, authHeader);
} else {
// create a new user
const createUserPayload: UserRegistration = {
user: {
timezone: "Asia/Kolkata",
username: loginDto.loginId,
mobilePhone: loginDto.loginId,
password: loginDto.password
},
registration: {
applicationId: loginDto.applicationId,
preferredLanguages: [
"en"
],
roles: loginDto.roles ?? [], // pass from request body if present, else empty list
}
}
const { userId, user, err }: { userId: UUID; user: User; err: Error } =
await this.fusionAuthService.createAndRegisterUser(
createUserPayload,
loginDto.applicationId,
authHeader,
);
if (userId == null || user == null) {
throw new HttpException(err, HttpStatus.BAD_REQUEST);
}
return this.login(loginDto, authHeader);
}
} else {
const response: SignupResponse = new SignupResponse().init(uuidv4());
response.responseCode = ResponseCode.FAILURE;
response.params.err = 'OTP_VERIFICATION_FAILED';
response.params.errMsg = 'OTP verification failed.';
response.params.status = ResponseStatus.failure;
return response;
}
}
async updateUserRegistration(
applicationId: UUID,
authHeader: null | string,
userId: UUID,
data: FusionAuthUserRegistration,
): Promise<any> {
const {
_userId,
registration,
err,
}: { _userId: UUID; registration: FusionAuthUserRegistration; err: Error } =
await this.fusionAuthService.updateUserRegistration(applicationId, authHeader, userId, data);
if (_userId == null || registration == null) {
throw new HttpException(err, HttpStatus.BAD_REQUEST);
}
return registration;
}
async verifyJwt(token: string): Promise<{ authenticated: boolean; user?: any }> {
try {
const decodedToken = await this.jwksClient.getSigningKey(token);
const signingKey = decodedToken.getPublicKey();
return { authenticated: true, user: decodedToken.payload };
} catch (error) {
console.error('JWT Verification Error:', error);
return { authenticated: false };
}
}
}