import { Injectable } from '@angular/core' ; import * as auth0 from 'auth0-js' ; import { environment } from '../../environments/environment' ; import { Observable , BehaviorSubject , bindNodeCallback , of } from 'rxjs' ; import { Router } from '@angular/router' ; @ Injectable ( { providedIn : 'root' } ) export class AuthService { auth0 = new auth0 . WebAuth ( { clientID : environment . auth0 . clientID , domain : environment . auth0 . domain , responseType : 'token id_token' , redirectUri : environment . auth0 . redirectUri , scope : 'openid profile email' } ) ; private _authFlag = 'isLoggedIn' ; private _userProfileFlag = 'userProfile' ; token$ : Observable < string > ; userProfile$ = new BehaviorSubject < any > ( null ) ; onAuthSuccessUrl = '/' ; onAuthFailureUrl = '/' ; logoutUrl = environment . auth0 . logoutUrl ; parseHash$ = bindNodeCallback ( this . auth0 . parseHash . bind ( this . auth0 ) ) ; checkSession$ = bindNodeCallback ( this . auth0 . checkSession . bind ( this . auth0 ) ) ; constructor ( private router ) { const userProfile = localStorage . getItem ( this . _userProfileFlag ) ; if ( userProfile ) { this . userProfile$ . next ( JSON . parse ( userProfile ) ) ; } } login = ( ) => this . auth0 . authorize ( ) ; handleLoginCallback = ( ) => { if ( window . location . hash && ! this . authenticated ) { this . parseHash$ ( ) . subscribe ( { next : authResult => { this . _setAuth ( authResult ) ; window . location . hash = '' ; this . router . navigate ( [ this . onAuthSuccessUrl ] ) ; } , error : err => this . _handleError ( err ) } ) ; } } ; private _setAuth = authResult => { this . token$ = of ( authResult . accessToken ) ; const userProfile = authResult . idTokenPayload ; this . userProfile$ . next ( userProfile ) ; localStorage . setItem ( this . _userProfileFlag , JSON . stringify ( userProfile ) ) ; localStorage . setItem ( this . _authFlag , JSON . stringify ( true ) ) ; } ; get authenticated ( ) : boolean { return JSON . parse ( localStorage . getItem ( this . _authFlag ) ) ; } renewAuth ( ) { if ( this . authenticated ) { this . checkSession$ ( { } ) . subscribe ( { next : authResult => this . _setAuth ( authResult ) , error : err => { localStorage . removeItem ( this . _authFlag ) ; localStorage . removeItem ( this . _userProfileFlag ) ; this . router . navigate ( [ this . onAuthFailureUrl ] ) ; } } ) ; } } logout = ( ) => { localStorage . setItem ( this . _authFlag , JSON . stringify ( false ) ) ; localStorage . removeItem ( this . _userProfileFlag ) ; this . auth0 . logout ( { returnTo : this . logoutUrl , clientID : environment . auth0 . clientID } ) ; } ; private _handleError = err => { if ( err . error_description ) { console . error ( `Error: ${ err . error_description }` ) ; } else { console . error ( `Error: ${ JSON . stringify ( err ) }` ) ; } } ; }