Client: add ability for user to change nsfw settings
[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 import { AuthStatus } from './auth-status.model';
13 import { AuthUser } from './auth-user.model';
14 // Do not use the barrel (dependency loop)
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.mergeUserInformations(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   refreshUserInformations() {
182     const obj = {
183       access_token: this.user.getAccessToken()
184     };
185
186     this.mergeUserInformations(obj)
187         .subscribe(
188           res => {
189             this.user.displayNSFW = res.displayNSFW;
190             this.user.role = res.role;
191
192             this.user.save();
193           }
194         );
195   }
196
197   private mergeUserInformations(obj: { access_token: string }) {
198     // Do not call authHttp here to avoid circular dependencies headaches
199
200     const headers = new Headers();
201     headers.set('Authorization', `Bearer ${obj.access_token}`);
202
203     return this.http.get(AuthService.BASE_USER_INFORMATIONS_URL, { headers })
204              .map(res => res.json())
205              .map(res => {
206                const newProperties = {
207                  id: res.id,
208                  role: res.role,
209                  displayNSFW: res.displayNSFW
210                };
211
212                return Object.assign(obj, newProperties);
213              }
214     );
215   }
216
217   private handleLogin (obj: any) {
218     const id = obj.id;
219     const username = obj.username;
220     const role = obj.role;
221     const displayNSFW = obj.displayNSFW;
222     const hashTokens = {
223       access_token: obj.access_token,
224       token_type: obj.token_type,
225       refresh_token: obj.refresh_token
226     };
227
228     this.user = new AuthUser({ id, username, role, displayNSFW }, hashTokens);
229     this.user.save();
230
231     this.setStatus(AuthStatus.LoggedIn);
232   }
233
234   private handleRefreshToken (obj: any) {
235     this.user.refreshTokens(obj.access_token, obj.refresh_token);
236     this.user.save();
237   }
238
239   private setStatus(status: AuthStatus) {
240     this.loginChanged.next(status);
241   }
242
243 }