import { ExperimentListResponse, ExperimentPrivilege } from './../interfaces/experiments'; import { AppConfig } from './../app-config.interface'; import { APP_CONFIG } from './../app-config'; import { Http, URLSearchParams } from '@angular/http'; import { Injectable, Inject } from '@angular/core'; import { Observable } from "rxjs/Observable"; @Injectable() export class UserService { public redirectUrl: string; private AUTH_PRIV = 'auth_privileges'; private AUTH_ID = 'auth_id'; private apiUrl; get id() { return JSON.parse(localStorage.getItem(this.AUTH_ID)); } set id(value) { localStorage.setItem(this.AUTH_ID, JSON.stringify(value)); } get privileges(): ExperimentPrivilege[] { return JSON.parse(localStorage.getItem(this.AUTH_PRIV)); }; set privileges(value) { localStorage.setItem(this.AUTH_PRIV, JSON.stringify(value)); } constructor( @Inject(APP_CONFIG) config: AppConfig, private http: Http) { this.apiUrl = config.apiEndpoint; } login(email: string, password: string): Promise { const url = `${this.apiUrl}/experiment/list`; const search = new URLSearchParams(); search.set('email', email); search.set('password', password); const options = { search }; return this.http.get(url, options) .timeoutWith(4000, Observable.throw('timeout')) .toPromise() .then(result => result.json()) .then(result => result.content) .then((content: ExperimentListResponse) => { this.id = content.user.id; this.privileges = content.privileges; }).catch(error => { if (error === 'timeout') { throw new Error('Operation timed out.') } else if (error.status === 401) { throw new Error('Email or password doesn\'t match'); } else { throw new Error('Something went wrong :('); } }); } loggedIn() { return !!this.privileges; } logout() { localStorage.removeItem(this.AUTH_PRIV); localStorage.removeItem(this.AUTH_ID); // todo: invalidate token on backend } }