1
- import { catchError } from 'rxjs/operators' ;
1
+ import { catchError , tap } from 'rxjs/operators' ;
2
2
import { Injectable } from '@angular/core' ;
3
- import { OAuthService , OAuthStorage } from 'angular-oauth2-oidc' ;
3
+ import { OAuthService } from 'angular-oauth2-oidc' ;
4
4
import { Observable , throwError } from 'rxjs' ;
5
5
import {
6
6
HttpErrorResponse ,
@@ -16,42 +16,50 @@ export class OAuthInterceptor implements HttpInterceptor {
16
16
excludedUrls = [ 'assets' , '/assets' ] ;
17
17
excludedUrlsRegEx = this . excludedUrls . map ( ( url ) => new RegExp ( '^' + url , 'i' ) ) ;
18
18
19
- constructor (
20
- private oauthService : OAuthService ,
21
- private authStorage : OAuthStorage ,
22
- private snackbar : SnackbarService
23
- ) { }
19
+ constructor ( private oauthService : OAuthService , private snackbar : SnackbarService ) { }
24
20
25
21
private isExcluded ( req : HttpRequest < any > ) : boolean {
26
22
return this . excludedUrlsRegEx . some ( ( toBeExcluded ) => toBeExcluded . test ( req . url ) ) ;
27
23
}
24
+
28
25
public intercept ( req : HttpRequest < any > , next : HttpHandler ) : Observable < HttpEvent < any > > {
29
26
if ( this . isExcluded ( req ) ) {
30
27
return next . handle ( req ) ;
31
28
}
32
- const token = this . authStorage . getItem ( 'access_token' ) ;
33
- const headers = req . headers . set ( 'Authorization' , 'Bearer ' + token ) ;
34
- req = req . clone ( { headers } ) ;
29
+ const token = this . getToken ( ) ;
30
+ if ( token ) {
31
+ const headers = req . headers . set ( 'Authorization' , 'Bearer ' + token ) ;
32
+ req = req . clone ( { headers } ) ;
33
+ }
35
34
return next . handle ( req ) . pipe (
36
35
catchError ( ( error : HttpErrorResponse ) => {
36
+ console . error ( 'OAuthInterceptor: Error occurred' , error ) ;
37
37
if ( error . status === 401 ) {
38
38
this . oauthService . logOut ( ) ;
39
39
}
40
40
if ( error . status === 404 ) {
41
41
this . handleErrorCodes ( error . status ) ;
42
42
}
43
- if ( error . error . issue ) {
43
+ if ( error . error ? .issue ) {
44
44
this . handleErrorCodes ( error . error . issue [ 0 ] ?. code ) ;
45
45
}
46
- if ( error . error . issues ) {
47
- this . handleErrorCodes ( error . error . issues [ 0 ] ?. code , error . headers . get ( 'Retry-After' ) ) ;
46
+ if ( error . error ?. issues ) {
47
+ const retryAfter = error . headers . get ( 'Retry-After' ) ;
48
+ this . handleErrorCodes ( error . error . issues [ 0 ] ?. code , Number ( retryAfter ) ) ;
48
49
}
49
50
return throwError ( error ) ;
50
51
} )
51
52
) ;
52
53
}
53
54
54
- public handleErrorCodes ( errorCode , retryAfter ?) {
55
+ private getToken ( ) : string | null {
56
+ if ( this . oauthService . hasValidAccessToken ( ) ) {
57
+ return this . oauthService . getAccessToken ( ) ;
58
+ }
59
+ return null ;
60
+ }
61
+
62
+ public handleErrorCodes ( errorCode , retryAfter ?: number ) {
55
63
this . snackbar . displayErrorMessage ( errorCode , retryAfter ) ;
56
64
}
57
65
}
0 commit comments