简体   繁体   中英

Firebase: Keep user logged in angular 7

I use firebase and angularfire2 within an authentication system!

The problem is that after refresh the user needs to log in again! I need to avoid that issue so I found out that firebase gives me that option by using authState

but still not working!

This the code for the authService:

import { Injectable } from '@angular/core';
import { AngularFireAuth } from 'angularfire2/auth';
import { Observable } from 'rxjs/internal/observable';
import { NavController } from '@ionic/angular';
import { ToastMessagesService } from './toast-messages.service';
import * as firebase from 'firebase';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  public user: Observable<firebase.User>;
  public userDetails: firebase.User = null;


  constructor(
    private af: AngularFireAuth,
    private navCtrl: NavController,
    private statusMessage: ToastMessagesService
  ) {

    this.user = af.authState;

    this.user.subscribe(
      user => this.userDetails = user
    )


  }

  async siginInRegular(username: string, password: string) {
    try {

      // const credentials = this.af.auth.email
      return await this.af.auth.signInWithEmailAndPassword(username, password).then(
        user => {
          if (user) {
            this.navCtrl.navigateForward('/home');
            this.statusMessage.message(`Welcome ${user.user.email}`);
          }
        },
        err => {
          console.log(err);
        }
      );
    } catch (error) {
      console.dir(error);
    }
  }

  async register(username: string, password: string) {
    try {
      return await this.af.auth.createUserWithEmailAndPassword(username, password).then(
        user => {
          this.navCtrl.navigateForward('/profile');
          this.statusMessage.message(`Welcome ${user.user.email}`);
        }
      );
    } catch (error) {
      console.dir(error);
    }
  }

  signOut() {
    return this.af.auth.signOut();
  }

  isLoggedIn(): boolean {
    return (this.userDetails != null) ? true : false;
  }


}

The guard code:

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
import { NavController } from '@ionic/angular';
import { AngularFireAuth } from 'angularfire2/auth';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {



  constructor(
    private auth: AuthService,
    private navCtrl: NavController,
    private af: AngularFireAuth
  ) {

  }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {


    if (this.auth.isLoggedIn()) {
      return true
    }

    console.log('Access denied!');
    return false;

  }
}

Firebase actually automatically will sign the user in when you reload the page. But since your handling of the sign-in is only in the then() block, it only happens when you explicitly sign them in.

To fix this, you want to use an onAuthState listener as shown in get the currently signed in user :

 firebase.auth().onAuthStateChanged(function(user) { if (user) { // User is signed in. } else { // No user is signed in. } }); 

Unlike the then() handler, this onAuthStateChanged handler will be called every time the user's authentication state changes, including when you reload the page.

Since you're using AngularFire2, you can also use af.auth.subscribe as shown here: How to get the firebase.User in AngularFire2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM