2
votes

I am new to Angular 4 and Firebase. I have created an authentication project using angular 4 and firebase. I am able to create a user and as well as able to sign in the newly created user.

After user logs in I get the authstate of the user as expected. Issue Occurs when I refresh the page or do ng serve in my angular CLI. The app reloads and my signed in user becomes a guest user.

This is my authenticationService.ts file.

import { Injectable } from '@angular/core';
import { Router } from "@angular/router";
import { AngularFireAuth } from 'angularfire2/auth';
import { AngularFireDatabaseModule, AngularFireDatabase } from 
'angularfire2/database';
import * as firebase from 'firebase/app';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class AuthService {
  authState: any = null;

  constructor(private afAuth: AngularFireAuth,
            private db: AngularFireDatabase,
            private router:Router,
            ) {
            this.afAuth.authState.subscribe((auth) => {
              this.authState = auth;
          });
  }

  // Returns true if user is logged in
  get authenticated(): boolean {
    return this.authState !== null;
  }

  // Returns current user data
  get currentUser(): any {
    return this.authenticated ? this.authState : null;
  }

  // Returns
  get currentUserObservable(): any {
    return this.afAuth.authState;
  }

  // Returns current user UID
  get currentUserId(): string {
    return this.authenticated ? this.authState.uid : '';
  }


  // Returns current user display name or Guest
  get currentUserDisplayName(): string {
    if (!this.authState) {
      return 'Guest';
    } else if (this.currentUserAnonymous) {
      return 'Anonymous';
    } else {
      return this.authState.email.substr(0, this.authState.email.indexOf('@'));
    }
  }


  //// Email/Password Auth ////

  // SignUp
  emailSignUp(email: string, password: string, uname: string) {
    return this.afAuth.auth.createUserWithEmailAndPassword(email, password).then((user) => {
      this.authState = user
      this.router.navigate(['/signin']);
      console.log('Registered Successfully ');        
    }).catch(error => console.log(error));
  }

  //SignIn
  emailLogin(email:string, password:string) {

    return this.afAuth.auth.signInWithEmailAndPassword(email, password).then((user) => {
       this.authState = user
       console.log("user details:",user);
       this.router.navigate(['/home']);
       console.log('Successfully Signed In');
     }).catch((error) => console.log(error));
   }

  //// Sign Out ////
  userSignOut(){
    this.afAuth.auth.signOut()
    .then((success) => {
      this.router.navigate(['/signin'])
      console.log(firebase.auth().currentUser);
    }).catch((error) =>{
      console.log(error);
    })
  }
}
1
I have only really dealt with oauth google login with angular not firebase but in my case I needed to save login information to sessionStorage or localStorage.Cacoon
I have tried tlocal storage in this issue..but still the authstate changes on refresh..Ashish Maity

1 Answers

2
votes

Instead of managing the authState with this variable:

authState: any = null;

Include this function in your service. I use it for that purpose, it returns a Promise.

isLoggedIn(){

    var promise = new Promise((resolve, reject) => {

      this.afAuth.authState.subscribe(res => {
        if (res && res.uid) {
          console.log('user is logged in');
          resolve(true);
        } else {
          console.log('user not logged in');
          resolve(false);
        }
      });
    });
    return promise;
}

You would use it like this in your main component:

this.auth.isLoggedIn().then((val) => {
        if(val){
            console.log('loggedIn');
        }else{
            console.log('not loggedIn');
        }
}

By default firebaseAuth stores the session in LocalStorage so you won't loose it after a page refresh since this is the right method to retrieve the session.