import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import { Location } from '@angular/common'; import { Http, RequestOptions, Response, Headers } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import { LocalStorageService } from 'angular-2-local-storage'; const SECURIS_TOKEN = "X-SECURIS-TOKEN"; @Injectable() export class UserService { constructor(private router: Router, private store: LocalStorageService, private http: Http) { } public login(username: string, password: string) : Observable { let params = new URLSearchParams(); params.append('username', username); params.append('password', password); let options = new RequestOptions({ headers: new Headers({ "Content-Type": "application/x-www-form-urlencoded" })}); return this.http.post('user/login', params, options) .map((res: Response) => { let data = res.json(); this.store.set('username', username); this.store.set('token', data.token); return data.token; }) .catch(this.handleError); } isLoggedIn() : Observable { if (!this.existsToken()) { return Observable.of(false); } var token = this.store.get(SECURIS_TOKEN); return this.http.get('check', new RequestOptions({ headers: new Headers({ 'X-SECURIS-TOKEN': token }) })) .map((res: Response) => { let body = res.json(); if (body.valid) { this.store.set('user', body.user); } return body.valid; }) .catch(this.handleError) .catch(() => Observable.of(false)); } existsToken() : Boolean { return this.store.get(SECURIS_TOKEN) !== null; } logout() : void { this.store.remove('user', 'token'); this.router.navigate(['Login']); } private handleError (error: Response | any) { // In a real world app, we might use a remote logging infrastructure let errMsg: string; if (error instanceof Response) { const body = error.json() || ''; const err = body.error || JSON.stringify(body); errMsg = `${error.status} - ${error.statusText || ''} ${err}`; } else { errMsg = error.message ? error.message : error.toString(); } console.error(errMsg); return Observable.throw(errMsg); } }