1

I use vue js 2.4.2 , vue router 2.7.0 , and firebase 4.3.0. I can't get the route authentication stuff to work. This is my current route.js

import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)

import Firebase from './firebase'

import Dashboard from './components/Dashboard.vue'
import Auth from './components/Auth.vue'


let router = new Router({
    mode: 'history',
    routes: [
        {
            path: '/',
            component: Dashboard,
            meta: {
                auth: true
            }
        },
        {
            path: '/login',
            component: Auth
        }
    ]
})

router.beforeEach((to, from, next) => {
    if (to.matched.some(record => record.meta.auth)) {
        if (!Firebase.auth().currentUser) {
            next({
                path: '/login'
            })
        } else {
            next()
        }
    } else {
        next()
    }
})

export default router

But now everytime I go to / it redirects me back to /login, probably because the Firebase.auth().currentUser is null, even though I am in fact logged in. How do I fix this?

1
  • You Config Initialize Firebase ? Commented Aug 27, 2017 at 4:02

1 Answer 1

3

try using Firebase.auth().onAuthStateChanged instead of Firebase.auth().currentUser; it is the recommended way to get the current user.

Getting the user by currentUser may cause a problem similar to what you are seeing. This is from the official doc of firebase.

Note: currentUser might also be null because the auth object has not finished initializing. If you use an observer to keep track of the user's sign-in status, you don't need to handle this case.

Try to set you authentication logic like this:

router.beforeEach((to, from, next) => {
    if (to.matched.some(record => record.meta.auth)) {
        Firebase.auth().onAuthStateChanged(function(user) {
            if (!user) {
                next({
                    path: '/login'
                })
            } else {
                next()
            }
        }
    } else {
        next()
    }
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.