]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/shared/auth/auth-http.service.ts
Use typescript standard and lint all files
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / auth / auth-http.service.ts
1 import { Injectable } from '@angular/core'
2 import {
3 ConnectionBackend,
4 Headers,
5 Http,
6 Request,
7 RequestMethod,
8 RequestOptions,
9 RequestOptionsArgs,
10 Response,
11 XHRBackend
12 } from '@angular/http'
13 import { Observable } from 'rxjs/Observable'
14
15 import { AuthService } from '../../core'
16
17 @Injectable()
18 export 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) {
32 return this.handleTokenExpired(url, options)
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
53 post (url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
54 if (!options) options = {}
55 options.method = RequestMethod.Post
56 options.body = body
57
58 return this.request(url, options)
59 }
60
61 put (url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
62 if (!options) options = {}
63 options.method = RequestMethod.Put
64 options.body = body
65
66 return this.request(url, options)
67 }
68
69 private handleTokenExpired (url: string | Request, options: RequestOptionsArgs) {
70 return this.authService.refreshAccessToken()
71 .flatMap(() => {
72 this.setAuthorizationHeader(options.headers)
73
74 return super.request(url, options)
75 })
76 }
77
78 private setAuthorizationHeader (headers: Headers) {
79 headers.set('Authorization', this.authService.getRequestHeaderValue())
80 }
81 }
82
83 export function useFactory (backend: XHRBackend, defaultOptions: RequestOptions, authService: AuthService) {
84 return new AuthHttp(backend, defaultOptions, authService)
85 }
86
87 export const AUTH_HTTP_PROVIDERS = [
88 {
89 provide: AuthHttp,
90 useFactory,
91 deps: [ XHRBackend, RequestOptions, AuthService ]
92 }
93 ]