angularfire icon indicating copy to clipboard operation
angularfire copied to clipboard

Angularfire2 and Rxjs Observable Not firing Catch and Complete functions for getting auth data

Open hllink opened this issue 10 years ago • 11 comments

Hello, i'm getting the auth data on the OnInit method of my page to find out if the user is logged in or not via subscribing to af.auth as showed on this github readme file on the Override configuration / No config Example app section.. it works fine, but im forcing some errors for testing and give the proper treatment to it, i'm signing in with a google account, logging off and logging on with a github account (that have the same email adress) to force the error "An account already exists with the same email address but different sign-in credentials. Sign in using a provider associated with this email address." but the observable NEVER calls catch or the complete functions for some reason, it just show the following message on my console: errorjson

the code that subscrible to the auth state:

private subscribleAuth() {
    this.af.auth
        .subscribe(
            auth => {
                this._auth = auth && auth.auth ? auth.auth : null;
                if (this._auth) {
                    this.loginState = 'logged';
                } else {
                    this.loginState = 'login';
                }

            },
            err => {
                console.log('error'),
                    this.loginState = 'error';
            },
            () => { console.log('done.') }
        );
}

Some people on Stackoverflow said that i should use the af.auth.login to return the login state, but i'm using the redirect method, if i call the login every time the page loads to check the user state it redirects to the provider page, gets back to my page and it gets into an infinite loop.

hllink avatar Sep 27 '16 13:09 hllink

@hllink, even I am facing this issue. After spending quite a lot of time, I found a hack for it. Add these to your code.

import { AngularFire, AuthProviders } from 'angularfire2';
import { AuthBackend } from 'angularfire2/auth/auth_backend';

export class SocialmenuComponent {
    constructor(public af: AngularFire, private _authBackend: AuthBackend) {
        // this.af.auth.subscribe(
        this._authBackend.getRedirectResult().subscribe(
            (auth) => {
                if(auth) {
                  console.log(auth);
                } else {
                  console.log('User Not Logged In');
                }
            },
            (err) => {
                if(err) {
                  console.log('Error in auth.subscribe : ');
                  console.log(err);
                } else {
                  console.log('No Error detected in auth.subscribe');
                }
            },
            () => { console.log('done.') }
        );
    }
}

Ideally the af.auth.subscribe should give out the error. Maybe it's a bug. @jeffbcross I found this getRedirectResult() from one of your previous commits while fixing #271

yashmurty avatar Sep 29 '16 01:09 yashmurty

thank you for sharing this, gonna test it tomorrow, maybe the best is to leave this issue open until a fix.

hllink avatar Sep 29 '16 01:09 hllink

Something to bear in mind is that the auth observable is used to emit changes in the authentication state. If it is used to emit errors that result from failed attempts to sign in, that has consequences regarding the Observable Contract.

According to the Observable Termination section (emphasis added):

When an Observable does issue an OnCompleted or OnError notification, the Observable may release its resources and terminate, and its observers should not attempt to communicate with it any further.

My reading of this is that if the auth observable emits an error upon a failed sign in, it cannot be used after that point. Given that failed attempts to sign in are common, reporting the error via the auth observable isn't appropriate, as it would terminate the observable.

cartant avatar Sep 29 '16 01:09 cartant

@cartant, your understanding seems pretty accurate but is there another way to check / ping the state of your authentication ?

[EDIT] : I found a good Authentifiaction checker example which works perfectly for me https://github.com/seanmavley/AngularFire2-Authentication

`

constructor(private af: AngularFire, private router: Router) {
    this.af.auth.subscribe((auth) => console.log(auth));
}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {

    return this.af.auth.map((auth) =>  {
        if(auth == null) {
            this.router.navigate(['/login']);
            return false;
        } else {
            return true;
        }
    }).first()
}

}

`

mquentin avatar Sep 30 '16 13:09 mquentin

@mquentin the anchor is broken but the display text is correct for that link.

bliitzkrieg avatar Oct 15 '16 04:10 bliitzkrieg

I am having the same problem with this. If I want to allow login with all of the federated id's and it fails on email I am fine with this, but I want to be able to say would you like to add this login to the existing. So I don't see a way to catch this that works.

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthMethods,
  AuthProviders,
  defaultFirebase,
  AngularFire,
  FIREBASE_PROVIDERS,
  FirebaseListObservable,
  FirebaseAuthState,
  FirebaseApp } from 'angularfire2';

