15

I have an ionic2 app and am using Firebase and angularFire2. I'd like to get the current authentication state and current auth object/user from firebase using angularFire2.

Here's what's working so far - I can authenticate the user and subscribe to the FirebaseAuthState to get the facebook user object.

  constructor(platform: Platform, private auth: FirebaseAuth) {

    auth.subscribe((user: FirebaseAuthState) => {
      if (user) {
        // I could store user in localstorage, but I'd like to see an All Firebase solution
        this.rootPage = TabsPage;
      } else {
        this.rootPage = LoginPage;
      }
    });

Now I can just set localstorage here and cache my user object to remember auth state. However, I am curious to see how I can use Firebase only without me implementing my own custom local storage key. I see that Firebase stores a localStorage key of it's own so knows that its logged in.

How can I get the auth object from code? Additionally, I tried the listed example in the AngularFire2 documentation to render the auth state in the template - but that gives me an error.

import {FirebaseAuth} from 'angularfire2';
@Component({
  selector: 'auth-status',
  template: `
    <div *ng-if="auth | async">You are logged in</div>
    <div *ng-if="!(auth | async)">Please log in</div>
  `
})
class App {
  constructor (@Inject(FirebaseAuth) public auth: FirebaseAuth) {}
}
MonkeyBonkey
  • 46,433
  • 78
  • 254
  • 460

4 Answers4

34
  1. Import: import { AngularFireAuth } from 'angularfire2/auth';
  2. Inject: constructor(public afAuth: AngularFireAuth) { }
  3. Check:

    this.afAuth.authState.subscribe(res => {
      if (res && res.uid) {
        console.log('user is logged in');
      } else {
        console.log('user not logged in');
      }
    });
    
Csaba
  • 1,945
  • 3
  • 28
  • 46
  • After a lot of confusing tutorials blending `AngularFire2` and `firebase` this is what actually worked after reading about `firebase.auth().onAuthStateChanged` from the official firebase docs. – rtpHarry Jul 29 '17 at 16:40
  • I really need to write this stuff in every single component to write this stuff in a observable variable? there is no simple way to access without so much extra code in every single component this information? – Budi Sep 17 '17 at 16:24
  • @Budi No. You can just write it once in a service. Your service subscribes to the state change, then you can set some state variable that's convenient to represent the relevant auth info for your components. Then you can inject this service into your components. – Chris Farmer Oct 23 '17 at 15:04
18

now in order to get the user info, you have to subscribe for getting the auth information. Ex

  constructor(public af: AngularFire) {
    this.af.auth.subscribe(auth => console.log(auth));// user info is inside auth object
  }

auth object will be null if auth state does not exist

afmeva
  • 839
  • 7
  • 13
  • Yup that's my approach as of my question: http://stackoverflow.com/questions/39205045/angularfire2-proper-approach-to-check-if-user-is-logged-in But I'm not sure if it's the right approach... – sandrooco Aug 29 '16 at 19:33
  • yes it is. This is the angularfire2 docs approach. I think if you want do some transformation on auth data you should use observables operators like map, flatmap. However, since you just want to check the user info this approach is fine. – afmeva Aug 29 '16 at 19:37
  • Do you have this code in constructor function for every page that requires user info? or store the user data in storage / localStorage then retrieve later on? In my case, nearly every page needs the user data (uid) for like/comment items, so I wonder is there any efficient ways to retrieve the user data? – William Wu Jul 16 '17 at 17:14
  • 1
    you can use something like a service (to provide) and inject through the different components. – afmeva Jul 26 '17 at 18:44
7

current authentication state is available from the injected FirebaseAuth. You can get the actual auth data auth.getAuth()

See: https://github.com/angular/angularfire2/blob/master/src/providers/auth.ts#L99

Aaron Saunders
  • 33,180
  • 5
  • 60
  • 80
2

You can simply import AngularFireAuth and do this:

this.angularFireAuth.authState.subscribe(userResponse => {
  if (userResponse) {
    console.log('here is your user data');
    localStorage.setItem('user', JSON.stringify(userResponse));
    console.log(userResponse);
  } else {
    localStorage.setItem('user', null);
  }
});

Here i am also using localStorage to save all data of my current user active on my app.