import * as firebase from 'firebase' ; import { Injectable } from '@angular/core' ; import { Observable , from as fromPromise , of } from 'rxjs' ; import { map , switchMap , take , catchError } from 'rxjs/operators' ; import { AuthService } from './auth.service' ; import { LoginUser } from '../models/user' ; @ Injectable ( ) export class FirebaseAuthService extends AuthService { auth$ : Observable < LoginUser > ; requireAuth ( ) { return ( new Observable ( obs => firebase . auth ( ) . onIdTokenChanged ( obs ) ) . pipe ( switchMap ( user => ( user ? of ( user ) : fromPromise ( < Promise < any > > firebase . auth ( ) . signInAnonymously ( ) ) ) ) ) ) ; } requireAuthOnce ( ) { return this . requireAuth ( ) . pipe ( take ( 1 ) ) ; } refreshToken ( ) { return fromPromise ( < Promise < any > > firebase . auth ( ) . currentUser . getIdToken ( true ) ) ; } signOut ( ) { return fromPromise ( < Promise < any > > firebase . auth ( ) . signOut ( ) ) ; } signInWithCredential ( credential ) { const loginPromise = firebase . auth ( ) . signInAndRetrieveDataWithCredential ( credential ) . then ( result => result . user ) ; return fromPromise ( < Promise < any > > loginPromise ) ; } linkOrSignInWithGitHub ( ) { const linkPromise = firebase . auth ( ) . currentUser . linkWithPopup ( new firebase . auth . GithubAuthProvider ( ) ) ; return fromPromise ( < Promise < any > > linkPromise ) . pipe ( switchMap ( loginUser => this . signInWithCredential ( loginUser . credential ) ) , catchError ( error => this . signInWithCredential ( error . credential ) ) ) ; } }