@Component({
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  // public allowFederated;
  constructor(
    public af: AngularFire,
    private router: Router
  ) {
    this.af.auth.subscribe(user => {
      if (user) {
        this.router.navigateByUrl("home");
      }
    }
      , (e) => {
        console.log('high');
        console.log(e);
      }
    );
  }

  ngOnInit() {
  }
  twitterLogin() {
    this.af.auth.login({
      provider: AuthProviders.Twitter,
      method: AuthMethods.Redirect,
      scope: ['email']
    })
    .catch(e => {
      console.log('twitter');
      console.log(e)
    });
  }
  googleLogin() {
    this.af.auth.login({
      provider: AuthProviders.Google,
      method: AuthMethods.Redirect,
      scope: ['email']
    }).catch(e => {
      console.log('google');
      console.log(e)
    });
  }
  facebookLogin() {
    this.af.auth.login({
      provider: AuthProviders.Facebook,
      method: AuthMethods.Redirect,
      scope: ['email'],
    }).catch(e => {
      console.log('facebook');
      console.log(e)
    });
  }
}

codercatdev avatar Nov 04 '16 12:11 codercatdev

Along the lines of what @cartant said, I don't think authentication errors should affect the auth observable, other than the effects that the error has on the auth state itself. I.e. if an error causes the state to become null, then it's reasonable that the auth observable would emit null. The auth observable is only concerned with the final state after auth operations have succeeded or failed, not with the operations themselves.

Watching the result of login() is the correct approach for non-redirect methods. For redirects, you should just inject the Firebase app and call getRedirectResult().

import { FirebaseApp } from 'angularfire2';
class MyComponent {
  constructor(@Inject(FirebaseApp) fbApp: firebase.App) {
    fbApp.auth().getRedirectResult().then(onSuccess, onError);
  }
}

I agree this isn't ideal. It's a by-product of the fact that your app gets thrown away and re-spawned, with no idea what just happened. It's not yet clear to me if/how AngularFire2 should solve the problem.

jeffbcross avatar Nov 14 '16 23:11 jeffbcross

In case anyone else is seeing this. When I run the following

return this.af.auth.map((auth) => { if (auth) { console.log('authenticated'); return true; } console.log('not authenticated'); this.router.navigateByUrl('/frontend'); return false; }).first();

I get an error this.af.auth.map(...).first is not a function

But it works perfectly when I removed the ".first()"

linuxninja39 avatar Feb 05 '17 19:02 linuxninja39

@linuxninja39 please file you own issue rather than repurposing existing (especially closed) issues. Glad to help, but not here.

katowulf avatar Feb 06 '17 20:02 katowulf

I have tried this solution and it still causes an exception from which I cannot recover from?

Is there any other solutions or is there a planned fix for this issue?

borntodesign avatar Mar 02 '17 09:03 borntodesign

import { FirebaseApp } from 'angularfire2';
class MyComponent {
  constructor(@Inject(FirebaseApp) fbApp: firebase.App) {
    fbApp.auth().getRedirectResult().then(onSuccess, onError);
  }
}

In this case, when it comes to getting auth/account-exists-with-different-credential, I also do not fully understand.

In the case of that error occurring, the onError's parameter will be an object which tells you the provider and for example secret (twitter). I believe we need to dig into the firebase. to create a TwitterAuthProvider.credential from this information.

But then everywhere says that you then use linkWithRedirect

But how can this be, from my perspective, there is no user so how would one link?

I don't really understand the actual expected sequence of events though, it appears to be undocumented. Am I supposed to tell the user that they can't sign in with this account, but instead, sign in with your other account first and then, later, lets start a new linking process? I was thinking that I could catch this error, and then link but that somehow doesn't make sense to me now that I read my response.

Edit - This SO sheds some light

linkWithCredential is used if you already have the oauth credential. The advantage here is that you don't need to open a popup or redirect. If you set "single account per email" in your project settings. If a user signs in with an email initially and then signs in with a OAuth provider that returns the same email, the backend will throw an error that the account exists. You will have to sign in to the first account and then link the OAuth provider account to it.

Finally having giving up on this linking process. I am similar to @borntodesign in that:

firebaseApp.auth().getRedirectResult().catch(error => {}}; still throws an exception.

clark-stevenson avatar Mar 06 '17 12:03 clark-stevenson