【问题标题】:How I keep the session of Firebase Auth in my Ionic App我如何在我的 Ionic App 中保持 Firebase Auth 会话
【发布时间】:2020-07-29 12:43:22
【问题描述】:

我一直在搜索这方面的信息,但我不知道我必须做什么。我需要的是,在我的 Ionic 应用程序中,用户可以登录并关闭应用程序,当他再次进入时,登录会话保持不变。就像 twitter、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.ts logInService.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 it_problems@halamaui.com")}).then(() => null)
  }

}

【问题讨论】:

  • 您可以发布您的 LoginService 的代码吗?这将是关键部分
  • 文件在那里。
  • 如果您使用 auth.currentUser 来确定是否应将用户重定向到登录页面,我建议您使用 AngularFire 身份验证保护,因为 auth.currentUser 并不总是立即可用,这可能会使您的用户似乎没有登录 github.com/angular/angularfire/blob/master/docs/auth/…

标签: angular firebase authentication ionic-framework firebase-authentication


【解决方案1】:

首先,您真的不应该使用 new 关键字来实例化服务。让注入器完成它的工作,只需将 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 中的构造函数参数前添加 private 或 public,它将作为属性添加到类中,因此您可以在 main.page.ts 中的任何位置使用this.loginService

现在解决持久性问题。您没有使用持久性 LOCAL,因为您自己说您正在使用持久性会话。所以你需要使用 firebase.auth.Auth.Persistence.LOCAL 而不是 firebase.auth.Auth.Persistence.SESSION

我在我的一个项目中使用带有 AngularFire2 的 firebase,我可以确认 firebase.auth.Auth.Persistence.LOCAL 将使您的用户保持登录

【讨论】:

  • 我读错了 Firebase 文档,我开始使用该服务作为注入。谢谢你的建议。
  • 它应该默认使用 Persistence.LOCAL,这样你的部分代码就不是完全必要的了。我们有几个使用 AngularFire 的项目,用户始终坚持使用而无需指定此
猜你喜欢
  • 2013-10-05
  • 2016-12-07
  • 2020-03-19
  • 1970-01-01
  • 1970-01-01
  • 2017-10-20
  • 2011-02-08
  • 2015-03-06
  • 2010-10-29
相关资源
最近更新 更多