Client: better confirm box for a beautiful world
[oweals/peertube.git] / client / src / app / core / auth / auth.service.ts
1 import { Injectable } from '@angular/core';
2 import { Headers, Http, Response, URLSearchParams } from '@angular/http';
3 import { Router } from '@angular/router';
4 import { Observable } from 'rxjs/Observable';
5 import { Subject } from 'rxjs/Subject';
6 import 'rxjs/add/operator/map';
7 import 'rxjs/add/operator/mergeMap';
8 import 'rxjs/add/observable/throw';
9
10 import { NotificationsService } from 'angular2-notifications';
11
12 // Do not use the barrel (dependency loop)
13 import { AuthStatus } from '../../shared/auth/auth-status.model';
14 import { AuthUser } from '../../shared/auth/auth-user.model';
15 import { RestExtractor } from '../../shared/rest';
16
17 @Injectable()
18 export class AuthService {
19   private static BASE_CLIENT_URL = '/api/v1/clients/local';
20   private static BASE_TOKEN_URL = '/api/v1/users/token';
21   private static BASE_USER_INFORMATIONS_URL = '/api/v1/users/me';
22
23   loginChangedSource: Observable<AuthStatus>;
24
25   private clientId: string;
26   private clientSecret: string;
27   private loginChanged: Subject<AuthStatus>;
28   private user: AuthUser = null;
29
30   constructor(
31     private http: Http,
32     private notificationsService: NotificationsService,
33     private restExtractor: RestExtractor,
34     private router: Router
35    ) {
36     this.loginChanged = new Subject<AuthStatus>();
37     this.loginChangedSource = this.loginChanged.asObservable();
38
39     // Fetch the client_id/client_secret
40     // FIXME: save in local storage?
41     this.http.get(AuthService.BASE_CLIENT_URL)
42       .map(this.restExtractor.extractDataGet)
43       .catch((res) => this.restExtractor.handleError(res))
44       .subscribe(
45         result => {
46           this.clientId = result.client_id;
47           this.clientSecret = result.client_secret;
48           console.log('Client credentials loaded.');
49         },
50
51         error => {
52           let errorMessage = `Cannot retrieve OAuth Client credentials: ${error.text}. \n`;
53           errorMessage += 'Ensure you have correctly configured PeerTube (config/ directory), in particular the "webserver" section.';
54
55           // We put a bigger timeout
56           // This is an important message
57           this.notificationsService.error('Error', errorMessage, { timeOut: 7000 });
58         }
59       );
60
61     // Return null if there is nothing to load
62     this.user = AuthUser.load();
63   }
64
65   getRefreshToken() {
66     if (this.user === null) return null;
67
68     return this.user.getRefreshToken();
69   }
70
71   getRequestHeaderValue() {
72     return `${this.getTokenType()} ${this.getAccessToken()}`;
73   }
74
75   getAccessToken() {
76     if (this.user === null) return null;
77
78     return this.user.getAccessToken();
79   }
80
81   getTokenType() {
82     if (this.user === null) return null;
83
84     return this.user.getTokenType();
85   }
86
87   getUser(): AuthUser {
88     return this.user;
89   }
90
91   isAdmin() {
92     if (this.user === null) return false;
93
94     return this.user.isAdmin();
95   }
96
97   isLoggedIn() {
98     if (this.getAccessToken()) {
99       return true;
100     } else {
101       return false;
102     }
103   }
104
105   login(username: string, password: string) {
106     let body = new URLSearchParams();
107     body.set('client_id', this.clientId);
108     body.set('client_secret', this.clientSecret);
109     body.set('response_type', 'code');
110     body.set('grant_type', 'password');
111     body.set('scope', 'upload');
112     body.set('username', username);
113     body.set('password', password);
114
115     let headers = new Headers();
116     headers.append('Content-Type', 'application/x-www-form-urlencoded');
117
118     let options = {
119       headers: headers
120     };
121
122     return this.http.post(AuthService.BASE_TOKEN_URL, body.toString(), options)
123                     .map(this.restExtractor.extractDataGet)
124                     .map(res => {
125                       res.username = username;
126                       return res;
127                     })
128                     .flatMap(res => this.fetchUserInformations(res))
129                     .map(res => this.handleLogin(res))
130                     .catch((res) => this.restExtractor.handleError(res));
131   }
132
133   logout() {
134     // TODO: make an HTTP request to revoke the tokens
135     this.user = null;
136
137     AuthUser.flush();
138
139     this.setStatus(AuthStatus.LoggedOut);
140   }
141
142   refreshAccessToken() {
143     console.log('Refreshing token...');
144
145     const refreshToken = this.getRefreshToken();
146
147     let body = new URLSearchParams();
148     body.set('refresh_token', refreshToken);
149     body.set('client_id', this.clientId);
150     body.set('client_secret', this.clientSecret);
151     body.set('response_type', 'code');
152     body.set('grant_type', 'refresh_token');
153
154     let headers = new Headers();
155     headers.append('Content-Type', 'application/x-www-form-urlencoded');
156
157     let options = {
158       headers: headers
159     };
160
161     return this.http.post(AuthService.BASE_TOKEN_URL, body.toString(), options)
162                     .map(this.restExtractor.extractDataGet)
163                     .map(res => this.handleRefreshToken(res))
164                     .catch((res: Response) => {
165                       // The refresh token is invalid?
166                       if (res.status === 400 && res.json() && res.json().error === 'invalid_grant') {
167                         console.error('Cannot refresh token -> logout...');
168                         this.logout();
169                         this.router.navigate(['/login']);
170
171                         return Observable.throw({
172                           json: () => '',
173                           text: () => 'You need to reconnect.'
174                         });
175                       }
176
177                       return this.restExtractor.handleError(res);
178                     });
179   }
180
181   private fetchUserInformations (obj: any) {
182     // Do not call authHttp here to avoid circular dependencies headaches
183
184     const headers = new Headers();
185     headers.set('Authorization', `Bearer ${obj.access_token}`);
186
187     return this.http.get(AuthService.BASE_USER_INFORMATIONS_URL, { headers })
188              .map(res => res.json())
189              .map(res => {
190                obj.id = res.id;
191                obj.role = res.role;
192                return obj;
193              }
194     );
195   }
196
197   private handleLogin (obj: any) {
198     const id = obj.id;
199     const username = obj.username;
200     const role = obj.role;
201     const hashTokens = {
202       access_token: obj.access_token,
203       token_type: obj.token_type,
204       refresh_token: obj.refresh_token
205     };
206
207     this.user = new AuthUser({ id, username, role }, hashTokens);
208     this.user.save();
209
210     this.setStatus(AuthStatus.LoggedIn);
211   }
212
213   private handleRefreshToken (obj: any) {
214     this.user.refreshTokens(obj.access_token, obj.refresh_token);
215     this.user.save();
216   }
217
218   private setStatus(status: AuthStatus) {
219     this.loginChanged.next(status);
220   }
221
222 }