ngx-sp-auth 4.22.8 → 4.22.13

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.
@@ -5,13 +5,13 @@ import { HTTP_INTERCEPTORS, HttpHeaders, HttpClient, HttpParams, HttpResponse }
5
5
  import * as i1$2 from '@azure/msal-angular';
6
6
  import { MsalInterceptor, MsalGuard, MsalModule, MSAL_GUARD_CONFIG } from '@azure/msal-angular';
7
7
  import { LogLevel, PublicClientApplication, InteractionType } from '@azure/msal-browser';
8
- import { take as take$1, tap as tap$1, map, switchMap as switchMap$1 } from 'rxjs/operators';
8
+ import { take as take$1, tap as tap$1, map as map$1, switchMap as switchMap$1 } from 'rxjs/operators';
9
9
  import * as i1$1 from '@angular/router';
10
10
  import { RouterLink, NavigationEnd, RouterOutlet } from '@angular/router';
11
- import { BehaviorSubject, firstValueFrom, take, tap, Subject, Subscription, debounceTime, distinctUntilChanged, filter, switchMap, timer, map as map$1, of, lastValueFrom, from, catchError, throwError } from 'rxjs';
11
+ import { BehaviorSubject, map, catchError, of, finalize, shareReplay, take, tap, firstValueFrom, Subject, Subscription, debounceTime, distinctUntilChanged, filter, switchMap, timer, lastValueFrom, from, throwError } from 'rxjs';
12
+ import { openDB, deleteDB } from 'idb';
12
13
  import * as i3 from 'ngx-sp-infra';
13
14
  import { Utils, SearchInputComponent, InfraModule, FormUtils, Usuario, RetPasswordPolicy, RetCheckPassword, CheckPasswordRecord, PasswordPolicyComponent, LibIconsComponent, ContentContainerComponent } from 'ngx-sp-infra';
14
- import { openDB, deleteDB } from 'idb';
15
15
  import * as i17 from '@angular/common';
16
16
  import { NgIf, CommonModule, NgClass } from '@angular/common';
17
17
  import * as i7 from '@angular/forms';
