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