簡體   English   中英

Firebase:如何持久化 auth state?

[英]Firebase: How to persist auth state?

我在沒有 React 的情況下使用 firebase web sdk。 我的申請中有 4 頁。 我正在為每個頁面使用 express js 來發送該路由的 html 文件。

我有一個名為common.js的文件,我在其中定義了將由所有頁面共享的方法。 在同一個文件中,我定義了一個方法來對 auth changed 進行操作,如下所示:

修改以下代碼

import { initializeApp } from 'firebase/app';
import { getAuth, onAuthStateChanged } from 'firebase/auth';
import { getFirestore } from 'firebase/firestore';
import { firebaseConfig } from './firebase.config';

const firebaseApp = initializeApp(firebaseConfig);
const db = getFirestore(firebaseApp);
const auth = getAuth(firebaseApp);

const addNavbar = () => {
   $('#nav').load('nav.html', () => {
      document.getElementById('btnSignOut').addEventListener('click', (e) => {
         auth.signOut();
      });
   });
}

// createAlert, createEditDeleteButtons, displayLoaderAndHideApp defined here

const unsubscribeOnAuthStateChanged = onAuthStateChanged(auth, async (user) => {
   if (user) {
      window.location.replace('/home');
   } else {
      window.location.replace('/login');
   }
});

export {
   addNavbar, auth, createAlert, createEditDeleteButtons, db, displayLoaderAndHideApp,
};

在每個頁面上,我首先調用handleOnAuthStateChanged() ,並且在成功登錄后也會調用它。 我想保留身份驗證,所以遇到了setPersistence() ,所以我在login.js中使用了它,如下所示:

import { browserLocalPersistence, browserSessionPersistence, setPersistence, signInWithEmailAndPassword } from 'firebase/auth';
import { auth, handleOnAuthStateChanged } from './common';

document.getElementById('btnSignin').addEventListener('click', async (e) => {
   e.preventDefault();
   try {
      const form = document.querySelector('form.formLogin');
      const email = form.email.value.trim();
      const password = form.password.value;
      await setPersistence(auth, browserLocalPersistence);
      await signInWithEmailAndPassword(auth, email, password);
      handleOnAuthStateChanged(auth.currentUser); // here auth will retrieve the new logged in user
   } catch (e) {
      console.error(e);
   }
});

如果我在其他頁面上使用onAuthStateChanged()我的用戶是 null 那么我就會陷入循環。

我錯過了什么嗎?

更新

所有最小代碼都是在刪除所有功能之后,除了一些可能導致問題的功能。

我有一個名為nav.html的文件,它由common.js加載到頁面中,並且定義如上。

主頁、第 1 頁和第 2 頁的代碼通過調用addNav添加導航。 Home 將從common.js 、頁面 2 的 js 和頁面 1 的 js 導入方法。 首頁的js如下:

import { addDoc, collection, deleteDoc, doc, getDocs, onSnapshot, query, setDoc, where } from 'firebase/firestore';
import { addNavbar, createAlert, createEditDeleteButtons, db, displayLoaderAndHideApp as displayLoader } from './common';
// imports from page 1 and page 2

addNavbar();

// Other methods are defined here...

// Nothing is exported as of now..

Firebase 在大多數瀏覽器環境中自動保留身份驗證 state ,並在應用程序/頁面重新加載時恢復它。 要檢測 auth state(以及其他 auth state 更改)的恢復,您需要使用 SDK 注冊一個 auth state 偵聽器,如獲取當前用戶文檔中的第一個代碼片段所示:

import { getAuth, onAuthStateChanged } from "firebase/auth";

const auth = getAuth();
onAuthStateChanged(auth, (user) => {
  if (user) {
    // User is signed in, see docs for a list of available properties
    // https://firebase.google.com/docs/reference/js/firebase.User
    const uid = user.uid;
    // ...
  } else {
    // User is signed out
    // ...
  }
});

您的handleOnAuthStateChanged的大部分代碼可能 go 到此處理程序中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM