1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
|
import { Injectable } from '@angular/core';
import {
ConnectionBackend,
Headers,
Http,
Request,
RequestMethod,
RequestOptions,
RequestOptionsArgs,
Response,
XHRBackend
} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { AuthService } from '../../core';
@Injectable()
export class AuthHttp extends Http {
constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, private authService: AuthService) {
super(backend, defaultOptions);
}
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
if (!options) options = {};
options.headers = new Headers();
this.setAuthorizationHeader(options.headers);
return super.request(url, options)
.catch((err) => {
if (err.status === 401) {
return this.handleTokenExpired(url, options);
}
return Observable.throw(err);
});
}
delete(url: string, options?: RequestOptionsArgs): Observable<Response> {
if (!options) options = {};
options.method = RequestMethod.Delete;
return this.request(url, options);
}
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
if (!options) options = {};
options.method = RequestMethod.Get;
return this.request(url, options);
}
post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
if (!options) options = {};
options.method = RequestMethod.Post;
options.body = body;
return this.request(url, options);
}
put(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
if (!options) options = {};
options.method = RequestMethod.Put;
options.body = body;
return this.request(url, options);
}
private handleTokenExpired(url: string | Request, options: RequestOptionsArgs) {
return this.authService.refreshAccessToken()
.flatMap(() => {
this.setAuthorizationHeader(options.headers);
return super.request(url, options);
});
}
private setAuthorizationHeader(headers: Headers) {
headers.set('Authorization', this.authService.getRequestHeaderValue());
}
}
export const AUTH_HTTP_PROVIDERS = [
{
provide: AuthHttp,
useFactory: (backend: XHRBackend, defaultOptions: RequestOptions, authService: AuthService) => {
return new AuthHttp(backend, defaultOptions, authService);
},
deps: [ XHRBackend, RequestOptions, AuthService ]
},
];
|