import { Injectable } from '@angular/core' ; import { HttpClient } from '@angular/common/http' ; import { Observable } from 'rxjs' ; import { map } from 'rxjs/operators' ; import { LocalStorageService , SessionStorageService } from 'ngx-webstorage' ; import { ApplicationConfigService } from '../config/application-config.service' ; import { Login } from 'app/login/login.model' ; type JwtToken = { id_token : string ; } ; @ Injectable ( { providedIn : 'root' } ) export class AuthServerProvider { constructor ( private http , private localStorageService , private sessionStorageService , private applicationConfigService ) { } getToken ( ) { const tokenInLocalStorage = this . localStorageService . retrieve ( 'authenticationToken' ) ; const tokenInSessionStorage = this . sessionStorageService . retrieve ( 'authenticationToken' ) ; return tokenInLocalStorage ?? tokenInSessionStorage ?? '' ; } login ( credentials ) { return this . http . post < JwtToken > ( this . applicationConfigService . getEndpointFor ( 'api/authenticate' ) , credentials ) . pipe ( map ( response => this . authenticateSuccess ( response , credentials . rememberMe ) ) ) ; } logout ( ) { return new Observable ( observer => { this . localStorageService . clear ( 'authenticationToken' ) ; this . sessionStorageService . clear ( 'authenticationToken' ) ; observer . complete ( ) ; } ) ; } private authenticateSuccess ( response , rememberMe ) { const jwt = response . id_token ; if ( rememberMe ) { this . localStorageService . store ( 'authenticationToken' , jwt ) ; this . sessionStorageService . clear ( 'authenticationToken' ) ; } else { this . sessionStorageService . store ( 'authenticationToken' , jwt ) ; this . localStorageService . clear ( 'authenticationToken' ) ; } } }