From c6919379b69335f81cda9f03a8bb3217d06cf696 Mon Sep 17 00:00:00 2001 From: Alix JEUDI--LEMOINE Date: Thu, 19 Jun 2025 22:16:31 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=9A=91=20Fix=20logout=20in=20case=20of=20?= =?UTF-8?q?401=20error?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/app/auth.interceptor.ts | 14 ++++---------- src/app/services/auth/auth.service.ts | 15 ++++++++++++--- 2 files changed, 16 insertions(+), 13 deletions(-) diff --git a/src/app/auth.interceptor.ts b/src/app/auth.interceptor.ts index 1d4c1ad..de4a2db 100644 --- a/src/app/auth.interceptor.ts +++ b/src/app/auth.interceptor.ts @@ -5,12 +5,11 @@ import { HttpEvent, HttpErrorResponse, } from '@angular/common/http'; -import { Observable, from, throwError } from 'rxjs'; +import { Observable, from, of, throwError } from 'rxjs'; import { catchError, switchMap } from 'rxjs/operators'; import { inject } from '@angular/core'; import { CookiesService } from './services/cookies/cookies.service'; -import { ModalService } from './services/modal/modal.service'; -import { Router } from '@angular/router'; +import { AuthService } from './services/auth/auth.service'; export const AuthInterceptor: HttpInterceptorFn = ( req: HttpRequest, @@ -22,9 +21,7 @@ export const AuthInterceptor: HttpInterceptorFn = ( } const cookiesService = inject(CookiesService); - const router = inject(Router); - const modalService = inject(ModalService); - + const authService = inject(AuthService); return from(cookiesService.getValidToken()).pipe( switchMap((token) => { const authReq = token @@ -37,10 +34,7 @@ export const AuthInterceptor: HttpInterceptorFn = ( }), catchError((err: HttpErrorResponse) => { if (err.status === 401) { - cookiesService.clearSession(); - router.navigate(['/']).then(() => { - modalService.openModal('login-modal'); - }); + authService.logout(false); } return throwError(() => err); }) diff --git a/src/app/services/auth/auth.service.ts b/src/app/services/auth/auth.service.ts index d046937..a315c6a 100644 --- a/src/app/services/auth/auth.service.ts +++ b/src/app/services/auth/auth.service.ts @@ -56,15 +56,24 @@ export class AuthService { ); } - logout(): void { - this.pushService.unsubscribe().finally(() => { + logout(withPush: boolean = true): void { + if (withPush) { + this.pushService.unsubscribe().finally(() => { + this.isAdminSubject.next(false); + this.username$.next(''); + this.userIdSubject.next(''); + this.isLoggedIn$.next(false); + this.cookiesService.clearSession(); + this.router.navigate(['/']); + }); + } else { this.isAdminSubject.next(false); this.username$.next(''); this.userIdSubject.next(''); this.isLoggedIn$.next(false); this.cookiesService.clearSession(); this.router.navigate(['/']); - }); + } } register(username: string, password: string): Observable {