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';
7 // Do not use the barrel (dependency loop)
8 import { AuthStatus } from '../../shared/auth/auth-status.model';
9 import { AuthUser } from '../../shared/auth/auth-user.model';
10 import { RestExtractor } from '../../shared/rest';
13 export class AuthService {
14 private static BASE_CLIENT_URL = '/api/v1/clients/local';
15 private static BASE_TOKEN_URL = '/api/v1/users/token';
16 private static BASE_USER_INFORMATIONS_URL = '/api/v1/users/me';
18 loginChangedSource: Observable<AuthStatus>;
20 private clientId: string;
21 private clientSecret: string;
22 private loginChanged: Subject<AuthStatus>;
23 private user: AuthUser = null;
27 private restExtractor: RestExtractor,
28 private router: Router
30 this.loginChanged = new Subject<AuthStatus>();
31 this.loginChangedSource = this.loginChanged.asObservable();
33 // Fetch the client_id/client_secret
34 // FIXME: save in local storage?
35 this.http.get(AuthService.BASE_CLIENT_URL)
36 .map(this.restExtractor.extractDataGet)
37 .catch((res) => this.restExtractor.handleError(res))
40 this.clientId = result.client_id;
41 this.clientSecret = result.client_secret;
42 console.log('Client credentials loaded.');
46 `Cannot retrieve OAuth Client credentials: ${error.text}. \n` +
47 'Ensure you have correctly configured PeerTube (config/ directory), in particular the "webserver" section.'
52 // Return null if there is nothing to load
53 this.user = AuthUser.load();
57 if (this.user === null) return null;
59 return this.user.getRefreshToken();
62 getRequestHeaderValue() {
63 return `${this.getTokenType()} ${this.getAccessToken()}`;
67 if (this.user === null) return null;
69 return this.user.getAccessToken();
73 if (this.user === null) return null;
75 return this.user.getTokenType();
83 if (this.user === null) return false;
85 return this.user.isAdmin();
89 if (this.getAccessToken()) {
96 login(username: string, password: string) {
97 let body = new URLSearchParams();
98 body.set('client_id', this.clientId);
99 body.set('client_secret', this.clientSecret);
100 body.set('response_type', 'code');
101 body.set('grant_type', 'password');
102 body.set('scope', 'upload');
103 body.set('username', username);
104 body.set('password', password);
106 let headers = new Headers();
107 headers.append('Content-Type', 'application/x-www-form-urlencoded');
113 return this.http.post(AuthService.BASE_TOKEN_URL, body.toString(), options)
114 .map(this.restExtractor.extractDataGet)
116 res.username = username;
119 .flatMap(res => this.fetchUserInformations(res))
120 .map(res => this.handleLogin(res))
121 .catch((res) => this.restExtractor.handleError(res));
125 // TODO: make an HTTP request to revoke the tokens
130 this.setStatus(AuthStatus.LoggedOut);
133 refreshAccessToken() {
134 console.log('Refreshing token...');
136 const refreshToken = this.getRefreshToken();
138 let body = new URLSearchParams();
139 body.set('refresh_token', refreshToken);
140 body.set('client_id', this.clientId);
141 body.set('client_secret', this.clientSecret);
142 body.set('response_type', 'code');
143 body.set('grant_type', 'refresh_token');
145 let headers = new Headers();
146 headers.append('Content-Type', 'application/x-www-form-urlencoded');
152 return this.http.post(AuthService.BASE_TOKEN_URL, body.toString(), options)
153 .map(this.restExtractor.extractDataGet)
154 .map(res => this.handleRefreshToken(res))
155 .catch((res: Response) => {
156 // The refresh token is invalid?
157 if (res.status === 400 && res.json() && res.json().error === 'invalid_grant') {
158 console.error('Cannot refresh token -> logout...');
160 this.router.navigate(['/login']);
162 return Observable.throw({
164 text: () => 'You need to reconnect.'
168 return this.restExtractor.handleError(res);
172 private fetchUserInformations (obj: any) {
173 // Do not call authHttp here to avoid circular dependencies headaches
175 const headers = new Headers();
176 headers.set('Authorization', `Bearer ${obj.access_token}`);
178 return this.http.get(AuthService.BASE_USER_INFORMATIONS_URL, { headers })
179 .map(res => res.json())
188 private handleLogin (obj: any) {
190 const username = obj.username;
191 const role = obj.role;
193 access_token: obj.access_token,
194 token_type: obj.token_type,
195 refresh_token: obj.refresh_token
198 this.user = new AuthUser({ id, username, role }, hashTokens);
201 this.setStatus(AuthStatus.LoggedIn);
204 private handleRefreshToken (obj: any) {
205 this.user.refreshTokens(obj.access_token, obj.refresh_token);
209 private setStatus(status: AuthStatus) {
210 this.loginChanged.next(status);