|
1 | 1 | import { Injectable, Optional } from '@angular/core'; |
2 | | -import { OAuthStorage } from '../types'; |
| 2 | +import { OAuthService } from '../oauth-service'; |
3 | 3 | import { |
4 | 4 | HttpEvent, |
5 | 5 | HttpHandler, |
6 | 6 | HttpInterceptor, |
7 | 7 | HttpRequest, |
8 | 8 | } from '@angular/common/http'; |
9 | | -import { Observable } from 'rxjs'; |
10 | | -import { catchError } from 'rxjs/operators'; |
| 9 | +import { Observable, of, merge } from 'rxjs'; |
| 10 | +import { catchError, filter, map, take, mergeMap, timeout } from 'rxjs/operators'; |
11 | 11 | import { OAuthResourceServerErrorHandler } from './resource-server-error-handler'; |
12 | 12 | import { OAuthModuleConfig } from '../oauth-module.config'; |
13 | 13 |
|
| 14 | +const WAIT_FOR_TOKEN_RECEIVED = 1000; |
| 15 | + |
14 | 16 | @Injectable() |
15 | 17 | export class DefaultOAuthInterceptor implements HttpInterceptor { |
16 | 18 | constructor( |
17 | | - private authStorage: OAuthStorage, |
| 19 | + private oAuthService: OAuthService, |
18 | 20 | private errorHandler: OAuthResourceServerErrorHandler, |
19 | 21 | @Optional() private moduleConfig: OAuthModuleConfig |
20 | 22 | ) { } |
@@ -42,17 +44,34 @@ export class DefaultOAuthInterceptor implements HttpInterceptor { |
42 | 44 |
|
43 | 45 | const sendAccessToken = this.moduleConfig.resourceServer.sendAccessToken; |
44 | 46 |
|
45 | | - if (sendAccessToken && this.authStorage.getItem('access_token')) { |
46 | | - const token = this.authStorage.getItem('access_token'); |
47 | | - const header = 'Bearer ' + token; |
48 | | - |
49 | | - const headers = req.headers.set('Authorization', header); |
50 | | - |
51 | | - req = req.clone({ headers }); |
| 47 | + if (!sendAccessToken) { |
| 48 | + return next |
| 49 | + .handle(req) |
| 50 | + .pipe(catchError(err => this.errorHandler.handleError(err))); |
52 | 51 | } |
53 | 52 |
|
54 | | - return next |
55 | | - .handle(req) |
56 | | - .pipe(catchError(err => this.errorHandler.handleError(err))); |
| 53 | + return merge( |
| 54 | + of(this.oAuthService.getAccessToken()).pipe( |
| 55 | + filter(token => token ? true : false), |
| 56 | + ), |
| 57 | + this.oAuthService.events.pipe( |
| 58 | + filter(e => e.type === 'token_received'), |
| 59 | + timeout(WAIT_FOR_TOKEN_RECEIVED), |
| 60 | + map(_ => this.oAuthService.getAccessToken()), |
| 61 | + ), |
| 62 | + ).pipe( |
| 63 | + take(1), |
| 64 | + mergeMap(token => { |
| 65 | + if (token) { |
| 66 | + const header = 'Bearer ' + token; |
| 67 | + const headers = req.headers.set('Authorization', header); |
| 68 | + req = req.clone({ headers }); |
| 69 | + } |
| 70 | + |
| 71 | + return next |
| 72 | + .handle(req) |
| 73 | + .pipe(catchError(err => this.errorHandler.handleError(err))); |
| 74 | + }), |
| 75 | + ); |
57 | 76 | } |
58 | 77 | } |
0 commit comments