import { Injectable } from '@angular/core';
import { Headers, Http, Response, URLSearchParams } from '@angular/http';
+import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { AuthStatus } from './auth-status.model';
import { AuthUser } from './auth-user.model';
+import { RestExtractor } from '../rest';
@Injectable()
export class AuthService {
private loginChanged: Subject<AuthStatus>;
private user: AuthUser = null;
- constructor(private http: Http) {
+ constructor(
+ private http: Http,
+ private restExtractor: RestExtractor,
+ private router: Router
+ ) {
this.loginChanged = new Subject<AuthStatus>();
this.loginChangedSource = this.loginChanged.asObservable();
// Fetch the client_id/client_secret
// FIXME: save in local storage?
this.http.get(AuthService.BASE_CLIENT_URL)
- .map(res => res.json())
- .catch(this.handleError)
+ .map(this.restExtractor.extractDataGet)
+ .catch((res) => this.restExtractor.handleError(res))
.subscribe(
result => {
this.clientId = result.client_id;
console.log('Client credentials loaded.');
},
error => {
- alert(error);
+ alert(
+ `Cannot retrieve OAuth Client credentials: ${error.text}. \n` +
+ 'Ensure you have correctly configured PeerTube (config/ directory), in particular the "webserver" section.'
+ );
}
);
};
return this.http.post(AuthService.BASE_TOKEN_URL, body.toString(), options)
- .map(res => res.json())
+ .map(this.restExtractor.extractDataGet)
.map(res => {
res.username = username;
return res;
})
.flatMap(res => this.fetchUserInformations(res))
.map(res => this.handleLogin(res))
- .catch(this.handleError);
+ .catch((res) => this.restExtractor.handleError(res));
}
logout() {
// TODO: make an HTTP request to revoke the tokens
this.user = null;
+
AuthUser.flush();
this.setStatus(AuthStatus.LoggedOut);
};
return this.http.post(AuthService.BASE_TOKEN_URL, body.toString(), options)
- .map(res => res.json())
+ .map(this.restExtractor.extractDataGet)
.map(res => this.handleRefreshToken(res))
- .catch(this.handleError);
+ .catch((res: Response) => {
+ // The refresh token is invalid?
+ if (res.status === 400 && res.json() && res.json().error === 'invalid_grant') {
+ console.error('Cannot refresh token -> logout...');
+ this.logout();
+ this.router.navigate(['/login']);
+
+ return Observable.throw({
+ json: () => '',
+ text: () => 'You need to reconnect.'
+ });
+ }
+
+ return this.restExtractor.handleError(res);
+ });
}
private fetchUserInformations (obj: any) {
);
}
- private handleError (error: Response) {
- console.error(error);
- return Observable.throw(error.json() || { error: 'Server error' });
- }
-
private handleLogin (obj: any) {
const id = obj.id;
const username = obj.username;