firebase onAuthStateChanged&的模式导航卫士-类星体应用 [英] Pattern for firebase onAuthStateChanged & Navigation Guards - Quasar app

查看:95
本文介绍了firebase onAuthStateChanged&的模式导航卫士-类星体应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Quasar应用程序中遇到有关浏览器刷新和Firebase身份验证的问题.

I am facing an issue in my Quasar app with regards to browser refresh and firebase authentication.

用户登录并单击浏览器刷新后,firebase.auth().currentUser返回null(因为它异步执行).这意味着当执行beforeEach时,currentUser为null,并通过登录页面提示用户.但是我看到,当调用onAuthStateChanged的回调时,将正确设置用户.

After a user logs in and then clicks on the browser refresh, then the firebase.auth().currentUser returns null (as this executes asynchronously). This means that when the beforeEach gets executed the currentUser is null and the user is prompted with the logon page. However I see that when the callback to onAuthStateChanged is getting invoked the user is getting set correctly.

在Quasar应用程序中,是否存在可以在导航过程中使用onAuthStateChanged的模式,以便重用现有的用户会话?

Is there any pattern by which, in a Quasar app, the onAuthStateChanged can be used in navigation process so that existing user session is reused?

//Vue-router => index.js

// Vue-router => index.js

firebase.auth().onAuthStateChanged(user => {
  console.log('onAuthStateChanged Invoked => ' + user);
});

router.beforeEach((to, from, next) => {
  let currentUser = firebase.auth().currentUser; 
  let requiresAuth = to.matched.some(record => record.meta.requiresAuth);

  if (requiresAuth && !currentUser) {
    next('signin');
  } else {
    if (requiresAuth && currentUser.emailVerified === false) {
      next('signin');
    } else {
      next();
    }
  }
});

推荐答案

在您的main.js中,您应该收听onAuthStateChange.

In your main.js, you should listen for onAuthStateChange.

import Vue from 'vue'
import App from './App'
import router from './router'
import firebase from 'firebase'

Vue.config.productionTip = false

let app;
let config = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
  databaseURL: "https://YOUR_PROJECT_ID.firebaseio.com",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_PROJECT_ID.appspot.com",
  messagingSenderId: "YOUR_MESSAGING_SEND_ID"
};

firebase.initializeApp(config)
firebase.auth().onAuthStateChanged(function(user) {
  if (!app) {
    /* eslint-disable no-new */
    app = new Vue({
      el: '#app',
      template: '<App/>',
      components: { App },
      router
    })
  }
});

我们仅在确定可以使用Firebase Auth对象时才初始化应用程序.

We only initialize the app only when we are sure Firebase Auth object is ready to use.

这篇关于firebase onAuthStateChanged&amp;的模式导航卫士-类星体应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