cca-auth-module 0.1.54 → 0.1.56

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -129,30 +129,10 @@ var createConfigInstance = /* @__PURE__ */ __name(async () => {
129
129
 
130
130
  // src/infrastructure/container/createAuthContainer.ts
131
131
  import { BaseContainer } from "cca-core";
132
- import { AuthEntity as AuthEntity6 } from "cca-entities";
132
+ import { AuthEntity as AuthEntity5 } from "cca-entities";
133
133
 
134
134
  // src/application/useCase/LoginUseCase.ts
135
135
  import { validateRepository } from "cca-core";
136
- import { UserEntity as UserEntity2 } from "cca-entities";
137
-
138
- // src/application/dtos/UserDTO.ts
139
- import { AutoMap } from "@automapper/classes";
140
- var _UserDTO = class _UserDTO {
141
- };
142
- __name(_UserDTO, "UserDTO");
143
- __decorateClass([
144
- AutoMap()
145
- ], _UserDTO.prototype, "id", 2);
146
- __decorateClass([
147
- AutoMap()
148
- ], _UserDTO.prototype, "name", 2);
149
- __decorateClass([
150
- AutoMap()
151
- ], _UserDTO.prototype, "email", 2);
152
- __decorateClass([
153
- AutoMap()
154
- ], _UserDTO.prototype, "role", 2);
155
- var UserDTO = _UserDTO;
156
136
 
157
137
  // src/application/validators/authValidation.ts
158
138
  import * as yup from "yup";
@@ -247,6 +227,73 @@ var validateAdminSecret = /* @__PURE__ */ __name(async (secretPassword) => {
247
227
  }
248
228
  }, "validateAdminSecret");
249
229
 
230
+ // src/application/useCase/LoginUseCase.ts
231
+ var _LoginUseCase = class _LoginUseCase {
232
+ constructor(repository) {
233
+ this.repository = repository;
234
+ }
235
+ async initialize() {
236
+ await validateRepository(this.repository, (repo) => repo.getAll());
237
+ }
238
+ async execute(loginDTO) {
239
+ const auth = await this.validateLogin(loginDTO);
240
+ return auth.user.id;
241
+ }
242
+ async validateLogin(loginDTO) {
243
+ const auth = await validateLoginDTO(loginDTO, this.repository);
244
+ return auth;
245
+ }
246
+ };
247
+ __name(_LoginUseCase, "LoginUseCase");
248
+ var LoginUseCase = _LoginUseCase;
249
+
250
+ // src/application/useCase/LoginAdminUseCase.ts
251
+ import { validateRepository as validateRepository2 } from "cca-core";
252
+ var _LoginAdminUseCase = class _LoginAdminUseCase {
253
+ constructor(repository) {
254
+ this.repository = repository;
255
+ }
256
+ async initialize() {
257
+ await validateRepository2(this.repository, (repo) => repo.getAll());
258
+ }
259
+ async execute(loginDTO, adminPassword) {
260
+ const auth = await this.validateLogin(loginDTO, adminPassword);
261
+ return auth.user.id;
262
+ }
263
+ async validateLogin(loginDTO, adminPassword) {
264
+ const auth = await validateLoginDTO(loginDTO, this.repository);
265
+ await validateAdminSecret(adminPassword);
266
+ return auth;
267
+ }
268
+ };
269
+ __name(_LoginAdminUseCase, "LoginAdminUseCase");
270
+ var LoginAdminUseCase = _LoginAdminUseCase;
271
+
272
+ // src/application/useCase/LogoutUseCase.ts
273
+ import { validateRepository as validateRepository3 } from "cca-core";
274
+ var _LogoutUseCase = class _LogoutUseCase {
275
+ constructor(repository) {
276
+ this.repository = repository;
277
+ }
278
+ async initialize() {
279
+ await validateRepository3(this.repository, (repo) => repo.getAll());
280
+ }
281
+ async execute(authId) {
282
+ try {
283
+ await this.repository.logout(authId);
284
+ } catch (error) {
285
+ new NotFoundError("Auth not found");
286
+ }
287
+ }
288
+ };
289
+ __name(_LogoutUseCase, "LogoutUseCase");
290
+ var LogoutUseCase = _LogoutUseCase;
291
+
292
+ // src/application/useCase/RegisterUseCase.ts
293
+ import { validateRepository as validateRepository4 } from "cca-core";
294
+ import * as bcrypt2 from "bcrypt";
295
+ import { AuthEntity as AuthEntity3, UserEntity as UserEntity2, UserRole as UserRole2 } from "cca-entities";
296
+
250
297
  // src/application/mappers/utils/mapper.ts
251
298
  import { createMapper } from "@automapper/core";
252
299
  import { classes } from "@automapper/classes";
@@ -261,6 +308,25 @@ var _RegisterDTO = class _RegisterDTO {
261
308
  __name(_RegisterDTO, "RegisterDTO");
262
309
  var RegisterDTO = _RegisterDTO;
263
310
 
311
+ // src/application/dtos/UserDTO.ts
312
+ import { AutoMap } from "@automapper/classes";
313
+ var _UserDTO = class _UserDTO {
314
+ };
315
+ __name(_UserDTO, "UserDTO");
316
+ __decorateClass([
317
+ AutoMap()
318
+ ], _UserDTO.prototype, "id", 2);
319
+ __decorateClass([
320
+ AutoMap()
321
+ ], _UserDTO.prototype, "name", 2);
322
+ __decorateClass([
323
+ AutoMap()
324
+ ], _UserDTO.prototype, "email", 2);
325
+ __decorateClass([
326
+ AutoMap()
327
+ ], _UserDTO.prototype, "role", 2);
328
+ var UserDTO = _UserDTO;
329
+
264
330
  // src/application/dtos/AdminDTO.ts
265
331
  import { AutoMap as AutoMap2 } from "@automapper/classes";
266
332
  var _AdminDTO = class _AdminDTO {
@@ -322,127 +388,7 @@ var mapper = createMapper({
322
388
  });
323
389
  createUserMappings(mapper);
324
390
 
325
- // src/application/useCase/LoginUseCase.ts
326
- var _LoginUseCase = class _LoginUseCase {
327
- constructor(repository, authService) {
328
- this.repository = repository;
329
- this.authService = authService;
330
- }
331
- async initialize() {
332
- await validateRepository(this.repository, (repo) => repo.getAll());
333
- }
334
- async execute(loginDTO) {
335
- const auth = await this.validateLogin(loginDTO);
336
- const token = await this.handleAuthentication(auth);
337
- const userDTO = this.mapUserToDTO(auth.user);
338
- return { token, user: userDTO };
339
- }
340
- async validateLogin(loginDTO) {
341
- const auth = await validateLoginDTO(loginDTO, this.repository);
342
- return auth;
343
- }
344
- async handleAuthentication(auth) {
345
- const token = this.generateTokens(auth);
346
- await this.updateUserStatus(auth);
347
- await this.updateUserRefreshToken(auth, token.refreshToken);
348
- return token;
349
- }
350
- generateTokens(auth) {
351
- return {
352
- accessToken: this.authService.generateAccessToken(auth.user, auth.role),
353
- refreshToken: this.authService.generateRefreshToken(auth.user)
354
- };
355
- }
356
- async updateUserStatus(auth) {
357
- auth.user.lastLoginAt = /* @__PURE__ */ new Date();
358
- auth.user.isActive = true;
359
- await this.repository.update(auth.id, auth);
360
- }
361
- async updateUserRefreshToken(auth, refreshToken) {
362
- auth.refreshToken = refreshToken;
363
- await this.repository.update(auth.id, { refreshToken });
364
- }
365
- mapUserToDTO(user) {
366
- return mapper.map(user, UserEntity2, UserDTO);
367
- }
368
- };
369
- __name(_LoginUseCase, "LoginUseCase");
370
- var LoginUseCase = _LoginUseCase;
371
-
372
- // src/application/useCase/LoginAdminUseCase.ts
373
- import { validateRepository as validateRepository2 } from "cca-core";
374
- import { AdminEntity as AdminEntity2 } from "cca-entities";
375
- var _LoginAdminUseCase = class _LoginAdminUseCase {
376
- constructor(repository, authService) {
377
- this.repository = repository;
378
- this.authService = authService;
379
- }
380
- async initialize() {
381
- await validateRepository2(this.repository, (repo) => repo.getAll());
382
- }
383
- async execute(loginDTO, adminPassword) {
384
- const auth = await this.validateLogin(loginDTO, adminPassword);
385
- const token = await this.handleAuthentication(auth);
386
- const userDTO = this.mapUserToDTO(auth.admin);
387
- return { token, user: userDTO };
388
- }
389
- async validateLogin(loginDTO, adminPassword) {
390
- const auth = await validateLoginDTO(loginDTO, this.repository);
391
- await validateAdminSecret(adminPassword);
392
- return auth;
393
- }
394
- async handleAuthentication(auth) {
395
- const token = this.generateTokens(auth);
396
- await this.updateUserStatus(auth);
397
- await this.updateUserRefreshToken(auth, token.refreshToken);
398
- return token;
399
- }
400
- generateTokens(auth) {
401
- return {
402
- accessToken: this.authService.generateAccessToken(auth.admin, auth.role),
403
- refreshToken: this.authService.generateRefreshToken(auth.admin)
404
- };
405
- }
406
- async updateUserStatus(auth) {
407
- auth.admin.lastLoginAt = /* @__PURE__ */ new Date();
408
- auth.admin.isActive = true;
409
- await this.repository.update(auth.id, auth);
410
- }
411
- async updateUserRefreshToken(auth, refreshToken) {
412
- auth.refreshToken = refreshToken;
413
- await this.repository.update(auth.id, { refreshToken });
414
- }
415
- mapUserToDTO(admin) {
416
- return mapper.map(admin, AdminEntity2, AdminDTO);
417
- }
418
- };
419
- __name(_LoginAdminUseCase, "LoginAdminUseCase");
420
- var LoginAdminUseCase = _LoginAdminUseCase;
421
-
422
- // src/application/useCase/LogoutUseCase.ts
423
- import { validateRepository as validateRepository3 } from "cca-core";
424
- var _LogoutUseCase = class _LogoutUseCase {
425
- constructor(repository) {
426
- this.repository = repository;
427
- }
428
- async initialize() {
429
- await validateRepository3(this.repository, (repo) => repo.getAll());
430
- }
431
- async execute(authId) {
432
- try {
433
- await this.repository.logout(authId);
434
- } catch (error) {
435
- new NotFoundError("Auth not found");
436
- }
437
- }
438
- };
439
- __name(_LogoutUseCase, "LogoutUseCase");
440
- var LogoutUseCase = _LogoutUseCase;
441
-
442
391
  // src/application/useCase/RegisterUseCase.ts
443
- import { validateRepository as validateRepository4 } from "cca-core";
444
- import * as bcrypt2 from "bcrypt";
445
- import { AuthEntity as AuthEntity5, UserEntity as UserEntity3, UserRole as UserRole3 } from "cca-entities";
446
392
  var _RegisterUseCase = class _RegisterUseCase {
447
393
  constructor(repository) {
448
394
  this.SALT_ROUNDS = 10;
@@ -451,7 +397,7 @@ var _RegisterUseCase = class _RegisterUseCase {
451
397
  async initialize() {
452
398
  await validateRepository4(this.repository, (repo) => repo.getAll());
453
399
  }
454
- async execute(email, name, password, role = UserRole3.GUEST, adminPassword) {
400
+ async execute(email, name, password, role = UserRole2.GUEST, adminPassword) {
455
401
  try {
456
402
  const normalizedDTO = this.normalizeAuthDTO({
457
403
  email,
@@ -460,7 +406,7 @@ var _RegisterUseCase = class _RegisterUseCase {
460
406
  role,
461
407
  adminPassword
462
408
  });
463
- if (role === UserRole3.ADMIN && adminPassword) {
409
+ if (role === UserRole2.ADMIN && adminPassword) {
464
410
  await validateAdminSecret(adminPassword);
465
411
  }
466
412
  await validateRegisterDTO(normalizedDTO, this.repository);
@@ -487,8 +433,8 @@ var _RegisterUseCase = class _RegisterUseCase {
487
433
  return await bcrypt2.hash(password, this.SALT_ROUNDS);
488
434
  }
489
435
  async createAuthEntity(dto, hashedPassword) {
490
- const authEntity = mapper.map(dto, RegisterDTO, AuthEntity5);
491
- const userEntity = mapper.map(dto, RegisterDTO, UserEntity3);
436
+ const authEntity = mapper.map(dto, RegisterDTO, AuthEntity3);
437
+ const userEntity = mapper.map(dto, RegisterDTO, UserEntity2);
492
438
  authEntity.password = hashedPassword;
493
439
  authEntity.refreshToken = "";
494
440
  authEntity.user = userEntity;
@@ -512,23 +458,34 @@ var _RefreshTokenUseCase = class _RefreshTokenUseCase {
512
458
  async execute(refreshToken) {
513
459
  try {
514
460
  const decoded = await this.service.verifyRefreshToken(refreshToken);
515
- const auth = decoded.userId ? await this.repository.findById(decoded.userId) : null;
516
- if (!auth || auth.refreshToken !== refreshToken) {
461
+ const user = decoded.userId ? await this.repository.findById(decoded.userId) : null;
462
+ if (!user) {
463
+ console.error("User not found for id:", decoded.userId);
517
464
  return null;
518
465
  }
519
- const accessToken = this.service.generateAccessToken(auth.user, auth.role);
520
- const newRefreshToken = this.service.generateRefreshToken(auth.user);
521
- await this.repository.update(auth.id, {
522
- refreshToken: newRefreshToken
523
- });
466
+ console.log("User entity found with role:", user.role);
467
+ let authEntity = null;
468
+ if (user.role === "user" && user.user) {
469
+ authEntity = await this.repository.findByUseAdminId(user.user.id);
470
+ } else if (user.role === "admin" && user.admin) {
471
+ authEntity = await this.repository.findByUseAdminId(user.admin.id, true);
472
+ } else {
473
+ console.error("User role not recognized or missing relations:", user.role);
474
+ return null;
475
+ }
476
+ if (!authEntity || authEntity.refreshToken !== refreshToken) {
477
+ console.error("Invalid refresh token or auth entity not found.");
478
+ return null;
479
+ }
480
+ const accessToken = this.service.generateAccessToken(user.user, authEntity.role);
481
+ const newRefreshToken = this.service.generateRefreshToken(authEntity.user);
482
+ await this.repository.update(authEntity.id, { refreshToken: newRefreshToken });
524
483
  return { accessToken, refreshToken: newRefreshToken };
525
484
  } catch (error) {
485
+ console.error("Error in refresh token process:", error);
526
486
  return null;
527
487
  }
528
488
  }
529
- async verityToken(token) {
530
- return await this.service.verifyAccessToken(token);
531
- }
532
489
  };
533
490
  __name(_RefreshTokenUseCase, "RefreshTokenUseCase");
534
491
  var RefreshTokenUseCase = _RefreshTokenUseCase;
@@ -610,12 +567,13 @@ var TwoFactorEnableUseCase = _TwoFactorEnableUseCase;
610
567
 
611
568
  // src/application/useCase/TwoFactorVerifyUseCase.ts
612
569
  import { validateRepository as validateRepository7 } from "cca-core";
570
+ import { AdminEntity as AdminEntity2, UserEntity as UserEntity3 } from "cca-entities";
613
571
  var _TwoFactorVerifyUseCase = class _TwoFactorVerifyUseCase {
614
572
  constructor(twoFactorService, authRepository, jwtService) {
615
- this.isInitialized = false;
616
573
  this.twoFactorService = twoFactorService;
617
574
  this.authRepository = authRepository;
618
575
  this.jwtService = jwtService;
576
+ this.isInitialized = false;
619
577
  }
620
578
  async initialize() {
621
579
  if (this.isInitialized) return;
@@ -624,7 +582,6 @@ var _TwoFactorVerifyUseCase = class _TwoFactorVerifyUseCase {
624
582
  this.jwtService.initialize(),
625
583
  validateRepository7(this.authRepository, (repo) => repo.getAll())
626
584
  ]);
627
- 4;
628
585
  this.isInitialized = true;
629
586
  }
630
587
  async execute(dto) {
@@ -633,18 +590,53 @@ var _TwoFactorVerifyUseCase = class _TwoFactorVerifyUseCase {
633
590
  }
634
591
  const { userId, token } = dto;
635
592
  if (!userId || !token) {
636
- throw new TwoFactorError("user ID and token are required");
593
+ throw new TwoFactorError("User ID and token are required.");
637
594
  }
638
595
  const auth = await this.authRepository.findByUserId(userId);
639
596
  if (!auth || !auth.twoFactorSecret || !auth.twoFactorEnabled) {
640
- throw new TwoFactorError("Invalid request");
597
+ throw new TwoFactorError("Invalid request.");
641
598
  }
642
599
  const isValid = this.twoFactorService.verifyToken(token, auth.twoFactorSecret);
643
600
  if (!isValid) {
644
- throw new TwoFactorError("Invalid verification code");
601
+ throw new TwoFactorError("Invalid verification code.");
645
602
  }
603
+ const tokenPair = this.generateTokens(auth);
604
+ await this.updateUserStatus(auth);
605
+ await this.updateUserRefreshToken(auth, tokenPair.refreshToken);
606
+ if (auth.admin) {
607
+ return {
608
+ token: tokenPair.accessToken,
609
+ refreshToken: tokenPair.refreshToken,
610
+ data: this.mapAdminToDTO(auth.admin)
611
+ };
612
+ }
613
+ if (auth.user) {
614
+ return {
615
+ token: tokenPair.accessToken,
616
+ refreshToken: tokenPair.refreshToken,
617
+ data: this.mapUserToDTO(auth.user)
618
+ };
619
+ }
620
+ return null;
621
+ }
622
+ mapAdminToDTO(admin) {
623
+ return mapper.map(admin, AdminEntity2, AdminDTO);
624
+ }
625
+ mapUserToDTO(user) {
626
+ return mapper.map(user, UserEntity3, UserDTO);
627
+ }
628
+ async updateUserStatus(auth) {
629
+ auth.user.lastLoginAt = /* @__PURE__ */ new Date();
630
+ auth.user.isActive = true;
631
+ await this.authRepository.update(auth.id, auth);
632
+ }
633
+ async updateUserRefreshToken(auth, refreshToken) {
634
+ auth.refreshToken = refreshToken;
635
+ await this.authRepository.update(auth.id, { refreshToken });
636
+ }
637
+ generateTokens(auth) {
646
638
  return {
647
- token: this.jwtService.generateAccessToken(auth.user, auth.role),
639
+ accessToken: this.jwtService.generateAccessToken(auth.user, auth.role),
648
640
  refreshToken: this.jwtService.generateRefreshToken(auth.user)
649
641
  };
650
642
  }
@@ -694,8 +686,16 @@ var _AuthController = class _AuthController {
694
686
  this.login = /* @__PURE__ */ __name(async (req, res, next) => {
695
687
  try {
696
688
  const { adminPassword, ...loginDTO } = req.body;
697
- const result = await this.loginUseCase.execute(loginDTO);
698
- res.status(201).json(result);
689
+ const id = await this.loginUseCase.execute(loginDTO);
690
+ res.status(201).json(
691
+ {
692
+ status: "pending",
693
+ message: "Enter 2FA code",
694
+ data: {
695
+ userId: id
696
+ }
697
+ }
698
+ );
699
699
  } catch (error) {
700
700
  next(error);
701
701
  }
@@ -724,6 +724,7 @@ var _AuthController = class _AuthController {
724
724
  try {
725
725
  const { email, name, password, role, adminPassword } = req.body;
726
726
  await this.registerUseCase.execute(email, name, password, role, adminPassword);
727
+ res.status(200).json({ status: "success" });
727
728
  } catch (error) {
728
729
  next(error);
729
730
  }
@@ -733,9 +734,6 @@ var _AuthController = class _AuthController {
733
734
  const result = await this.refreshTokenUseCase.execute(refreshToken);
734
735
  res.json(result);
735
736
  }, "refreshToken");
736
- this.verifyToken = /* @__PURE__ */ __name(async (token) => {
737
- return await this.refreshTokenUseCase.verityToken(token);
738
- }, "verifyToken");
739
737
  this.setup2FA = /* @__PURE__ */ __name(async (req, res, next) => {
740
738
  try {
741
739
  const userId = req.auth.id;
@@ -772,7 +770,10 @@ var _AuthController = class _AuthController {
772
770
  const userId = req.auth.id;
773
771
  const dto = req.body;
774
772
  await this.twoFactorDisableUseCase.execute(userId, dto);
775
- res.status(200).json({ message: "Two-factor authentication has been disabled successfully" });
773
+ res.status(200).json({
774
+ status: "success",
775
+ message: "Two-factor authentication has been disabled successfully"
776
+ });
776
777
  } catch (error) {
777
778
  next(error);
778
779
  }
@@ -838,6 +839,15 @@ var _AuthRepository = class _AuthRepository extends BaseRepository {
838
839
  return await query.getOne();
839
840
  ;
840
841
  }
842
+ async findByUseAdminId(userId, isAdmin = false) {
843
+ const query = this.repository.createQueryBuilder("auth").addSelect("auth.twoFactorSecret");
844
+ if (isAdmin) {
845
+ query.leftJoinAndSelect("auth.admin", "admin").where("admin.id = :userId", { userId });
846
+ } else {
847
+ query.leftJoinAndSelect("auth.user", "user").where("user.id = :userId", { userId });
848
+ }
849
+ return await query.getOne();
850
+ }
841
851
  async logout(userId) {
842
852
  const auth = await this.findByUserId(userId);
843
853
  if (!auth) {
@@ -1057,7 +1067,7 @@ var TwoFactorService = _TwoFactorService;
1057
1067
  async function createAuthContainer(database) {
1058
1068
  const container = new BaseContainer({ database });
1059
1069
  const authRepository = new AuthRepository(
1060
- database.getRepository(AuthEntity6)
1070
+ database.getRepository(AuthEntity5)
1061
1071
  );
1062
1072
  container.registerRepository("AuthRepository", authRepository);
1063
1073
  const jwtAuthService = new JwtAuthService(authRepository);
@@ -1066,10 +1076,9 @@ async function createAuthContainer(database) {
1066
1076
  const twoFactorService = new TwoFactorService(configData);
1067
1077
  container.registerService("TwoFactorService", twoFactorService);
1068
1078
  const requireComplete2FA = new RequireComplete2FA(jwtAuthService);
1069
- const loginUseCase = new LoginUseCase(authRepository, jwtAuthService);
1079
+ const loginUseCase = new LoginUseCase(authRepository);
1070
1080
  const loginAdminUseCase = new LoginAdminUseCase(
1071
- authRepository,
1072
- jwtAuthService
1081
+ authRepository
1073
1082
  );
1074
1083
  const logoutUseCase = new LogoutUseCase(authRepository);
1075
1084
  const registerUseCase = new RegisterUseCase(authRepository);