/*-------------------------------------------------------------------------------------------------------------- * 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 { Injectable, Inject } from '@angular/core'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; import { IUserAuthStateService } from '../interfaces/IUserAuthStateService.interface'; import { IUserAuthenticationService, IUSERAUTHENTICATIONSERVICE_TOKEN } from '../interfaces/IUserAuthenticationService.interface'; import { AuthAction } from '../interfaces/AuthAction'; import { Subject } from 'rxjs/Subject'; import { Observable } from 'rxjs/Observable'; @Injectable() export class UserAuthStateService implements IUserAuthStateService { private _actionRequest: Subject; public username: string = ""; public level: string = ""; constructor(@Inject(IUSERAUTHENTICATIONSERVICE_TOKEN) private _userAuthenticationService: IUserAuthenticationService) { this._actionRequest = new Subject(); this.level = this._userAuthenticationService.InvalidUserLevel; } login(loginResult: (username: string, level: string, success: boolean) => void): void { return this.doLogin(this._userAuthenticationService.InvalidUserLevel, loginResult); } logout(): void { console.log("User " + this.username + " logged out."); this.username = ""; this.level = this._userAuthenticationService.InvalidUserLevel; } checkRequestedLevel(levelRequested: string, loginResult: (username: string, level: string, success: boolean) => void): void { if (this._userAuthenticationService.isSufficientLevel(this.level, levelRequested)) { loginResult(this.username, this.level, true); } else { this.doLogin(levelRequested, loginResult); } } private doLogin(levelRequested: string, loginResult: (username: string, level: string, success: boolean) => void): void { this._actionRequest.next(new AuthAction("login", this._userAuthenticationService, (username: string, level: string, success: boolean) => { if (success && (levelRequested === this._userAuthenticationService.InvalidUserLevel || this._userAuthenticationService.isSufficientLevel(level, levelRequested))) { this.username = username; this.level = level; } else { success = false; } loginResult(this.username, this.level, success); })); } actionRequest(): Subject { return this._actionRequest; } }