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