我如何在Ionic App中保持Firebase Auth会话

问题描述 投票:0回答:1

我一直在搜索有关此的信息,但我不知道该怎么做。我需要的是,在我的Ionic应用程序中,用户可以登录并关闭该应用程序,当他再次输入时,登录会话保持不变。像推特,Instagram和这些应用程序的工作方式。我读过将Firebase持久性设置为LOCAL应该足够了,但对我不起作用。我认为这将是一个棘手的问题,因为我认为Firebase可用于持久性会话。

我的app.module.ts

import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy, RouterModule } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AngularFireModule } from '@angular/fire/';
import { environment } from '../environments/environment';
import { routes } from './app-routing.module';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule,
    CommonModule,
    IonicModule.forRoot(),
    AngularFireModule.initializeApp(environment.firebase),
    RouterModule.forRoot(routes),
  ],
  providers: [
    StatusBar,
    SplashScreen,
    AngularFireAuth,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

我的main.page.tslogInService.LogIn返回已登录的用户,在其他情况下为null

import { AngularFireAuth } from '@angular/fire/auth';
import { LoginService } from './../../services/login.service';
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router'
import { User } from "../../clases/data"

import { FormGroup, FormBuilder, Validators } from "@angular/forms";

@Component({
  selector: 'app-login',
  templateUrl: './main.page.html',
  styleUrls: ['./main.page.scss'],
})
export class MainPage implements OnInit {


  protected email: "";
  protected password: "";
  protected errLabel: string = "";
  public user;
  credentialsForm: FormGroup;

  constructor(private routes: Router, private fAuth: AngularFireAuth) {
    let response = fAuth.auth.currentUser;
    if (response != null) {
      this.routes.navigateByUrl("/home");
      console.log(response);
    }
  }

  ngOnInit() {
    if (this.fAuth?.auth?.currentUser != null)
      this.routes.navigateByUrl("/home");
  }

  async onSumbit() {
    let loginService = new LoginService(this.fAuth);
    let user: User = new User(this.email, this.password);
    let response = await loginService.logIn(user);
    console.log("MainPage: ", response)
    if (response != null) {
      this.routes.navigateByUrl("/home")
    }
    else {
      this.errLabel = "The password is not correct.";
    }


  }

}

我的login.service.ts

import { User } from './../clases/data';
import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import * as firebase from "firebase/app";

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

  public isLogged: any = false;

  constructor(public fAuth: AngularFireAuth)
  {
    fAuth.authState.subscribe(user => (this.isLogged = user))
  }

  async logIn(user: User)
  {
    var res = null;
    res = firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION).then(async () =>
    {
      this.fAuth.auth.onAuthStateChanged(user => console.log(user));
        let userReceived = await this.fAuth.auth.signInWithEmailAndPassword(user.email, user.pass).catch(() => {console.log("Error during login"); return (null)})
        return (userReceived);
    }).catch(() => {console.log("Error during setting log in persistence"); return (null)})

    return (res);
  }

  async signUp(user: User)
  {
   return await this.fAuth.auth.createUserWithEmailAndPassword(user.email, user.pass).catch(
      () => {
        console.log("Error during the creation of the new user.")
        return "The email already exists.";
      }).then(
        () => {
          console.log("User created successfully")
          return (this.updateProfile({displayName: user.name}));
        }
      )
  }

  async updateProfile(user)
  {
    return await this.fAuth.auth.currentUser.updateProfile(user).catch((error) => {console.log(error); return ("There was an error creating your user, try it again past a few minutes if it continues ocurring contact with us in [email protected]")}).then(() => null)
  }

}
angular firebase authentication ionic-framework firebase-authentication
1个回答
0
投票

首先,您实际上不应该使用new关键字实例化Service。让注入器完成其工作,然后将LoginService添加到main.page的构造函数中,例如:

constructor(private routes: Router, private fAuth: AngularFireAuth, private loginService: LoginService) {
  let response = fAuth.auth.currentUser;
  if (response != null) {
    this.routes.navigateByUrl("/home");
    console.log(response);
  }
}

通过在Typescript中的构造函数参数前添加私有或公共,它作为类的属性添加,因此您可以在this.loginService的main.page.ts中的任何位置使用它>

现在考虑持久性问题。您没有像自己说的那样使用持久性LOCAL,而是使用持久性SESSION。所以你需要使用firebase.auth.Auth.Persistence.LOCAL代替firebase.auth.Auth.Persistence.SESSION

我也在其中一个项目中将firebase与AngularFire2一起使用,我可以确认firebase.auth.Auth.Persistence.LOCAL将使您的用户保持登录状态

© www.soinside.com 2019 - 2024. All rights reserved.