From af5d428134c6f91f23d5598fa11885b40af9d8e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eudes=20In=C3=A1cio?= Date: Wed, 6 Mar 2024 15:20:35 +0100 Subject: [PATCH] chat interceptor added --- src/app/app.module.ts | 5 +- src/app/interceptors/chatToken.interceptor.ts | 266 ++++++++++-------- src/app/interceptors/token.interceptors.ts | 8 +- src/app/services/chat.service.ts | 55 ---- 4 files changed, 152 insertions(+), 182 deletions(-) diff --git a/src/app/app.module.ts b/src/app/app.module.ts index e9d6f4b08..9b80a69cc 100644 --- a/src/app/app.module.ts +++ b/src/app/app.module.ts @@ -87,7 +87,7 @@ import { LoggingInterceptorService } from './services/logging-interceptor.servic import { PopupQuestionPipe } from './modals/popup-question.pipe'; import '@teamhive/capacitor-video-recorder'; import { tokenInterceptor } from './interceptors/token.interceptors'; -import { ChatTokenInterceptor } from './interceptors/chatToken.interceptor'; +import { chatTokenInterceptor } from './interceptors/chatToken.interceptor'; import { InputFilterDirective } from './services/directives/input-filter.directive'; import { VisibilityDirective } from './services/directives/visibility.directive'; @@ -217,8 +217,9 @@ import { FirebaseX } from '@ionic-native/firebase-x/ngx'; */ DocumentViewer, FFMpeg, { provide: HTTP_INTERCEPTORS, useClass: LoggingInterceptorService, multi: true }, + chatTokenInterceptor, tokenInterceptor, - /* ChatTokenInterceptor */ + ], bootstrap: [AppComponent], diff --git a/src/app/interceptors/chatToken.interceptor.ts b/src/app/interceptors/chatToken.interceptor.ts index c1929a01e..974b7d783 100644 --- a/src/app/interceptors/chatToken.interceptor.ts +++ b/src/app/interceptors/chatToken.interceptor.ts @@ -1,12 +1,12 @@ import { Injectable } from '@angular/core'; import { - HttpInterceptor, - HttpRequest, - HttpHandler, - HttpEvent, - HttpErrorResponse, - HTTP_INTERCEPTORS, - HttpHeaders, + HttpInterceptor, + HttpRequest, + HttpHandler, + HttpEvent, + HttpErrorResponse, + HTTP_INTERCEPTORS, + HttpHeaders, } from '@angular/common/http'; import { Observable, throwError, BehaviorSubject } from 'rxjs'; import { catchError, switchMap, filter, take } from 'rxjs/operators'; @@ -15,138 +15,158 @@ import { Router } from '@angular/router'; import { SessionStore } from '../store/session.service'; import { environment } from "src/environments/environment"; import { PermissionService } from '../services/permission.service'; -import { NetworkServiceService , ConnectionStatus} from 'src/app/services/network-service.service'; +import { NetworkServiceService, ConnectionStatus } from 'src/app/services/network-service.service'; import { RochetChatConnectorService } from 'src/app/services/chat/rochet-chat-connector.service'; - + @Injectable() export class ChatTokenInterceptor implements HttpInterceptor { - private isRefreshing = false; - headers: HttpHeaders; - options: any; - private refreshTokenSubject: BehaviorSubject = new BehaviorSubject( - null - ); - - private excludedDomain = 'https://gdchat-dev.dyndns.info';// Add other domains as needed - - constructor(private http: HttpClient, private router: Router,private p: PermissionService,private NetworkServiceService: NetworkServiceService, - private RochetChatConnectorService: RochetChatConnectorService) {} - - intercept( - request: HttpRequest, - next: HttpHandler - ): Observable> { - if (this.shouldExcludeDomain(request)) { - return next.handle(request); - } - - return next.handle(request).pipe( - catchError((error) => { - if (error instanceof HttpErrorResponse && error.status === 401) { - return this.handle401Error(request, next); - } else { - return throwError(error); - } - }) + private isRefreshing = false; + headers: HttpHeaders; + options: any; + private refreshChatTokenSubject: BehaviorSubject = new BehaviorSubject( + null ); - } - - private shouldExcludeDomain(request: HttpRequest): boolean { - const url = request.url.toLowerCase(); - return !url.includes(this.excludedDomain.toLowerCase()); - } - - private handle401Error( - request: HttpRequest, - next: HttpHandler - ): Observable> { - if (!this.isRefreshing) { - this.isRefreshing = true; - this.refreshTokenSubject.next(null); - - return this.refreshToken().pipe( - switchMap((token: any) => { - this.isRefreshing = false; - let data = { - status: token['status'], - data: { - userId: token['data'].userId, - authToken: token['data'].authToken - } + private excludedDomains = ['Login',environment.apiURL];// Add other domains as needed + + constructor(private http: HttpClient, private router: Router, private p: PermissionService, private NetworkServiceService: NetworkServiceService, + private RochetChatConnectorService: RochetChatConnectorService) { } + + intercept( + request: HttpRequest, + next: HttpHandler + ): Observable> { + if (this.shouldExcludeDomain(request)) { + return next.handle(request); + } + + if (SessionStore.user.Authorization) { + request = this.addToken(request, SessionStore.user.Authorization); } - SessionStore.user.ChatData = data - SessionStore.save() - this.setheader() - - - this.refreshTokenSubject.next(token.Authorization); - return next.handle(this.addToken(request, token.Authorization)); - }) - ); - } else { - return this.refreshTokenSubject.pipe( - filter((token) => token != null), - take(1), - switchMap((jwt) => { - return next.handle(this.addToken(request, jwt)); - }) - ); + return next.handle(request).pipe( + catchError((error) => { + if (error instanceof HttpErrorResponse && error.status === 401) { + return this.handle401Error(request, next); + } else { + return throwError(error); + } + }) + ); } - } - - private addToken(request: HttpRequest, token: string) { - return request.clone({ - /* setHeaders: { - Authorization: `Bearer ${token}`, - }, */ - }); - } - - private refreshToken(): Observable { - return this.http - .get(environment.apiURL + 'UserAuthentication/RegenereChatToken', { - /* refreshToken: SessionStore.user.RefreshToken, */ - }) - .pipe( - catchError((error) => { - // Handle token refresh failure - console.log('ChatToken refresh failed:', error); - return throwError(error); - }) - ); - } - + + private shouldExcludeDomain(request: HttpRequest): boolean { + const url = request.url.toLowerCase(); + return this.excludedDomains.some((domain) => url.includes(domain.toLowerCase())); + } + + private handle401Error( + request: HttpRequest, + next: HttpHandler + ): Observable> { + if (!this.isRefreshing) { + this.isRefreshing = true; + this.refreshChatTokenSubject.next(null); + + return this.refreshToken().pipe( + switchMap((token: any) => { + this.isRefreshing = false; + + let data = { + status: token['status'], + data: { + userId: token['data'].userId, + authToken: token['data'].authToken + } + } + SessionStore.user.ChatData = data + SessionStore.save() + /* this.setheader() */ - setheader() { - try { - if (this.p.userPermission(this.p.permissionList.Chat.access) && SessionStore.user.ChatData) { - this.headers = new HttpHeaders();; + this.refreshChatTokenSubject.next(token.Authorization); + return next.handle(this.addToken(request, token.Authorization)); + }) + ); + } else { + return this.refreshChatTokenSubject.pipe( + filter((token) => token != null), + take(1), + switchMap((jwt) => { + return next.handle(this.addToken(request, jwt)); + }) + ); + } + } - if (this.p.userPermission(this.p.permissionList.Chat.access)) { - // - this.headers = this.headers.set('X-User-Id', SessionStore.user.ChatData.data.userId); - this.headers = this.headers.set('X-Auth-Token', SessionStore.user.ChatData.data.authToken); - this.options = { - headers: this.headers, - }; + private addToken(request: HttpRequest, token: string) { + let headers = new HttpHeaders(); + + + console.log('X-User-Id', SessionStore.user.ChatData.data.userId) + console.log('X-Auth-Token', SessionStore.user.ChatData.data.authToken) + headers = headers.set('X-User-Id', SessionStore.user.ChatData.data.userId); + headers = headers.set('X-Auth-Token', SessionStore.user.ChatData.data.authToken); + + return request.clone({ + setHeaders: { + Authorization: `Bearer ${token}`, + ...headers.keys().reduce((acc, key) => ({ ...acc, [key]: headers.get(key) }), {}), + }, + }); + } + + /* private addToken(request: HttpRequest, token: string) { + return request.clone({ + setHeaders: { + Authorization: `Bearer ${token}`, + }, + }); + } */ + + private refreshToken(): Observable { + return this.http + .get(environment.apiURL + 'UserAuthentication/RegenereChatToken', { + /* refreshToken: SessionStore.user.RefreshToken, */ + }) + .pipe( + catchError((error) => { + // Handle token refresh failure + console.log('ChatToken refresh failed:', error); + return throwError(error); + }) + ); + } + + + + setheader() { + try { + + if (this.p.userPermission(this.p.permissionList.Chat.access) && SessionStore.user.ChatData) { + this.headers = new HttpHeaders();; + + if (this.p.userPermission(this.p.permissionList.Chat.access)) { + // + this.headers = this.headers.set('X-User-Id', SessionStore.user.ChatData.data.userId); + this.headers = this.headers.set('X-Auth-Token', SessionStore.user.ChatData.data.authToken); + this.options = { + headers: this.headers, + }; + + } + } + } catch (error) { } - } - } catch (error) { - } - } } - - - -export const tokenInterceptor = { + + + +export const chatTokenInterceptor = { provide: HTTP_INTERCEPTORS, useClass: ChatTokenInterceptor, multi: true - }; - \ No newline at end of file +}; diff --git a/src/app/interceptors/token.interceptors.ts b/src/app/interceptors/token.interceptors.ts index 13e4ebe71..b0916499f 100644 --- a/src/app/interceptors/token.interceptors.ts +++ b/src/app/interceptors/token.interceptors.ts @@ -119,9 +119,13 @@ export class TokenInterceptor implements HttpInterceptor { if (environment.production) { window.location.pathname = '/auth' } else { - /* const pathBeforeGoOut = window.location.pathname */ + const pathBeforeGoOut = window.location.pathname + console.log('Before auth',window.location.pathname) this.router.navigateByUrl('/auth', { replaceUrl: true }).then(() =>{ - this.httpErrorHandle.httpsSucessMessagge('sessonExpired') + if(pathBeforeGoOut != "/auth") { + this.httpErrorHandle.httpsSucessMessagge('sessonExpired') + } + }) } return of(false); diff --git a/src/app/services/chat.service.ts b/src/app/services/chat.service.ts index 792716595..5d8072ddb 100644 --- a/src/app/services/chat.service.ts +++ b/src/app/services/chat.service.ts @@ -392,61 +392,6 @@ export class ChatService { async refreshtoken() { - if(this.headers && SessionStore.user.ChatData) { - this.headers = this.headers.set('Authorization', 'Bearer ' + SessionStore.user.Authorization); - let options = { - headers: this.headers - }; - - try { - let res = await this.http.get(environment.apiURL + 'UserAuthentication/RegenereChatToken', options).toPromise(); - - let data = { - status: res['status'], - data: { - userId: res['data'].userId, - authToken: res['data'].authToken - } - } - SessionStore.user.ChatData = data - SessionStore.save() - this.setheader() - this.timerEventTriggerDateLastUpdate = new Date(); - } catch (error) { - - if(this.NetworkServiceService.getCurrentNetworkStatus() == ConnectionStatus.Offline) { - this.RochetChatConnectorService.registerCallback({ - requestId: 'refreshtoken', - type: 'reConnect', - funx: async () => { - - this.resetTimer(); - await this.refreshtoken(); - - return true - } - }) - } else { - - if(SessionStore.user.Authorization != '') { - setTimeout(async () => { - this.resetTimer(); - await this.refreshtoken(); - }, 60000) - } - - - } - - } - - } else if(!SessionStore.user.ChatData) { - // do nothing - } else if (!this.headers) { - this.setheader() - this.refreshtoken() - } - }