import { Observable } from 'rxjs/Observable' ; import { Injectable } from '@angular/core' ; import { Store } from '@ngrx/store' ; import { AngularFireAuth } from 'angularfire2/auth' ; import { Network } from '@ionic-native/network' ; import * as firebase from 'firebase/app' ; import { AppState , IUser , ICredential , IAuthState } from '../../reducers' ; import { addAuthCredential , cleanAuth , logout , login } from '../../actions' ; @ Injectable ( ) export class AuthProvider { isOnline : boolean = navigator . onLine ; constructor ( public afAuth , public store , private network ) { this . network . onConnect ( ) . subscribe ( ( ) => this . isOnline = true ) ; this . network . onDisconnect ( ) . subscribe ( ( ) => this . isOnline = false ) ; } run ( ) { const credential = this . getCredential ( ) ; if ( credential ) { this . afAuth . auth . signInAndRetrieveDataWithCredential ( firebase . auth . TwitterAuthProvider . credential ( credential . access_token_key , credential . access_token_secret ) ) . then ( result => this . store . dispatch ( addAuthCredential ( result . credential ) ) , error => { this . isOnline && this . logout ( ) ; } ) ; } else { this . logout ( ) ; } this . afAuth . authState . distinctUntilChanged ( ) . subscribe ( ( user ) => { console . log ( 'authState user' , user ) ; if ( ! user ) return ; this . store . dispatch ( login ( user . toJSON ( ) ) ) ; } , ( ) => { this . store . dispatch ( cleanAuth ( ) ) ; } ) ; } login ( ) { return this . afAuth . auth . signInWithPopup ( new firebase . auth . TwitterAuthProvider ( ) ) . then ( result => this . store . dispatch ( addAuthCredential ( result . credential ) ) ) ; } logout ( ) { this . afAuth . auth . signOut ( ) ; this . store . dispatch ( logout ( ) ) ; } isAuthenticated$ ( ) { return this . store . select ( state => state . auth ) . map ( ( { credential , user } ) => credential !== null && user !== null ) ; } isAuthenticated ( ) { let isAuthenticated ; this . isAuthenticated$ ( ) . first ( ) . subscribe ( isAuth => isAuthenticated = isAuth ) ; return isAuthenticated ; } getCredential$ ( ) { return this . store . select ( state => state . auth . credential ) ; } getCredential ( ) { let credentialData ; this . getCredential$ ( ) . first ( ) . subscribe ( ( credential ) => { console . log ( 'credential2' , credential ) ; return credentialData = credential ; } ) ; return credentialData ; } getUser$ ( ) { return this . store . select ( state => state . auth . user ) ; } getUser ( ) { let userData ; this . getUser$ ( ) . first ( ) . subscribe ( ( user ) => userData = user ) ; return userData ; } getProvider$ ( ) { return this . store . select ( state => state . auth . provider ) ; } getProvider ( ) { let providerData ; this . getProvider$ ( ) . first ( ) . subscribe ( ( provider ) => providerData = provider ) ; console . log ( 'getProvider' , providerData ) ; return providerData ; } }