@@ -590,12 +590,14 @@ class AuthStorageService {
590
590
  this._router = _router;
591
591
  this._BASE_URL = ''; // SpInfra2LoginWS
592
592
  this._LOGOUT_BASE_URL = ''; // SpInfra2LoginWS
593
+ this._BASE_VERIFICATION_URL = ''; // SpInfra2LoginWS
593
594
  this._HTTP_HEADERS = new HttpHeaders().set('Content-Type', 'application/json');
594
595
  this.__local_key = 'user_auth_v6';
595
596
  // indica se objeto já está marcado para salvar os dados no local storage.
596
597
  this.__isSaving = false;
597
598
  /** Se ainda estamos com uma função rodando para verificar o login do usuário */
598
599
  this.__isCheckingAuth = false;
600
+ this.__authenticationCheck$ = null;
599
601
  // #region GETTERS/SETTERS
600
602
  this.isLoggedInSub = new BehaviorSubject(false);
601
603
  //ip
@@ -616,8 +618,31 @@ class AuthStorageService {
616
618
  this.__user = "";
617
619
  //username
618
620
  this.__userName = "";
621
+ //tokenPayload
622
+ // private __tokenPayload!: Payload;
623
+ // public get tokenPayload(): Payload {
624
+ // return this.__tokenPayload;
625
+ // }
626
+ // public set tokenPayload(value: Payload) {
627
+ // this.__tokenPayload = value;
628
+ // this.__saveLocalInstance();
629
+ // }
619
630
  //authToken
620
- this.__authToken = "";
631
+ // private __authToken: string = "";
632
+ // public get authToken(): string {
633
+ // return this.__authToken;
634
+ // }
635
+ // public set authToken(value: string) {
636
+ // this.__authToken = value;
637
+ // if (this.__authToken != '') {
638
+ // // Utiliza-se a função dos Utils para pegar o segundo valor do Token, separados por um '.'
639
+ // // e define o __tokenPayload como o objeto resultante do JSON.parse(payloadJson)
640
+ // const payloadJson: string = Utils.b64DecodeUnicode(this.__authToken.split('.')[1]);
641
+ // this.__tokenPayload = JSON.parse(payloadJson);
642
+ // this.startLoginCheck();
643
+ // }
644
+ // this.__saveLocalInstance();
645
+ // }
621
646
  /** Domínio */
622
647
  this.__dominio = "";
623
648
  //url para redirecionamento
@@ -640,7 +665,9 @@ class AuthStorageService {
640
665
  this._BASE_URL = `${_customEnvironmentService.SpInfra2LoginWS}/LoginSisproERP`; // SpInfra2LoginWS
641
666
  this._BASE_URL = !_customEnvironmentService.production ? this._BASE_URL : `${_customEnvironmentService.SpInfra2LoginWS}/LoginSisproERP`; // SpInfra2LoginWS
642
667
  this._LOGOUT_BASE_URL = `${_customEnvironmentService.SpInfra2LoginWS}/LogoutSisproErp`; // SpInfra2LoginWS
643
- this._BASE_URL = !_customEnvironmentService.production ? this._BASE_URL : `${_customEnvironmentService.SpInfra2LoginWS}/LogoutSisproErp`; // SpInfra2LoginWS
668
+ this._LOGOUT_BASE_URL = !_customEnvironmentService.production ? this._LOGOUT_BASE_URL : `${_customEnvironmentService.SpInfra2LoginWS}/LogoutSisproErp`; // SpInfra2LoginWS
669
+ this._BASE_VERIFICATION_URL = `${_customEnvironmentService.SpInfra2LoginWS}/verify`; // SpInfra2LoginWS
670
+ this._BASE_VERIFICATION_URL = !_customEnvironmentService.production ? this._BASE_VERIFICATION_URL : `${_customEnvironmentService.SpInfra2LoginWS}/verify`; // SpInfra2LoginWS
644
671
  // Método com customizações para inicializações da storage
645
672
  this._customStorageService.storageConstructor();
646
673
  const expectedLocalAuthStorage = localStorage.getItem(this.__local_key);
@@ -656,8 +683,8 @@ class AuthStorageService {
656
683
  this.__infraEmpresaNome = localAuthStorage.__infraEmpresaNome;
657
684
  this.__user = localAuthStorage.__user;
658
685
  this.__userName = localAuthStorage.__userName;
659
- this.__tokenPayload = localAuthStorage.__tokenPayload;
660
- this.__authToken = localAuthStorage.__authToken;
686
+ // this.__tokenPayload = localAuthStorage.__tokenPayload;
687
+ // this.__authToken = localAuthStorage.__authToken;
661
688
  this.__dominio = localAuthStorage.__dominio;
662
689
  this.__isExternalLogin = localAuthStorage.__isExternalLogin;
663
690
  this.__infraInAuthTypeId = localAuthStorage.__infraInAuthTypeId;
@@ -738,27 +765,6 @@ class AuthStorageService {
738
765
  this.__userName = value;
739
766
  this.__saveLocalInstance();
740
767
  }
741
- get tokenPayload() {
742
- return this.__tokenPayload;
743
- }
744
- set tokenPayload(value) {
745
- this.__tokenPayload = value;
746
- this.__saveLocalInstance();
747
- }
748
- get authToken() {
749
- return this.__authToken;
750
- }
751
- set authToken(value) {
752
- this.__authToken = value;
753
- if (this.__authToken != '') {
754
- // Utiliza-se a função dos Utils para pegar o segundo valor do Token, separados por um '.'
755
- // e define o __tokenPayload como o objeto resultante do JSON.parse(payloadJson)
756
- const payloadJson = Utils.b64DecodeUnicode(this.__authToken.split('.')[1]);
757
- this.__tokenPayload = JSON.parse(payloadJson);
758
- this.startLoginCheck();
759
- }
760
- this.__saveLocalInstance();
761
- }
762
768
  get dominio() {
763
769
  return this.__dominio;
764
770
  }
@@ -850,8 +856,7 @@ class AuthStorageService {
850
856
  "__infraEmpresaNome": "${this.infraEmpresaNome}",
851
857
  "__user": "${this.user}",
852
858
  "__userName": "${this.userName}",
853
- "__authToken": "${this.authToken}",
854
- "__tokenPayload": ${JSON.stringify(this.tokenPayload)},
859
+
855
860
  "__dominio": "${this.dominio}",
856
861
  "__isExternalLogin": ${this.isExternalLogin},
857
862
  "__infraInAuthTypeId": ${this.infraInAuthTypeId},
@@ -866,53 +871,77 @@ class AuthStorageService {
866
871
  /** Inicia a verificação do login. */
867
872
  startLoginCheck() {
868
873
  if (!this.__isCheckingAuth) {
869
- // ERICK: Chamada do método custom movida para cá para chamar uma única vez ao invés de se repetir a cada validação do token no método reCheckLogin,
870
- // visto que o método storageInitializeAutoStorage tem como objetivo realizar inicializações diversas quando o Login é executado via Pré Portal,
871
- // e não há necessidade de repetir essas inicializações a cada verificação do token.
872
- this._customStorageService.storageInitializeAutoStorage(); // Método com customizações para inicializações da AutoStorage
873
- this.reCheckLogin(false);
874
+ this.checkAuthentication().subscribe((isLoggedIn) => {
875
+ if (isLoggedIn) {
876
+ // ERICK: Chamada do método custom movida para cá para chamar uma única vez ao invés de se repetir a cada validação do token no método reCheckLogin,
877
+ // visto que o método storageInitializeAutoStorage tem como objetivo realizar inicializações diversas quando o Login é executado via Pré Portal,
878
+ // e não há necessidade de repetir essas inicializações a cada verificação do token.
879
+ this._customStorageService.storageInitializeAutoStorage(); // Método com customizações para inicializações da AutoStorage
880
+ // this.reCheckLogin(false);
881
+ }
882
+ });
874
883
  }
875
884
  }
876
- /** Verifica a cada diferença de tempo entre a data atual e a data do token. */
877
- async reCheckLogin(renew) {
878
- if (this.__authToken === undefined || this.__authToken === '' || this.authToken === null || this.authToken === '') {
879
- this.__isCheckingAuth = false;
880
- return;
881
- }
882
- this.__isCheckingAuth = true;
883
- let isRenewToken = false;
884
- let nowDate = Math.round(Date.now() / 1000);
885
- if (this.tokenPayload.exp <= nowDate) {
886
- isRenewToken = true;
887
- }
888
- let leftTime = this.tokenPayload.exp - nowDate;
889
- if (leftTime <= 0) {
890
- isRenewToken = true;
891
- }
892
- // Se o token estiver expirado ou prestes a expirar, tenta renovar o token. Se não conseguir renovar, desloga o usuário.
893
- if (isRenewToken) {
894
- // Se o token não deve ser renovado, desloga o usuário. Caso contrário, tenta renovar o token. Se não conseguir renovar, desloga o usuário.
895
- if (!renew) {
896
- this.logout();
897
- return;
898
- }
899
- const response = await this.getNewToken();
900
- if (response !== undefined && response !== null && response != '') {
901
- this.authToken = response;
902
- nowDate = Math.round(Date.now() / 1000);
903
- leftTime = this.tokenPayload.exp - nowDate;
904
- }
905
- else {
906
- this.logout();
907
- return;
908
- }
885
+ checkAuthentication() {
886
+ if (!this.__authenticationCheck$) {
887
+ this.__authenticationCheck$ = this.verifyToken()
888
+ .pipe(map((response) => !response.Error), catchError(() => {
889
+ this.isLoggedInSub.next(false);
890
+ return of(false);
891
+ }), finalize(() => this.__authenticationCheck$ = null), shareReplay({ bufferSize: 1, refCount: true }));
909
892
  }
910
- if (this.ignoreCheckLogin)
911
- this.ignoreCheckLogin = false;
912
- this.isLoggedInSub.next(true);
913
- // Chama a si próprio depois de um tempo igual ao tempo restante para o vencimento do token, para renovar o token ou deslogar o usuário.
914
- setTimeout(this.reCheckLogin.bind(this, true), leftTime * 1000);
893
+ return this.__authenticationCheck$;
894
+ }
895
+ verifyToken() {
896
+ const url = `${this._BASE_VERIFICATION_URL}`;
897
+ const headers = this._HTTP_HEADERS;
898
+ return this._httpClient.get(url, { 'headers': headers, withCredentials: true })
899
+ .pipe(take(1), tap(res => {
900
+ console.log(res);
901
+ if (res.Error)
902
+ this.isLoggedInSub.next(false);
903
+ else
904
+ this.isLoggedInSub.next(true);
905
+ }));
915
906
  }
907
+ /** Verifica a cada diferença de tempo entre a data atual e a data do token. */
908
+ // public async reCheckLogin(renew: boolean) {
909
+ // if (this.__authToken === undefined || this.__authToken === '' || this.authToken === null || this.authToken === '') {
910
+ // this.__isCheckingAuth = false;
911
+ // return;
912
+ // }
913
+ // this.__isCheckingAuth = true;
914
+ // let isRenewToken: boolean = false;
915
+ // let nowDate: number = Math.round(Date.now() / 1000);
916
+ // if (this.tokenPayload.exp <= nowDate) {
917
+ // isRenewToken = true;
918
+ // }
919
+ // let leftTime: number = this.tokenPayload.exp - nowDate
920
+ // if (leftTime <= 0) {
921
+ // isRenewToken = true;
922
+ // }
923
+ // // Se o token estiver expirado ou prestes a expirar, tenta renovar o token. Se não conseguir renovar, desloga o usuário.
924
+ // if (isRenewToken) {
925
+ // // Se o token não deve ser renovado, desloga o usuário. Caso contrário, tenta renovar o token. Se não conseguir renovar, desloga o usuário.
926
+ // if (!renew) {
927
+ // this.logout();
928
+ // return;
929
+ // }
930
+ // const response = await this.getNewToken();
931
+ // if (response !== undefined && response !== null && response != '') {
932
+ // this.authToken = response;
933
+ // nowDate = Math.round(Date.now() / 1000);
934
+ // leftTime = this.tokenPayload.exp - nowDate;
935
+ // } else {
936
+ // this.logout();
937
+ // return;
938
+ // }
939
+ // }
940
+ // if (this.ignoreCheckLogin) this.ignoreCheckLogin = false;
941
+ // this.isLoggedInSub.next(true);
942
+ // // Chama a si próprio depois de um tempo igual ao tempo restante para o vencimento do token, para renovar o token ou deslogar o usuário.
943
+ // setTimeout(this.reCheckLogin.bind(this, true), leftTime * 1000);
944
+ // }
916
945
  /**
917
946
  * Realiza o logout do sistema, consumindo o endpoint de logout para remover os cookies e limpando as informações de autenticação armazenadas no localStorage.
918
947
  * @returns Promise<boolean> indicando navegação para a tela de login após o logout.
@@ -946,7 +975,7 @@ class AuthStorageService {
946
975
  domain: this.__dominio,
947
976
  user: this.__user,
948
977
  tenantId: this.tenantId,
949
- token: this.authToken,
978
+ // token: this.authToken,
950
979
  infraUsuarioId: this.__infraUsuarioId,
951
980
  userName: this.__userName
952
981
  };
@@ -976,29 +1005,30 @@ class AuthStorageService {
976
1005
  /**
977
1006
  * Renova o Token quando este estiver vencido.
978
1007
  */
979
- async renewToken() {
980
- if (!this.isLoggedInSub || this.__authToken === undefined || this.__authToken === '' || this.authToken === null || this.authToken === '') {
981
- return;
982
- }
983
- let isRenewToken = false;
984
- let nowDate = Math.round(Date.now() / 1000);
985
- if (this.tokenPayload.exp <= nowDate) {
986
- isRenewToken = true;
987
- }
988
- let leftTime = this.tokenPayload.exp - nowDate;
989
- if (leftTime <= 0) {
990
- isRenewToken = true;
991
- }
992
- if (isRenewToken) {
993
- const response = await this.getNewToken();
994
- if (response !== undefined && response !== null && response != '') {
995
- this.authToken = response;
996
- }
997
- }
998
- }
1008
+ // public async renewToken() {
1009
+ // if (!this.isLoggedInSub || this.__authToken === undefined || this.__authToken === '' || this.authToken === null || this.authToken === '') {
1010
+ // return;
1011
+ // }
1012
+ // let isRenewToken: boolean = false;
1013
+ // let nowDate: number = Math.round(Date.now() / 1000);
1014
+ // if (this.tokenPayload.exp <= nowDate) {
1015
+ // isRenewToken = true;
1016
+ // }
1017
+ // let leftTime: number = this.tokenPayload.exp - nowDate
1018
+ // if (leftTime <= 0) {
1019
+ // isRenewToken = true;
1020
+ // }
1021
+ // if (isRenewToken) {
1022
+ // const response = await this.getNewToken();
1023
+ // if (response !== undefined && response !== null && response != '') {
1024
+ // this.authToken = response;
1025
+ // }
1026
+ // }
1027
+ // }
999
1028
  onLogout() {
1000
1029
  console.log('4.1. Iniciando onLogout() para limpar variáveis de autenticação e redirecionar para a tela de login');
1001
1030
  this.__isCheckingAuth = false;
1031
+ this.__authenticationCheck$ = null;
1002
1032
  this.isLoggedInSub.next(false);
1003
1033
  this.__UrlRedirect = "/";
1004
1034
  this.__ip = "";
@@ -1010,9 +1040,9 @@ class AuthStorageService {
1010
1040
  this.__infraEmpresaNome = "";
1011
1041
  this.__user = "";
1012
1042
  this.__userName = "";
1013
- this.__authToken = "";
1043
+ // this.__authToken = "";
1014
1044
  this.__dominio = "";
1015
- this.__tokenPayload = {};
1045
+ // this.__tokenPayload = {} as Payload;
1016
1046
  this.__isExternalLogin = false;
1017
1047
  this.__infraInAuthTypeId = 0;
1018
1048
  this.__infraIn2FaTypeId = null;
@@ -1234,8 +1264,8 @@ class AuthService {
1234
1264
  }
1235
1265
  // Comentadas pois não serão mais armazenadas desta forma, o webservice gerará um Cookie com o valor já formatado para Base64
1236
1266
  // E o mesmo será enviada nas requisições subsequentes via párâmetro `withCredentials: true`, e não mais via header Authorization
1237
- localStorage.setItem('configServerUser', response.User);
1238
- localStorage.setItem('configServerPassword', response.Password);
1267
+ // localStorage.setItem('configServerUser', response.User);
1268
+ // localStorage.setItem('configServerPassword', response.Password);
1239
1269
  this._authStorageService.tenantId = response.TenantId;
1240
1270
  this._authStorageService.dominio = response.Domain;
1241
1271
  this._authStorageService.infraInAuthTypeId = response.InfraInAuthTypeId;
@@ -1243,7 +1273,7 @@ class AuthService {
1243
1273
  this._authStorageService.is2FaEnabled = response.Is2FaEnabled;
1244
1274
  this._authStorageService.azureTenantId = response.AzureTenantId;
1245
1275
  this._authStorageService.azureClientId = response.AzureClientId;
1246
- this._authStorageService.tokenPayload = {};
1276
+ // this._authStorageService.tokenPayload = {} as Payload;
1247
1277
  }));
1248
1278
  }
1249
1279
  /** Realiza o login no sistema
@@ -1309,7 +1339,7 @@ class AuthService {
1309
1339
  this._authStorageService.infraEmpresaNome = response.NomeEmpresa;
1310
1340
  this._authStorageService.user = login.usuario;
1311
1341
  this._authStorageService.userName = response.UserName;
1312
- this._authStorageService.authToken = response.Token;
1342
+ // this._authStorageService.authToken = response.Token;
1313
1343
  this._authStorageService.dominio = response.Dominio;
1314
1344
  this._authStorageService.isExternalLogin = false;
1315
1345
  // Método com customizações para inicializações do Login
@@ -1366,7 +1396,7 @@ class AuthService {
1366
1396
  this._authStorageService.infraEmpresaNome = response.NomeEmpresa;
1367
1397
  this._authStorageService.user = login.usuario;
1368
1398
  this._authStorageService.userName = response.UserName;
1369
- this._authStorageService.authToken = response.Token;
1399
+ // this._authStorageService.authToken = response.Token;
1370
1400
  this._authStorageService.dominio = response.Dominio;
1371
1401
  this._authStorageService.isExternalLogin = false;
1372
1402
  // Método com customizações para inicializações do Login
@@ -1404,11 +1434,11 @@ class AuthService {
1404
1434
  this._authStorageService.infraEmpresaNome = response.NomeEmpresa;
1405
1435
  this._authStorageService.user = login.usuario;
1406
1436
  this._authStorageService.userName = response.UserName;
1407
- this._authStorageService.authToken = response.Token;
1437
+ // this._authStorageService.authToken = response.Token;
1408
1438
  this._authStorageService.dominio = response.Dominio;
1409
1439
  this._authStorageService.isExternalLogin = true;
1410
1440
  }
1411
- }), map((response) => {
1441
+ }), map$1((response) => {
1412
1442
  return response.Error;
1413
1443
  }));
1414
1444
  }
@@ -1473,7 +1503,7 @@ class AuthService {
1473
1503
  this._authStorageService.infraEmpresaNome = response.NomeEmpresa;
1474
1504
  this._authStorageService.user = login.usuario;
1475
1505
  this._authStorageService.userName = response.UserName;
1476
- this._authStorageService.authToken = response.Token;
1506
+ // this._authStorageService.authToken = response.Token;
1477
1507
  this._authStorageService.dominio = response.Dominio;
1478
1508
  this._authStorageService.isExternalLogin = false;
1479
1509
  }
@@ -1507,7 +1537,7 @@ class AuthService {
1507
1537
  this._authStorageService.infraEmpresaNome = response.NomeEmpresa;
1508
1538
  this._authStorageService.user = this._authStorageService.user;
1509
1539
  this._authStorageService.userName = response.UserName;
1510
- this._authStorageService.authToken = response.Token;
1540
+ // this._authStorageService.authToken = response.Token;
1511
1541
  this._authStorageService.dominio = response.Dominio;
1512
1542
  this._authStorageService.isExternalLogin = false;
1513
1543
  // Método com customizações para inicializações do Login
@@ -2545,7 +2575,7 @@ class LoginComponent {
2545
2575
  this._subscription = new Subscription();
2546
2576
  this.timerDuration = 90;
2547
2577
  this.secondsLeft = this.timerDuration;
2548
- this.countdown$ = timer(0, 1000).pipe(take(this.timerDuration + 1), map$1(secondsElapsed => this.timerDuration - secondsElapsed));
2578
+ this.countdown$ = timer(0, 1000).pipe(take(this.timerDuration + 1), map(secondsElapsed => this.timerDuration - secondsElapsed));
2549
2579
  }
2550
2580
  get situacaoLogin() { return this._situacaoLogin; }
2551
2581
  set situacaoLogin(value) {
@@ -4280,8 +4310,8 @@ class MeuPerfilComponent {
4280
4310
  }
4281
4311
  async ngOnInit() {
4282
4312
  this.usuarioData.Usuario = this._authStorageService.user;
4283
- await this.getPerfil(this._authStorageService.tokenPayload.userId);
4284
- await this.getInfraUsuarioImg(this._authStorageService.tokenPayload.userId);
4313
+ await this.getPerfil(this._authStorageService.infraUsuarioId);
4314
+ await this.getInfraUsuarioImg(this._authStorageService.infraUsuarioId);
4285
4315
  await this.GetPasswordPolicyList();
4286
4316
  await this.GetAdminId();
4287
4317
  this.isLoading = false;
@@ -4483,8 +4513,8 @@ class AuthGuard {
4483
4513
  this.authStorageService = authStorageService;
4484
4514
  }
4485
4515
  IsUserAuth() {
4486
- return this.authStorageService.isLoggedInSub
4487
- .pipe(map((isLoggedIn) => {
4516
+ return this.authStorageService.checkAuthentication()
4517
+ .pipe(map$1((isLoggedIn) => {
4488
4518
  if (!isLoggedIn || this.authStorageService.isExternalLogin) {
4489
4519
  let login = this.router.parseUrl("/auth/login");
4490
4520
  return login;
@@ -4522,14 +4552,16 @@ class ExternaLoginlGuard {
4522
4552
  return login;
4523
4553
  }
4524
4554
  IsUserAuth(param) {
4525
- return this.authStorageService.isLoggedInSub
4526
- .pipe(take$1(1), switchMap$1((isLoggedIn) => {
4555
+ return this.authStorageService.checkAuthentication()
4556
+ .pipe(take$1(1), switchMap$1(() => {
4527
4557
  // Split dos parâmetros para o login externo
4528
4558
  var params = param.split('$');
4529
4559
  let domain = params[0];
4530
4560
  let user = params[1];
4531
4561
  let password = params[2];
4532
- if (isLoggedIn && !this.authStorageService.isExternalLogin && this.authStorageService.dominio.toLowerCase() == domain.toLowerCase()) {
4562
+ if (this.authStorageService.isLoggedInSub.value
4563
+ && !this.authStorageService.isExternalLogin
4564
+ && this.authStorageService.dominio.toLowerCase() == domain.toLowerCase()) {
4533
4565
  return of(true);
4534
4566
  }
4535
4567
  ;
@@ -4666,13 +4698,14 @@ class LoginGuard {
4666
4698
  * @returns
4667
4699
  */
4668
4700
  canLoad(_route, _segments) {
4669
- if (_route.path === "auth/login" && this.authStorageService.isLoggedInSub.value && !this.authStorageService.isExternalLogin) {
4670
- // TODO: Validar se usuário existe e se o domínio é o mesmo, caso contrário, deslogar o usuário e redirecionar para a tela de login
4671
- // Possivelmente usar a mesma lógica do ValidateLogin no backend e a lógica do external-login.guard.ts
4672
- // ...
4673
- return this.router.createUrlTree(["/home"]);
4674
- }
4675
- return true;
4701
+ console.log('route', _route);
4702
+ return this.authStorageService.checkAuthentication()
4703
+ .pipe(map(() => {
4704
+ if ((_route.path === "auth/login" && this.authStorageService.isLoggedInSub.value && !this.authStorageService.isExternalLogin)) {
4705
+ return this.router.createUrlTree(["/home"]);
4706
+ }
4707
+ return true;
4708
+ }));
4676
4709
  }
4677
4710
  static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.25", ngImport: i0, type: LoginGuard, deps: [{ token: i1$1.Router }, { token: AuthStorageService }], target: i0.ɵɵFactoryTarget.Injectable }); }
4678
4711
  static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.25", ngImport: i0, type: LoginGuard, providedIn: 'root' }); }
@@ -4725,14 +4758,11 @@ class AuthAplicInterceptor {
4725
4758
  let changedReq = req;
4726
4759
  if (this._authCheckService.needsAuthRequest(req.url, req.method, this._customEnvironmentService.needsAuthAplic)) {
4727
4760
  // Verifica se o Token precisa ser renovado
4728
- await this._authStorage.renewToken();
4761
+ // await this._authStorage.renewToken();
4729
4762
  // Adiciona as autenticações necessárias ao servidor.
4730
4763
  // Daqui alguns dias este trecho será removido e os tokens serão enviados exclusivamente pelos Cookies, mas por enquanto, para manter compatibilidade com o que já existe, o token será enviado no header
4731
- let headers = req.headers.set('Authorization', `Bearer ${this._authStorage.authToken}`);
4732
- changedReq = req.clone({
4733
- headers: headers,
4734
- //withCredentials: true // Parâmetro necessário para utilização dos Cookies HttpOnly
4735
- });
4764
+ // let headers: HttpHeaders = req.headers.set('Authorization', `Bearer ${this._authStorage.authToken}`);
4765
+ changedReq = req.clone({ headers: req.headers, withCredentials: true });
4736
4766
  }
4737
4767
  // return await lastValueFrom(next.handle(changedReq));
4738
4768
  // Exemplo de leitura de resposta via interceptor abaixo:
@@ -4775,8 +4805,8 @@ class AuthInfraInterceptor {
4775
4805
  `);
4776
4806
  }
4777
4807
  changedReq = req.clone({
4778
- headers: headers,
4779
- //withCredentials: true // Parâmetro necessário para utilização dos Cookies HttpOnly
4808
+ headers: req.headers,
4809
+ withCredentials: true // Parâmetro necessário para utilização dos Cookies HttpOnly
4780
4810
  });
4781
4811
  }
4782
4812
  // return next.handle(changedReq);