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';
9 // Do not use the barrel (dependency loop)
10 import { AuthStatus } from '../../shared/auth/auth-status.model';
11 import { AuthUser } from '../../shared/auth/auth-user.model';
12 import { RestExtractor } from '../../shared/rest';
15 export class AuthService {
16 private static BASE_CLIENT_URL = '/api/v1/clients/local';
17 private static BASE_TOKEN_URL = '/api/v1/users/token';
18 private static BASE_USER_INFORMATIONS_URL = '/api/v1/users/me';
20 loginChangedSource: Observable<AuthStatus>;
22 private clientId: string;
23 private clientSecret: string;
24 private loginChanged: Subject<AuthStatus>;
25 private user: AuthUser = null;
29 private restExtractor: RestExtractor,
30 private router: Router
32 this.loginChanged = new Subject<AuthStatus>();
33 this.loginChangedSource = this.loginChanged.asObservable();
35 // Fetch the client_id/client_secret
36 // FIXME: save in local storage?
37 this.http.get(AuthService.BASE_CLIENT_URL)
38 .map(this.restExtractor.extractDataGet)
39 .catch((res) => this.restExtractor.handleError(res))
42 this.clientId = result.client_id;
43 this.clientSecret = result.client_secret;
44 console.log('Client credentials loaded.');
48 `Cannot retrieve OAuth Client credentials: ${error.text}. \n` +
49 'Ensure you have correctly configured PeerTube (config/ directory), in particular the "webserver" section.'
54 // Return null if there is nothing to load
55 this.user = AuthUser.load();
59 if (this.user === null) return null;
61 return this.user.getRefreshToken();
64 getRequestHeaderValue() {
65 return `${this.getTokenType()} ${this.getAccessToken()}`;
69 if (this.user === null) return null;
71 return this.user.getAccessToken();
75 if (this.user === null) return null;
77 return this.user.getTokenType();
85 if (this.user === null) return false;
87 return this.user.isAdmin();
91 if (this.getAccessToken()) {
98 login(username: string, password: string) {
99 let body = new URLSearchParams();
100 body.set('client_id', this.clientId);
101 body.set('client_secret', this.clientSecret);
102 body.set('response_type', 'code');
103 body.set('grant_type', 'password');
104 body.set('scope', 'upload');
105 body.set('username', username);
106 body.set('password', password);
108 let headers = new Headers();
109 headers.append('Content-Type', 'application/x-www-form-urlencoded');
115 return this.http.post(AuthService.BASE_TOKEN_URL, body.toString(), options)
116 .map(this.restExtractor.extractDataGet)
118 res.username = username;
121 .flatMap(res => this.fetchUserInformations(res))
122 .map(res => this.handleLogin(res))
123 .catch((res) => this.restExtractor.handleError(res));
127 // TODO: make an HTTP request to revoke the tokens
132 this.setStatus(AuthStatus.LoggedOut);
135 refreshAccessToken() {
136 console.log('Refreshing token...');
138 const refreshToken = this.getRefreshToken();
140 let body = new URLSearchParams();
141 body.set('refresh_token', refreshToken);
142 body.set('client_id', this.clientId);
143 body.set('client_secret', this.clientSecret);
144 body.set('response_type', 'code');
145 body.set('grant_type', 'refresh_token');
147 let headers = new Headers();
148 headers.append('Content-Type', 'application/x-www-form-urlencoded');
154 return this.http.post(AuthService.BASE_TOKEN_URL, body.toString(), options)
155 .map(this.restExtractor.extractDataGet)
156 .map(res => this.handleRefreshToken(res))
157 .catch((res: Response) => {
158 // The refresh token is invalid?
159 if (res.status === 400 && res.json() && res.json().error === 'invalid_grant') {
160 console.error('Cannot refresh token -> logout...');
162 this.router.navigate(['/login']);
164 return Observable.throw({
166 text: () => 'You need to reconnect.'
170 return this.restExtractor.handleError(res);
174 private fetchUserInformations (obj: any) {
175 // Do not call authHttp here to avoid circular dependencies headaches
177 const headers = new Headers();
178 headers.set('Authorization', `Bearer ${obj.access_token}`);
180 return this.http.get(AuthService.BASE_USER_INFORMATIONS_URL, { headers })
181 .map(res => res.json())
190 private handleLogin (obj: any) {
192 const username = obj.username;
193 const role = obj.role;
195 access_token: obj.access_token,
196 token_type: obj.token_type,
197 refresh_token: obj.refresh_token
200 this.user = new AuthUser({ id, username, role }, hashTokens);
203 this.setStatus(AuthStatus.LoggedIn);
206 private handleRefreshToken (obj: any) {
207 this.user.refreshTokens(obj.access_token, obj.refresh_token);
211 private setStatus(status: AuthStatus) {
212 this.loginChanged.next(status);