简体   繁体   中英

Nuxt Firebase Authentication Middleware

I'm using Nuxt(vue) as frontend and Firestore and Authentication as Backend. I got the authentication to work to a certain amount, but my problem is refreshing the browser resets the state so my Middleware returns a false result.

Here some code snippets:

Middleware:

export default function ({store, redirect, route}) {

    const userIsLoggedIn = !!store.state.currentUser; 

    if(!userIsLoggedIn) {
        return redirect ('/')
    } 
}

Plugin:

import { auth } from '@/services/firebaseInit.js'

export default (context) => {
    const { store } = context

    return new Promise((resolve, reject) => {
        auth.onAuthStateChanged(user => {
            store.commit('setCurrentUser', user)
            resolve()
        })
    })
}

Now this works in running App but when someone refreshes a page where you need auth it doesnt work and redirect to /, now i dont know how to solve that, would appreciate help and if you need more code then i provide it.

EDIT 1:

   async nuxtServerInit ({ commit }, { req }) {
            let user = await firebase.auth().currentUser

            commit('setCurrentUser', user)
        }

You need to init your user in nuxtServerInit method, otherwise your middleware will be executed on server with empty user and hence redirect will happen.

You need to grab user data from req object. See this repo for reference implementation https://github.com/davidroyer/nuxt-ssr-firebase-auth.v2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM