import { Injectable } from '@angular/core' ; import { HttpClient , HttpErrorResponse } from '@angular/common/http' ; import { Observable } from 'rxjs' ; import { tap , map , switchMap , catchError } from 'rxjs/operators' ; import { AuthService } from 'ngx-auth' ; import { TokenStorage } from './token-storage.service' ; interface AccessData { accessToken : string ; refreshToken : string ; } @ Injectable ( ) export class AuthenticationService implements AuthService { constructor ( private http , private tokenStorage ) { } description returns { Observable < boolean > } memberOf public isAuthorized ( ) { return this . tokenStorage . getAccessToken ( ) . pipe ( map ( token => ! ! token ) ) ; } description returns { Observable < string > } public getAccessToken ( ) { return this . tokenStorage . getAccessToken ( ) ; } description returns { Observable < any > } public refreshToken ( ) { return this . tokenStorage . getRefreshToken ( ) . pipe ( switchMap ( ( refreshToken ) => this . http . post ( `http://localhost:3000/refresh` , { refreshToken } ) ) , tap ( ( tokens ) => this . saveAccessData ( tokens ) ) , catchError ( ( err ) => { this . logout ( ) ; return Observable . throw ( err ) ; } ) ) ; } description param { Response } response returns { boolean } public refreshShouldHappen ( response ) { return response . status === 401 ; } param { string } url returns { boolean } public verifyTokenRequest ( url ) { return url . endsWith ( '/refresh' ) ; } /**
     * EXTRA AUTH METHODS
     */ public login ( ) { return this . http . post ( `http://localhost:3000/login` , { } ) . pipe ( tap ( ( tokens ) => this . saveAccessData ( tokens ) ) ) ; } /**
     * Logout
     */ public logout ( ) { this . tokenStorage . clear ( ) ; location . reload ( true ) ; } private param { AccessData } data private saveAccessData ( { accessToken , refreshToken } ) { this . tokenStorage . setAccessToken ( accessToken ) . setRefreshToken ( refreshToken ) ; } }