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 import { AuthStatus } from './auth-status.model';
8 import { AuthUser } from './auth-user.model';
9 import { RestExtractor } from '../rest';
12 export class AuthService {
13 private static BASE_CLIENT_URL = '/api/v1/clients/local';
14 private static BASE_TOKEN_URL = '/api/v1/users/token';
15 private static BASE_USER_INFORMATIONS_URL = '/api/v1/users/me';
17 loginChangedSource: Observable<AuthStatus>;
19 private clientId: string;
20 private clientSecret: string;
21 private loginChanged: Subject<AuthStatus>;
22 private user: AuthUser = null;
26 private restExtractor: RestExtractor,
27 private router: Router
29 this.loginChanged = new Subject<AuthStatus>();
30 this.loginChangedSource = this.loginChanged.asObservable();
32 // Fetch the client_id/client_secret
33 // FIXME: save in local storage?
34 this.http.get(AuthService.BASE_CLIENT_URL)
35 .map(this.restExtractor.extractDataGet)
36 .catch((res) => this.restExtractor.handleError(res))
39 this.clientId = result.client_id;
40 this.clientSecret = result.client_secret;
41 console.log('Client credentials loaded.');
45 `Cannot retrieve OAuth Client credentials: ${error.text}. \n` +
46 'Ensure you have correctly configured PeerTube (config/ directory), in particular the "webserver" section.'
51 // Return null if there is nothing to load
52 this.user = AuthUser.load();
56 if (this.user === null) return null;
58 return this.user.getRefreshToken();
61 getRequestHeaderValue() {
62 return `${this.getTokenType()} ${this.getAccessToken()}`;
66 if (this.user === null) return null;
68 return this.user.getAccessToken();
72 if (this.user === null) return null;
74 return this.user.getTokenType();
82 if (this.user === null) return false;
84 return this.user.isAdmin();
88 if (this.getAccessToken()) {
95 login(username: string, password: string) {
96 let body = new URLSearchParams();
97 body.set('client_id', this.clientId);
98 body.set('client_secret', this.clientSecret);
99 body.set('response_type', 'code');
100 body.set('grant_type', 'password');
101 body.set('scope', 'upload');
102 body.set('username', username);
103 body.set('password', password);
105 let headers = new Headers();
106 headers.append('Content-Type', 'application/x-www-form-urlencoded');
112 return this.http.post(AuthService.BASE_TOKEN_URL, body.toString(), options)
113 .map(this.restExtractor.extractDataGet)
115 res.username = username;
118 .flatMap(res => this.fetchUserInformations(res))
119 .map(res => this.handleLogin(res))
120 .catch((res) => this.restExtractor.handleError(res));
124 // TODO: make an HTTP request to revoke the tokens
129 this.setStatus(AuthStatus.LoggedOut);
132 refreshAccessToken() {
133 console.log('Refreshing token...');
135 const refreshToken = this.getRefreshToken();
137 let body = new URLSearchParams();
138 body.set('refresh_token', refreshToken);
139 body.set('client_id', this.clientId);
140 body.set('client_secret', this.clientSecret);
141 body.set('response_type', 'code');
142 body.set('grant_type', 'refresh_token');
144 let headers = new Headers();
145 headers.append('Content-Type', 'application/x-www-form-urlencoded');
151 return this.http.post(AuthService.BASE_TOKEN_URL, body.toString(), options)
152 .map(this.restExtractor.extractDataGet)
153 .map(res => this.handleRefreshToken(res))
154 .catch((res: Response) => {
155 // The refresh token is invalid?
156 if (res.status === 400 && res.json() && res.json().error === 'invalid_grant') {
157 console.error('Cannot refresh token -> logout...');
159 this.router.navigate(['/login']);
161 return Observable.throw({
163 text: () => 'You need to reconnect.'
167 return this.restExtractor.handleError(res);
171 private fetchUserInformations (obj: any) {
172 // Do not call authHttp here to avoid circular dependencies headaches
174 const headers = new Headers();
175 headers.set('Authorization', `Bearer ${obj.access_token}`);
177 return this.http.get(AuthService.BASE_USER_INFORMATIONS_URL, { headers })
178 .map(res => res.json())
187 private handleLogin (obj: any) {
189 const username = obj.username;
190 const role = obj.role;
192 access_token: obj.access_token,
193 token_type: obj.token_type,
194 refresh_token: obj.refresh_token
197 this.user = new AuthUser({ id, username, role }, hashTokens);
200 this.setStatus(AuthStatus.LoggedIn);
203 private handleRefreshToken (obj: any) {
204 this.user.refreshTokens(obj.access_token, obj.refresh_token);
208 private setStatus(status: AuthStatus) {
209 this.loginChanged.next(status);