Firebase Auth和Vue路由器

时间:2017-04-27 03:38:26

标签: firebase vue.js firebase-authentication

我尝试使用firebase验证Vue.js应用。

我遇到一个问题,如果在登录时尝试直接访问受登录保护的URL,路由器将在firebase.js有时间返回auth响应之前加载并检查auth状态。这导致用户被退回到登录页面(当他们已经登录时)。

如何从firebase检索auth状态之前,如何延迟vue-router导航?我可以看到firebase将auth数据存储在localStorage中,是否可以安全地检查它是否作为初步身份验证检查存在?理想情况下,最终结果是在用户通过身份验证时显示加载微调器或其他内容,然后他们应该能够访问他们导航到的页面。

router / index.js

let router = new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home
    },
    {
      path: '/login',
      name: 'Login',
      component: Login
    },
    {
      path: '/example',
      name: 'Example',
      component: Example,
      beforeEnter: loginRequired
    }
})

function loginRequired (to, from, next) {
  if (authService.authenticated()) {
    next()
  } else {
    next('/login')
  }
}

auth.js

import * as firebase from 'firebase'

var config = {
    // firebase config
}

firebase.initializeApp(config)

var authService = {

  firebase: firebase,
  user: null,

  authenticated () {
    if (this.user == null) {
      return false
    } else {
      return !this.user.isAnonymous
    }
  },

  setUser (user) {
    this.user = user
  },

  login (email, password) {
    return this.firebase.auth().signInWithEmailAndPassword(email, password)
      .then(user => {
        this.setUser(user)
      })
  },

  logout () {
    this.firebase.auth().signOut().then(() => {
      console.log('logout done')
    })
  }
}

firebase.auth().onAuthStateChanged(user => {
  authService.setUser(user)
})

export default authService

app.vue

<template>
  <div id="app">
    <p v-if="auth.user !== null">Logged in with {{ auth.user.email }}</p>
    <p v-else>not logged in</p>
    <router-view v-if="auth.user !== null"></router-view>
  </div>
</template>

<script>
import authService from './auth'

export default {
  name: 'app',
  data () {
    return {
      auth: authService
    }
  }
}
</script>

5 个答案:

答案 0 :(得分:5)

Firebase始终在启动时触发身份验证状态更改事件,但不会立即触发。

您需要让authService.authenticated返回一个承诺,以便等待Firebase完成其用户/身份验证初始化。

const initializeAuth = new Promise(resolve => {
  // this adds a hook for the initial auth-change event
  firebase.auth().onAuthStateChanged(user => {
    authService.setUser(user)
    resolve(user)
  })
})

const authService = {

  user: null,

  authenticated () {
    return initializeAuth.then(user => {
      return user && !user.isAnonymous
    })
  },

  setUser (user) {
    this.user = user
  },

  login (email, password) {
    return firebase.auth().signInWithEmailAndPassword(email, password)
  },

  logout () {
    firebase.auth().signOut().then(() => {
      console.log('logout done')
    })
  }
}

您不需要从setUser承诺致电signInWith...,因为这已经由initializeAuth承诺处理。

答案 1 :(得分:3)

我遇到了同样的问题,最终推迟了Vue对象的创建,直到第一个onAuthStatedChanged。

# main.js
// wait for first firebase auth change before setting up vue
import { AUTH_SUCCESS, AUTH_LOGOUT } from "@/store/actions/auth";
import { utils } from "@/store/modules/auth";
let app;
firebase.auth().onAuthStateChanged(async user => {
  if (!app) {
    if (user) {
      await store.dispatch(AUTH_SUCCESS, utils.mapUser(user));
    } else {
      await store.dispatch(AUTH_LOGOUT);
    }
    app = new Vue({
      router,
      store,
      i18n,
      render: h => h(App)
    }).$mount("#app");
  }
});

然后在我的路线中我检查正常,如果他们最终登录路线我只是将它们推到我的概述页面,这是我的仪表板页面。

#router.js
router.beforeEach((to, from, next) => {
  let authenticated = store.getters.isAuthenticated;
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // this route requires auth, check if logged in
    // if not, redirect to login page.
    if (!authenticated) {
      next({
        name: "Login",
        query: { redirect: to.fullPath }
      });
    } else {
      next();
    }
  } else {
    // doesn't require auth, but if authenticated already and hitting login then go to overview
    if (authenticated && to.name === "Login") {
      next({
        name: "Overview"
      });
    }
    next(); // make sure to always call next()!
  }
});

答案 2 :(得分:1)

针对使用常规Vue(而非Vuex)的用户,以Richard's答案为基础

main.js

//initialize firebase
firebase.initializeApp(config);
let app: any;
firebase.auth().onAuthStateChanged(async user => {
if (!app) {
    //wait to get user
    var user = await firebase.auth().currentUser;

    //start app
    app = new Vue({
      router,
      created() {
        //redirect if user not logged in
        if (!user) {
          this.$router.push("/login");
        }
      },
      render: h => h(App)
    }).$mount("#app");
  }
});

router.js

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

  if (requiresAuth && !currentUser) {
    const loginpath = window.location.pathname;   
    next({ name: 'login', query: { from: loginpath } });
  } else if (!requiresAuth && currentUser) {
    next("defaultView");
  } else {
    next();
  }
});

答案 3 :(得分:1)

您有两个选择:

1)从组件使用 beforeRouteEnter

export default {
        name: "example",
        ....
        beforeRouteEnter(to, from, next){
            if (authService.authenticated()) {
                next()
            } else {
                next('/login')
            }
        },
}

2)使用路由器中的 beforeResolve

router.beforeResolve((to, from, next) => {

    if(to.fullPath === '/example' && !authService.authenticated()){
        next('/login')
    }else{
        next()
    }
})

Life-circle of Vue route guards

答案 4 :(得分:0)

要延迟身份验证状态,您需要做的只是

  • a)在安装应用程序之前,请使用firebase auth onAuthStateChanged方法。
  • b)在路由器文件中,向您要添加登录保护的父路由添加一个元数据
  • c)使用router.beforeEach进行身份验证以及如何将用户重定向到。我将在以下每种情况下提供示例: 阶段a)
    firebase.auth().onAuthStateChanged(function(user) {
        console.log(user)
        new Vue({
            router,
            render: h => h(App),
          }).$mount('#app')
        }
    });

阶段b)

    ....
    ....
    ....
    {
        path: "/dashboard",
        name: "dashboard",
        component: Dashboard,
        meta: { requiresAuth: true },//Add this
        children: [
            {
                path: "products",
                name: "products",
                component: Products,
            },
        ],
    ....
    ....
    ....

阶段c)

    router.beforeEach((to, from, next) => {
        const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
        const currentUser = firebase.auth().currentUser
        if(requiresAuth && !currentUser) {
            next("/")
        } else if(requiresAuth && currentUser) {
            next()
        }else{
            next()
        }
    })

我相信您可以采用这种方式。