import { Injectable } from '@angular/core' ; import { JhiLanguageService } from 'ng-jhipster' ; import { SessionStorageService } from 'ngx-webstorage' ; import { HttpClient , HttpResponse } from '@angular/common/http' ; import { Observable , Subject } from 'rxjs' ; import { SERVER_API_URL } from 'app/app.constants' ; import { Account } from 'app/core/user/account.model' ; @ Injectable ( { providedIn : 'root' } ) export class AccountService { private userIdentity : any ; private authenticated = false ; private authenticationState = new Subject < any > ( ) ; constructor ( private languageService , private sessionStorage , private http ) { } fetch ( ) { return this . http . get < Account > ( SERVER_API_URL + 'api/account' , { observe : 'response' } ) ; } save ( account ) { return this . http . post ( SERVER_API_URL + 'api/account' , account , { observe : 'response' } ) ; } authenticate ( identity ) { this . userIdentity = identity ; this . authenticated = identity !== null ; this . authenticationState . next ( this . userIdentity ) ; } hasAnyAuthority ( authorities ) { if ( ! this . authenticated || ! this . userIdentity || ! this . userIdentity . authorities ) { return false ; } for ( let i = 0 ; i < authorities . length ; i ++ ) { if ( this . userIdentity . authorities . includes ( authorities [ i ] ) ) { return true ; } } return false ; } hasAuthority ( authority ) { if ( ! this . authenticated ) { return Promise . resolve ( false ) ; } return this . identity ( ) . then ( id => { return Promise . resolve ( id . authorities && id . authorities . includes ( authority ) ) ; } , ( ) => { return Promise . resolve ( false ) ; } ) ; } identity ( force ? ) { if ( force ) { this . userIdentity = undefined ; } if ( this . userIdentity ) { return Promise . resolve ( this . userIdentity ) ; } return this . fetch ( ) . toPromise ( ) . then ( response => { const account = response . body ; if ( account ) { this . userIdentity = account ; this . authenticated = true ; if ( this . userIdentity . langKey ) { const langKey = this . sessionStorage . retrieve ( 'locale' ) || this . userIdentity . langKey ; this . languageService . changeLanguage ( langKey ) ; } } else { this . userIdentity = null ; this . authenticated = false ; } this . authenticationState . next ( this . userIdentity ) ; return this . userIdentity ; } ) . catch ( err => { this . userIdentity = null ; this . authenticated = false ; this . authenticationState . next ( this . userIdentity ) ; return null ; } ) ; } isAuthenticated ( ) { return this . authenticated ; } isIdentityResolved ( ) { return this . userIdentity !== undefined ; } getAuthenticationState ( ) { return this . authenticationState . asObservable ( ) ; } getImageUrl ( ) { return this . isIdentityResolved ( ) ? this . userIdentity . imageUrl : null ; } }