如何在ionic 4应用程序中使用Firebase保持用户永久登录

时间:2019-02-24 12:50:10

标签: javascript firebase ionic-framework firebase-authentication angularfire2

我找不到有关如何使用户使用signInWithEmailAndPassword()方法使用Firebase身份验证保持登录状态的文档或内容!

我打算使用本地存储,但是我发现Firebase提供了一个更好的选择,而不是将用户数据存储在本地存储中,但是我不知道该怎么做!

我发现具体是这样的:

firebase.auth().onAuthStateChanged(); 

但是我不知道如何通过我的服务和我的Guard来实现它!

这是我的身份验证服务代码:

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 {

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

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

    this.user = afAuth.authState;


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


  }

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

      // const credentials = this.afAuth.auth.email
      return await this.afAuth.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 this.afAuth.auth.createUserWithEmailAndPassword(username, password).then(
        user => {
          this.navCtrl.navigateForward('/profile');
          this.statusMessage.message(`Welcome ${user.user.email}`);
        }
      );
    } catch (error) {
      console.dir(error);
    }
  }

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


}

这也是我的保护代码:

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';

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

  constructor(
    private auth: AuthService,
    private navCtrl: NavController
  ) { }

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

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

    this.navCtrl.navigateBack('/login');
    return false;


  }
}

0 个答案:

没有答案