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';
10 // Do not use the barrel (dependency loop)
11 import { AuthStatus } from '../../shared/auth/auth-status.model';
12 import { AuthUser } from '../../shared/auth/auth-user.model';
13 import { RestExtractor } from '../../shared/rest';
16 export class AuthService {
17 private static BASE_CLIENT_URL = '/api/v1/clients/local';
18 private static BASE_TOKEN_URL = '/api/v1/users/token';
19 private static BASE_USER_INFORMATIONS_URL = '/api/v1/users/me';
21 loginChangedSource: Observable<AuthStatus>;
23 private clientId: string;
24 private clientSecret: string;
25 private loginChanged: Subject<AuthStatus>;
26 private user: AuthUser = null;
30 private restExtractor: RestExtractor,
31 private router: Router
33 this.loginChanged = new Subject<AuthStatus>();
34 this.loginChangedSource = this.loginChanged.asObservable();
36 // Fetch the client_id/client_secret
37 // FIXME: save in local storage?
38 this.http.get(AuthService.BASE_CLIENT_URL)
39 .map(this.restExtractor.extractDataGet)
40 .catch((res) => this.restExtractor.handleError(res))
43 this.clientId = result.client_id;
44 this.clientSecret = result.client_secret;
45 console.log('Client credentials loaded.');
49 `Cannot retrieve OAuth Client credentials: ${error.text}. \n` +
50 'Ensure you have correctly configured PeerTube (config/ directory), in particular the "webserver" section.'
55 // Return null if there is nothing to load
56 this.user = AuthUser.load();
60 if (this.user === null) return null;
62 return this.user.getRefreshToken();
65 getRequestHeaderValue() {
66 return `${this.getTokenType()} ${this.getAccessToken()}`;
70 if (this.user === null) return null;
72 return this.user.getAccessToken();
76 if (this.user === null) return null;
78 return this.user.getTokenType();
86 if (this.user === null) return false;
88 return this.user.isAdmin();
92 if (this.getAccessToken()) {
99 login(username: string, password: string) {
100 let body = new URLSearchParams();
101 body.set('client_id', this.clientId);
102 body.set('client_secret', this.clientSecret);
103 body.set('response_type', 'code');
104 body.set('grant_type', 'password');
105 body.set('scope', 'upload');
106 body.set('username', username);
107 body.set('password', password);
109 let headers = new Headers();
110 headers.append('Content-Type', 'application/x-www-form-urlencoded');
116 return this.http.post(AuthService.BASE_TOKEN_URL, body.toString(), options)
117 .map(this.restExtractor.extractDataGet)
119 res.username = username;
122 .flatMap(res => this.fetchUserInformations(res))
123 .map(res => this.handleLogin(res))
124 .catch((res) => this.restExtractor.handleError(res));
128 // TODO: make an HTTP request to revoke the tokens
133 this.setStatus(AuthStatus.LoggedOut);
136 refreshAccessToken() {
137 console.log('Refreshing token...');
139 const refreshToken = this.getRefreshToken();
141 let body = new URLSearchParams();
142 body.set('refresh_token', refreshToken);
143 body.set('client_id', this.clientId);
144 body.set('client_secret', this.clientSecret);
145 body.set('response_type', 'code');
146 body.set('grant_type', 'refresh_token');
148 let headers = new Headers();
149 headers.append('Content-Type', 'application/x-www-form-urlencoded');
155 return this.http.post(AuthService.BASE_TOKEN_URL, body.toString(), options)
156 .map(this.restExtractor.extractDataGet)
157 .map(res => this.handleRefreshToken(res))
158 .catch((res: Response) => {
159 // The refresh token is invalid?
160 if (res.status === 400 && res.json() && res.json().error === 'invalid_grant') {
161 console.error('Cannot refresh token -> logout...');
163 this.router.navigate(['/login']);
165 return Observable.throw({
167 text: () => 'You need to reconnect.'
171 return this.restExtractor.handleError(res);
175 private fetchUserInformations (obj: any) {
176 // Do not call authHttp here to avoid circular dependencies headaches
178 const headers = new Headers();
179 headers.set('Authorization', `Bearer ${obj.access_token}`);
181 return this.http.get(AuthService.BASE_USER_INFORMATIONS_URL, { headers })
182 .map(res => res.json())
191 private handleLogin (obj: any) {
193 const username = obj.username;
194 const role = obj.role;
196 access_token: obj.access_token,
197 token_type: obj.token_type,
198 refresh_token: obj.refresh_token
201 this.user = new AuthUser({ id, username, role }, hashTokens);
204 this.setStatus(AuthStatus.LoggedIn);
207 private handleRefreshToken (obj: any) {
208 this.user.refreshTokens(obj.access_token, obj.refresh_token);
212 private setStatus(status: AuthStatus) {
213 this.loginChanged.next(status);