Where to place code to set Firebase auth state persistence in Vue.js?

杀马特。学长 韩版系。学妹 提交于 2020-11-28 10:11:56

问题


Overview

I'm building a web app in Quasar/Vue.js and Firebase which needs to authenticate users.

What I'm trying to achieve

A pretty common feature - keep users logged even after they close the browser/tab.

Possible Solutions

I'm aware that I can use localStorage or cookies to set the user auth state. However, I want to allow Firebase auth do it for me (if it can do it).

I checked the docs in this regard - https://firebase.google.com/docs/auth/web/auth-state-persistence and they're nice, except I cannot figure out where to place this piece of code mentioned there:

firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL)
  .then(function() {
    // New sign-in will be persisted with session persistence.
    return firebase.auth().signInWithEmailAndPassword(email, password);
  })
  .catch(function(error) {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
  });

I'm not sure where to place it out of the following places:

  • with the onAuthStatechanged listener?
  • in the App.vue (root Vue) instance?
  • somewhere else?

Would be glad if anyone could help out. Thanks.


回答1:


I'd do it wherever you have firebase.initializeApp(). Eg

firebase.initializeApp({
  // config goes here
});

export const auth = firebase.auth()

auth.setPersistence(firebase.auth.Auth.Persistence.LOCAL)

Note that LOCAL is the default in web apps already.

You don't really need to wait for that promise. From the docs

This will return a promise that will resolve once the state finishes copying from one type of storage to the other. Calling a sign-in method after changing persistence will wait for that persistence change to complete before applying it on the new Auth state.



来源:https://stackoverflow.com/questions/62078982/where-to-place-code-to-set-firebase-auth-state-persistence-in-vue-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!