1 import { Injectable } from '@angular/core';
2 import { Headers, Http, Response, URLSearchParams } from '@angular/http';
3 import { Observable } from 'rxjs/Observable';
4 import { Subject } from 'rxjs/Subject';
6 import { AuthStatus } from './auth-status.model';
7 import { User } from './user.model';
10 export class AuthService {
11 private static BASE_CLIENT_URL = '/api/v1/clients/local';
12 private static BASE_TOKEN_URL = '/api/v1/users/token';
13 private static BASE_USER_INFORMATIONS_URL = '/api/v1/users/me';
15 loginChangedSource: Observable<AuthStatus>;
17 private clientId: string;
18 private clientSecret: string;
19 private loginChanged: Subject<AuthStatus>;
20 private user: User = null;
22 constructor(private http: Http) {
23 this.loginChanged = new Subject<AuthStatus>();
24 this.loginChangedSource = this.loginChanged.asObservable();
26 // Fetch the client_id/client_secret
27 // FIXME: save in local storage?
28 this.http.get(AuthService.BASE_CLIENT_URL)
29 .map(res => res.json())
30 .catch(this.handleError)
33 this.clientId = result.client_id;
34 this.clientSecret = result.client_secret;
35 console.log('Client credentials loaded.');
42 // Return null if there is nothing to load
43 this.user = User.load();
47 if (this.user === null) return null;
49 return this.user.getRefreshToken();
52 getRequestHeaderValue() {
53 return `${this.getTokenType()} ${this.getAccessToken()}`;
57 if (this.user === null) return null;
59 return this.user.getAccessToken();
63 if (this.user === null) return null;
65 return this.user.getTokenType();
73 if (this.getAccessToken()) {
80 login(username: string, password: string) {
81 let body = new URLSearchParams();
82 body.set('client_id', this.clientId);
83 body.set('client_secret', this.clientSecret);
84 body.set('response_type', 'code');
85 body.set('grant_type', 'password');
86 body.set('scope', 'upload');
87 body.set('username', username);
88 body.set('password', password);
90 let headers = new Headers();
91 headers.append('Content-Type', 'application/x-www-form-urlencoded');
97 return this.http.post(AuthService.BASE_TOKEN_URL, body.toString(), options)
98 .map(res => res.json())
100 res.username = username;
103 .flatMap(res => this.fetchUserInformations(res))
104 .map(res => this.handleLogin(res))
105 .catch(this.handleError);
109 // TODO: make an HTTP request to revoke the tokens
113 this.setStatus(AuthStatus.LoggedOut);
116 refreshAccessToken() {
117 console.log('Refreshing token...');
119 const refreshToken = this.getRefreshToken();
121 let body = new URLSearchParams();
122 body.set('refresh_token', refreshToken);
123 body.set('client_id', this.clientId);
124 body.set('client_secret', this.clientSecret);
125 body.set('response_type', 'code');
126 body.set('grant_type', 'refresh_token');
128 let headers = new Headers();
129 headers.append('Content-Type', 'application/x-www-form-urlencoded');
135 return this.http.post(AuthService.BASE_TOKEN_URL, body.toString(), options)
136 .map(res => res.json())
137 .map(res => this.handleRefreshToken(res))
138 .catch(this.handleError);
141 private fetchUserInformations (obj: any) {
142 // Do not call authHttp here to avoid circular dependencies headaches
144 const headers = new Headers();
145 headers.set('Authorization', `Bearer ${obj.access_token}`);
147 return this.http.get(AuthService.BASE_USER_INFORMATIONS_URL, { headers })
148 .map(res => res.json())
157 private handleError (error: Response) {
158 console.error(error);
159 return Observable.throw(error.json() || { error: 'Server error' });
162 private handleLogin (obj: any) {
164 const username = obj.username;
165 const role = obj.role;
166 const hash_tokens = {
167 access_token: obj.access_token,
168 token_type: obj.token_type,
169 refresh_token: obj.refresh_token
172 this.user = new User(id, username, role, hash_tokens);
175 this.setStatus(AuthStatus.LoggedIn);
178 private handleRefreshToken (obj: any) {
179 this.user.refreshTokens(obj.access_token, obj.refresh_token);
183 private setStatus(status: AuthStatus) {
184 this.loginChanged.next(status);