1 import { Injectable } from '@angular/core';
2 import { Headers, Http, 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';
8 import { RestExtractor } from '../rest';
11 export class AuthService {
12 private static BASE_CLIENT_URL = '/api/v1/clients/local';
13 private static BASE_TOKEN_URL = '/api/v1/users/token';
14 private static BASE_USER_INFORMATIONS_URL = '/api/v1/users/me';
16 loginChangedSource: Observable<AuthStatus>;
18 private clientId: string;
19 private clientSecret: string;
20 private loginChanged: Subject<AuthStatus>;
21 private user: AuthUser = null;
23 constructor(private http: Http, private restExtractor: RestExtractor) {
24 this.loginChanged = new Subject<AuthStatus>();
25 this.loginChangedSource = this.loginChanged.asObservable();
27 // Fetch the client_id/client_secret
28 // FIXME: save in local storage?
29 this.http.get(AuthService.BASE_CLIENT_URL)
30 .map(this.restExtractor.extractDataGet)
31 .catch((res) => this.restExtractor.handleError(res))
34 this.clientId = result.client_id;
35 this.clientSecret = result.client_secret;
36 console.log('Client credentials loaded.');
43 // Return null if there is nothing to load
44 this.user = AuthUser.load();
48 if (this.user === null) return null;
50 return this.user.getRefreshToken();
53 getRequestHeaderValue() {
54 return `${this.getTokenType()} ${this.getAccessToken()}`;
58 if (this.user === null) return null;
60 return this.user.getAccessToken();
64 if (this.user === null) return null;
66 return this.user.getTokenType();
74 if (this.user === null) return false;
76 return this.user.isAdmin();
80 if (this.getAccessToken()) {
87 login(username: string, password: string) {
88 let body = new URLSearchParams();
89 body.set('client_id', this.clientId);
90 body.set('client_secret', this.clientSecret);
91 body.set('response_type', 'code');
92 body.set('grant_type', 'password');
93 body.set('scope', 'upload');
94 body.set('username', username);
95 body.set('password', password);
97 let headers = new Headers();
98 headers.append('Content-Type', 'application/x-www-form-urlencoded');
104 return this.http.post(AuthService.BASE_TOKEN_URL, body.toString(), options)
105 .map(this.restExtractor.extractDataGet)
107 res.username = username;
110 .flatMap(res => this.fetchUserInformations(res))
111 .map(res => this.handleLogin(res))
112 .catch((res) => this.restExtractor.handleError(res));
116 // TODO: make an HTTP request to revoke the tokens
120 this.setStatus(AuthStatus.LoggedOut);
123 refreshAccessToken() {
124 console.log('Refreshing token...');
126 const refreshToken = this.getRefreshToken();
128 let body = new URLSearchParams();
129 body.set('refresh_token', refreshToken);
130 body.set('client_id', this.clientId);
131 body.set('client_secret', this.clientSecret);
132 body.set('response_type', 'code');
133 body.set('grant_type', 'refresh_token');
135 let headers = new Headers();
136 headers.append('Content-Type', 'application/x-www-form-urlencoded');
142 return this.http.post(AuthService.BASE_TOKEN_URL, body.toString(), options)
143 .map(this.restExtractor.extractDataGet)
144 .map(res => this.handleRefreshToken(res))
145 .catch((res) => this.restExtractor.handleError(res));
148 private fetchUserInformations (obj: any) {
149 // Do not call authHttp here to avoid circular dependencies headaches
151 const headers = new Headers();
152 headers.set('Authorization', `Bearer ${obj.access_token}`);
154 return this.http.get(AuthService.BASE_USER_INFORMATIONS_URL, { headers })
155 .map(res => res.json())
164 private handleLogin (obj: any) {
166 const username = obj.username;
167 const role = obj.role;
169 access_token: obj.access_token,
170 token_type: obj.token_type,
171 refresh_token: obj.refresh_token
174 this.user = new AuthUser({ id, username, role }, hashTokens);
177 this.setStatus(AuthStatus.LoggedIn);
180 private handleRefreshToken (obj: any) {
181 this.user.refreshTokens(obj.access_token, obj.refresh_token);
185 private setStatus(status: AuthStatus) {
186 this.loginChanged.next(status);