/*-------------------------------------------------------------------------------------------------------------- * Copyright (c) insite-gmbh. All rights reserved. * Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------------------------*/ import { Observable, Subscription } from 'rxjs/Rx'; import { Injectable, Inject } from '@angular/core'; import { Http, Headers } from '@angular/http'; import { InaxConfiguration } from '../inaxConfiguration'; import { ServiceAuthentication } from './serviceAuthentication'; import { IINAXCONFIGSERVICE_TOKEN, IInaxConfigService, IInaxConfig } from '../interfaces/IInaxConfigService.interface'; import { Guid } from '../guid'; class ChangeSubscriber{ id:Guid; constructor(public callback:()=>void){ this.id = Guid.newGuid(); } } @Injectable() export class ProfileService { private _authData: ServiceAuthentication = null; private _configSubscription: Subscription; private _configuration: InaxConfiguration; private _subscribers: Array = []; constructor(private _http: Http, @Inject(IINAXCONFIGSERVICE_TOKEN) private _configurationService: IInaxConfigService) { this._authData = JSON.parse(localStorage.getItem('auth_token')); this._configSubscription = _configurationService .getConfiguration() .subscribe( (configSettings: IInaxConfig) => { this._configuration = _configurationService as InaxConfiguration; this.login(this._configuration.Username, this._configuration.Password) .subscribe((result) => { if(result) { this._subscribers.forEach(sub => { try { sub.callback(); } catch(error) { console.error(error); } }); } }); }); } public addSubscriber(callback:()=>void):Guid{ let sub = new ChangeSubscriber(callback); this._subscribers.push(sub) return sub.id; } public removeSubscriber(id:Guid){ let idx = this._subscribers.findIndex(s => s.id === id) if (idx >= 0) { this._subscribers.splice(idx, 1); } } public isAuthenticated() { return this._authData != null && this._authData.Authenticated && new Date(this._authData.TokenExpires) > new Date(); } public roles(): Array { return this._authData != null && this._authData.Authenticated ? this._authData.Roles : new Array(); } public addAuthorization(headers: Headers): Headers { this.ensureAuthenticated(); headers.append('Content-Type', 'application/json'); let authToken = JSON.parse(localStorage.getItem('auth_token')); headers.append('Authorization', `Bearer ${authToken.Token}`); return headers; } public getUserInfo(): Observable { let url = this._configuration.buildRestUrl("Account","Logon"); let headers = this.addAuthorization(new Headers()); return this._http.get(url, { headers: headers }).map(res => res.json()); } public getToken(): string{ try { let authToken = localStorage.getItem('auth_token'); return JSON.parse(authToken).Token; } catch (error) { console.warn("invald authentication token!") } return null; } public ensureAuthenticated(throwException: boolean = false): boolean { let loggedIn = false; try { if (this._authData != null) { loggedIn = ((new Date(this._authData.TokenExpires).valueOf() - Date.now().valueOf()) > 0); } else { var token = localStorage.getItem('auth_token'); if (token != null) { this._authData = JSON.parse(token); loggedIn = ((new Date(this._authData.TokenExpires).valueOf() - Date.now().valueOf()) > 0); } } } catch (error) { console.warn(error); this._authData = null; } if (throwException && !loggedIn) throw "not authenticated"; return loggedIn; } public login(username: string, password: string): Observable { let url = this._configuration.Url + "token"; let headers = new Headers(); headers.append('Content-Type', 'application/x-www-form-urlencoded'); let data = "grant_type=password&username=" + username + "&password=" + password; return this._http .post(url, data, { headers }) .map(res => res.json()) .map((result: any) => { try { if (result != null) { this._authData = new ServiceAuthentication; this._authData.UserName = result.userName; this._authData.UserRetreived = false; this._authData.Token = result.access_token; this._authData.TokenExpires = result[".expires"]; this._authData.Authenticated = new Date(this._authData.TokenExpires) > new Date(); if(this._authData.Authenticated){ localStorage.setItem('auth_token', JSON.stringify(this._authData)); console.warn("Authenticated!"); return true; }else { localStorage.removeItem('auth_token'); console.warn("Not Authenticated!"); return false; } } else { console.warn("Not Authenticated!"); return false; } } catch (error) { localStorage.removeItem('auth_token'); console.warn(error); return false; } }); } public logout() { let url = this._configuration.buildRestUrl("Account","Logout"); if (this._authData != null) this._authData.Authenticated = false; return this._http.post(url, null).map(res => res.json()).subscribe(res => { localStorage.removeItem('auth_token'); }); } public UnauthorizedResult() { this.logout(); } }