1 import { Injectable } from '@angular/core';
2 import { Headers, Http, RequestOptions, Response, URLSearchParams } from '@angular/http';
3 import { Observable, Subject } from 'rxjs/Rx';
5 import { AuthStatus } from './auth-status.model';
6 import { User } from './user.model';
9 export class AuthService {
10 private static BASE_CLIENT_URL = '/api/v1/users/client';
11 private static BASE_LOGIN_URL = '/api/v1/users/token';
13 loginChangedSource: Observable<AuthStatus>;
15 private clientId: string;
16 private clientSecret: string;
17 private loginChanged: Subject<AuthStatus>;
19 constructor(private http: Http) {
20 this.loginChanged = new Subject<AuthStatus>();
21 this.loginChangedSource = this.loginChanged.asObservable();
23 // Fetch the client_id/client_secret
24 // FIXME: save in local storage?
25 this.http.get(AuthService.BASE_CLIENT_URL)
26 .map(res => res.json())
27 .catch(this.handleError)
30 this.clientId = result.client_id;
31 this.clientSecret = result.client_secret;
32 console.log('Client credentials loaded.');
40 getAuthRequestOptions(): RequestOptions {
41 return new RequestOptions({ headers: this.getRequestHeader() });
45 return new Headers({ 'Authorization': `${this.getTokenType()} ${this.getToken()}` });
49 return localStorage.getItem('access_token');
53 return localStorage.getItem('token_type');
57 if (this.isLoggedIn() === false) {
61 const user = User.load();
67 if (this.getToken()) {
74 login(username: string, password: string) {
75 let body = new URLSearchParams();
76 body.set('client_id', this.clientId);
77 body.set('client_secret', this.clientSecret);
78 body.set('response_type', 'code');
79 body.set('grant_type', 'password');
80 body.set('scope', 'upload');
81 body.set('username', username);
82 body.set('password', password);
84 let headers = new Headers();
85 headers.append('Content-Type', 'application/x-www-form-urlencoded');
91 return this.http.post(AuthService.BASE_LOGIN_URL, body.toString(), options)
92 .map(res => res.json())
93 .catch(this.handleError);
97 // TODO make HTTP request
100 setStatus(status: AuthStatus) {
101 this.loginChanged.next(status);
104 private handleError (error: Response) {
105 console.error(error);
106 return Observable.throw(error.json() || { error: 'Server error' });