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 { AuthUser } from './auth-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: AuthUser = 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 = AuthUser.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.user === null) return false;
75 return this.user.isAdmin();
79 if (this.getAccessToken()) {
86 login(username: string, password: string) {
87 let body = new URLSearchParams();
88 body.set('client_id', this.clientId);
89 body.set('client_secret', this.clientSecret);
90 body.set('response_type', 'code');
91 body.set('grant_type', 'password');
92 body.set('scope', 'upload');
93 body.set('username', username);
94 body.set('password', password);
96 let headers = new Headers();
97 headers.append('Content-Type', 'application/x-www-form-urlencoded');
103 return this.http.post(AuthService.BASE_TOKEN_URL, body.toString(), options)
104 .map(res => res.json())
106 res.username = username;
109 .flatMap(res => this.fetchUserInformations(res))
110 .map(res => this.handleLogin(res))
111 .catch(this.handleError);
115 // TODO: make an HTTP request to revoke the tokens
119 this.setStatus(AuthStatus.LoggedOut);
122 refreshAccessToken() {
123 console.log('Refreshing token...');
125 const refreshToken = this.getRefreshToken();
127 let body = new URLSearchParams();
128 body.set('refresh_token', refreshToken);
129 body.set('client_id', this.clientId);
130 body.set('client_secret', this.clientSecret);
131 body.set('response_type', 'code');
132 body.set('grant_type', 'refresh_token');
134 let headers = new Headers();
135 headers.append('Content-Type', 'application/x-www-form-urlencoded');
141 return this.http.post(AuthService.BASE_TOKEN_URL, body.toString(), options)
142 .map(res => res.json())
143 .map(res => this.handleRefreshToken(res))
144 .catch(this.handleError);
147 private fetchUserInformations (obj: any) {
148 // Do not call authHttp here to avoid circular dependencies headaches
150 const headers = new Headers();
151 headers.set('Authorization', `Bearer ${obj.access_token}`);
153 return this.http.get(AuthService.BASE_USER_INFORMATIONS_URL, { headers })
154 .map(res => res.json())
163 private handleError (error: Response) {
164 console.error(error);
165 return Observable.throw(error.json() || { error: 'Server error' });
168 private handleLogin (obj: any) {
170 const username = obj.username;
171 const role = obj.role;
173 access_token: obj.access_token,
174 token_type: obj.token_type,
175 refresh_token: obj.refresh_token
178 this.user = new AuthUser({ id, username, role }, hashTokens);
181 this.setStatus(AuthStatus.LoggedIn);
184 private handleRefreshToken (obj: any) {
185 this.user.refreshTokens(obj.access_token, obj.refresh_token);
189 private setStatus(status: AuthStatus) {
190 this.loginChanged.next(status);