ngx-sp-auth 4.23.8 → 4.23.10

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,9 +5,9 @@ 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 as map$1, switchMap as switchMap$1 } from 'rxjs/operators';
8
+ import { take as take$1, tap as tap$1, map as map$1, filter as filter$1, switchMap as switchMap$1 } from 'rxjs/operators';
9
9
  import * as i1$1 from '@angular/router';
10
- import { RouterLink, NavigationEnd, RouterOutlet } from '@angular/router';
10
+ import { RouterLink, NavigationEnd, RouterOutlet, Router, PRIMARY_OUTLET } from '@angular/router';
11
11
  import * as i3 from 'ngx-sp-infra';
12
12
  import { IpServiceService, Utils, SearchInputComponent, InfraModule, FormUtils, Usuario, RetPasswordPolicy, RetCheckPassword, CheckPasswordRecord, PasswordPolicyComponent, LibIconsComponent, ContentContainerComponent } from 'ngx-sp-infra';
13
13
  import * as i10 from 'ngx-toastr';
@@ -807,8 +807,8 @@ class AuthStorageService {
807
807
  /** Inicia a verificação do login. */
808
808
  startLoginCheck() {
809
809
  if (!this.__isCheckingAuth) {
810
- this.checkAuthentication().subscribe((isLoggedIn) => {
811
- if (isLoggedIn) {
810
+ this.checkAuthentication().subscribe((res) => {
811
+ if (res.isLoggedIn) {
812
812
  // 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,
813
813
  // visto que o método storageInitializeAutoStorage tem como objetivo realizar inicializações diversas quando o Login é executado via Pré Portal,
814
814
  // e não há necessidade de repetir essas inicializações a cada verificação do token.
@@ -820,10 +820,14 @@ class AuthStorageService {
820
820
  }
821
821
  checkAuthentication() {
822
822
  if (!this.__authenticationCheck$) {
823
+ let errorMessage = '';
823
824
  this.__authenticationCheck$ = this.verifyToken()
824
- .pipe(map((response) => !response.Error), catchError(() => {
825
+ .pipe(map((response) => {
826
+ errorMessage = response.ErrorMessage;
827
+ return { error: response.ErrorMessage, isLoggedIn: !response.Error };
828
+ }), catchError((err) => {
825
829
  this.isLoggedInSub.next(false);
826
- return of(false);
830
+ return of({ error: err.error.ErrorMessage, isLoggedIn: false });
827
831
  }), finalize(() => this.__authenticationCheck$ = null), shareReplay({ bufferSize: 1, refCount: true }));
828
832
  }
829
833
  return this.__authenticationCheck$;
@@ -832,7 +836,7 @@ class AuthStorageService {
832
836
  const url = `${this._BASE_VERIFICATION_URL}`;
833
837
  const headers = this._HTTP_HEADERS.set('x-application', this._customEnvironmentService.product);
834
838
  return defer(() => {
835
- this._toastr.info('Validando token do usuário.', 'Aguarde...', { timeOut: 3000, progressBar: true, progressAnimation: 'increasing', closeButton: true });
839
+ this._toastr.info('Validando token do usuário.', 'Aguarde...', { disableTimeOut: true, progressBar: true, progressAnimation: 'increasing', closeButton: true });
836
840
  const params = new HttpParams()
837
841
  .set('ip', this.ip)
838
842
  .set('browser', this._ipService.getDataBrowserUser().browser);
@@ -4510,16 +4514,21 @@ i0.ɵɵngDeclareClassMetadataAsync({ minVersion: "18.0.0", version: "19.2.25", n
4510
4514
  }], ctorParameters: () => [{ type: AuthUtilService }, { type: i4.BsModalService }, { type: MenuServicesService }, { type: i3.MessageService }, { type: MeuPerfilService }, { type: i1$1.Router }], propDecorators: null }) });
4511
4515
 
4512
4516
  class AuthGuard {
4513
- constructor(router, authStorageService) {
4514
- this.router = router;
4515
- this.authStorageService = authStorageService;
4517
+ constructor(_router, _authStorage, _message) {
4518
+ this._router = _router;
4519
+ this._authStorage = _authStorage;
4520
+ this._message = _message;
4516
4521
  }
4517
- IsUserAuth() {
4518
- return this.authStorageService.checkAuthentication()
4519
- .pipe(map$1((isLoggedIn) => {
4520
- if (!isLoggedIn || this.authStorageService.isExternalLogin) {
4521
- let login = this.router.parseUrl("/auth/login");
4522
- return login;
4522
+ IsUserAuth(targetUrl = this._router.url) {
4523
+ return this._authStorage.checkAuthentication()
4524
+ .pipe(map$1(({ error, isLoggedIn }) => {
4525
+ if (!isLoggedIn || this._authStorage.isExternalLogin) {
4526
+ const targetPath = targetUrl.split(/[?#]/, 1)[0].replace(/\/+$/, '').toLowerCase();
4527
+ if (error.trim() && (targetPath !== '/auth/login' && targetPath !== '')) {
4528
+ this._router.events.pipe(filter$1((event) => event instanceof NavigationEnd), filter$1(event => event.urlAfterRedirects.split(/[?#]/, 1)[0] === '/auth/login'), take$1(1))
4529
+ .subscribe(() => this._message.showAlertWarning(error));
4530
+ }
4531
+ return this._router.parseUrl('/auth/login');
4523
4532
  }
4524
4533
  return true;
4525
4534
  }));
@@ -4528,21 +4537,21 @@ class AuthGuard {
4528
4537
  if (segments[0]?.path.toLowerCase() === 'auth') {
4529
4538
  return of(false);
4530
4539
  }
4531
- return this.IsUserAuth();
4540
+ return this.IsUserAuth(`/${segments.map(segment => segment.path).join('/')}`);
4532
4541
  }
4533
- canActivate(_route, _state) {
4534
- return this.IsUserAuth();
4542
+ canActivate(_route, state) {
4543
+ return this.IsUserAuth(state.url);
4535
4544
  }
4536
- canLoad(_route) {
4537
- return this.IsUserAuth();
4545
+ canLoad(_route, segments) {
4546
+ return this.IsUserAuth(`/${segments.map(segment => segment.path).join('/')}`);
4538
4547
  }
4539
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.25", ngImport: i0, type: AuthGuard, deps: [{ token: i1$1.Router }, { token: AuthStorageService }], target: i0.ɵɵFactoryTarget.Injectable }); }
4548
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.25", ngImport: i0, type: AuthGuard, deps: [{ token: i1$1.Router }, { token: AuthStorageService }, { token: i3.MessageService }], target: i0.ɵɵFactoryTarget.Injectable }); }
4540
4549
  static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.25", ngImport: i0, type: AuthGuard, providedIn: 'root' }); }
4541
4550
  }
4542
4551
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.25", ngImport: i0, type: AuthGuard, decorators: [{
4543
4552
  type: Injectable,
4544
4553
  args: [{ providedIn: 'root' }]
4545
- }], ctorParameters: () => [{ type: i1$1.Router }, { type: AuthStorageService }] });
4554
+ }], ctorParameters: () => [{ type: i1$1.Router }, { type: AuthStorageService }, { type: i3.MessageService }] });
4546
4555
 
4547
4556
  class ExternaLoginlGuard {
4548
4557
  constructor(router, authService, authStorageService) {
@@ -4688,6 +4697,81 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.25", ngImpo
4688
4697
  args: [{ providedIn: 'root' }]
4689
4698
  }], ctorParameters: () => [{ type: i1$1.Router }, { type: MenuServicesService }] });
4690
4699
 
4700
+ const IsMenuAllowedGuard = (_route, state) => {
4701
+ const router = inject(Router);
4702
+ const menuService = inject(MenuServicesService);
4703
+ const navigateToError = () => {
4704
+ return router.createUrlTree(['/error-menu-not-allowed']);
4705
+ };
4706
+ const permissionRoute = getPermissionRoute(state);
4707
+ // console.log('permissionRoute:', permissionRoute);
4708
+ return menuService.isMenuAllowed(permissionRoute).pipe(map(response => {
4709
+ // console.log('isMenuAllowed.response:', response);
4710
+ if (response.IsMenuAllowed)
4711
+ return true;
4712
+ return navigateToError();
4713
+ }), catchError(() => {
4714
+ return of(navigateToError());
4715
+ }));
4716
+ };
4717
+ /**
4718
+ * Obtém a rota utilizada para validar a permissão.
4719
+ *
4720
+ * Regras:
4721
+ * - considera toda a rota ativa, inclusive rotas lazy-loaded;
4722
+ * - ignora query parameters e fragments;
4723
+ * - ignora parâmetros declarados com ":";
4724
+ * - ignora qualquer segmento posterior ao primeiro parâmetro;
4725
+ * - retorna a rota sem "/" inicial.
4726
+ *
4727
+ * Exemplos:
4728
+ *
4729
+ * movimentacoes/alteracao-cadastral-grupo
4730
+ * => movimentacoes/alteracao-cadastral-grupo
4731
+ *
4732
+ * movimentacoes/fluxos-gerais/:id
4733
+ * => movimentacoes/fluxos-gerais
4734
+ *
4735
+ * movimentacoes/fluxos-gerais/:id/editar
4736
+ * => movimentacoes/fluxos-gerais
4737
+ */
4738
+ const getPermissionRoute = (state) => {
4739
+ const routeSegments = [];
4740
+ let currentRoute = state.root;
4741
+ // console.log('currentRoute:', currentRoute);
4742
+ while (currentRoute) {
4743
+ const configuredPath = currentRoute.routeConfig?.path;
4744
+ // console.log('configuredPath:', configuredPath);
4745
+ if (configuredPath) {
4746
+ const configuredSegments = configuredPath.split('/');
4747
+ for (const segment of configuredSegments) {
4748
+ if (isRouteParameter(segment))
4749
+ return routeSegments.join('/');
4750
+ routeSegments.push(segment);
4751
+ }
4752
+ // console.log('routeSegments:', routeSegments);
4753
+ }
4754
+ currentRoute = getPrimaryChild(currentRoute);
4755
+ // console.log('currentRoute 2:', currentRoute);
4756
+ }
4757
+ return routeSegments.join('/');
4758
+ };
4759
+ /**
4760
+ * Identifica parâmetros declarados na configuração da rota.
4761
+ *
4762
+ * Exemplos:
4763
+ * :id
4764
+ * :codigo
4765
+ * :empresaId
4766
+ */
4767
+ const isRouteParameter = (segment) => {
4768
+ return segment.startsWith(':');
4769
+ };
4770
+ /** Obtém a próxima rota ativa no outlet principal */
4771
+ const getPrimaryChild = (route) => {
4772
+ return route.children.find(child => child.outlet === PRIMARY_OUTLET);
4773
+ };
4774
+
4691
4775
  /**
4692
4776
  * Protege a página de login de ser carregada quando o usuário já está logado,
4693
4777
  * redirecionando ele para a página home da aplicação.
@@ -5177,5 +5261,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.25", ngImpo
5177
5261
  * Generated bundle index. Do not edit.
5178
5262
  */
5179
5263
 
5180
- export { AUTH_ROUTES, AuthAplicInterceptor, AuthGuard, AuthInfraInterceptor, AuthModule, AuthService, AuthStorageService, AuthUtilService, DynamicMenuComponent, ErrorMenuNotAllowed, ExternaLoginlGuard, FavoritarModel, IMenu, IndexedDBService, InfraEstabelecimentoFavoritoDefault, InfraUsuarioImg, IsMenuAllowedlGuard, LIB_CUSTOM_ENVIRONMENT_SERVICE, LIB_CUSTOM_LOGIN_SERVICE, LIB_CUSTOM_MENU_SERVICE, LIB_CUSTOM_STORAGE_SERVICE, LIB_MENU_CONFIG, LibCustomEnvironmentService, LibCustomLoginService, LibCustomMenuService, LibCustomStorageService, LibMenuConfigService, ListComponent, LoginComponent, LoginGuard, LoginOSComponent, LoginOSGuard, LoginProgress, MenuLateralComponent, MenuServicesService, MeuPerfilComponent, NavSubMenus, NavSubmenuCards, NavSubmenuSearchItem, NavTabsComponent, NotifSubmenuComponent, NovaSenhaComponent, PesquisaTelasGlobalService, PrimaryDropdownComponent, RetEstabelecimentosModal, RetInfraUsuarioImg, RetMenuItemStructure, RetMenuLateral, RetMenuPromise, RetNavSubMenu, RetSubmenuWithCards, SecondaryDropdownComponent, SelecaoEstabelecimentosModalComponent, SituacaoLogin, SubMenuCardComponent, SubMenuComponent, SubMenuItem, TelaItem };
5264
+ export { AUTH_ROUTES, AuthAplicInterceptor, AuthGuard, AuthInfraInterceptor, AuthModule, AuthService, AuthStorageService, AuthUtilService, DynamicMenuComponent, ErrorMenuNotAllowed, ExternaLoginlGuard, FavoritarModel, IMenu, IndexedDBService, InfraEstabelecimentoFavoritoDefault, InfraUsuarioImg, IsMenuAllowedGuard, IsMenuAllowedlGuard, LIB_CUSTOM_ENVIRONMENT_SERVICE, LIB_CUSTOM_LOGIN_SERVICE, LIB_CUSTOM_MENU_SERVICE, LIB_CUSTOM_STORAGE_SERVICE, LIB_MENU_CONFIG, LibCustomEnvironmentService, LibCustomLoginService, LibCustomMenuService, LibCustomStorageService, LibMenuConfigService, ListComponent, LoginComponent, LoginGuard, LoginOSComponent, LoginOSGuard, LoginProgress, MenuLateralComponent, MenuServicesService, MeuPerfilComponent, NavSubMenus, NavSubmenuCards, NavSubmenuSearchItem, NavTabsComponent, NotifSubmenuComponent, NovaSenhaComponent, PesquisaTelasGlobalService, PrimaryDropdownComponent, RetEstabelecimentosModal, RetInfraUsuarioImg, RetMenuItemStructure, RetMenuLateral, RetMenuPromise, RetNavSubMenu, RetSubmenuWithCards, SecondaryDropdownComponent, SelecaoEstabelecimentosModalComponent, SituacaoLogin, SubMenuCardComponent, SubMenuComponent, SubMenuItem, TelaItem };
5181
5265
  //# sourceMappingURL=ngx-sp-auth.mjs.map