ibrahim farhat
ibrahim farhat

Reputation: 11

check required auth in vue beforeEach method with firebase v9

i want to check if user exist before go to some pages in beforeEach method

i export the user state i use firebase v9

export const userAuthState = ()=>{
  let currentUser = null;
   onAuthStateChanged(auth, (user) => {
  if (user) {
    currentUser = user;
  }
});
return currentUser;
}

here where i use it

 import {userAuthState} from 'src/backend/firebase-config';
...

console.log("before route");
Router.beforeEach(async (to,from,next)=>{
    if(await !userAuthState() && to.meta.requiresAuth){
      next({path: 'login', query:{ redirect: to.fullPath }})
    }else if(await userAuthState() && to.meta.requiresAuth == 'login'){
      next({path:'/'})
    }else{
      next()
    }
  })

here the problem cant navigate to any page and print the console.log many times

how i can check the user before route in correct way thank you.

Upvotes: 0

Views: 1387

Answers (1)

Lucas David Ferrero
Lucas David Ferrero

Reputation: 1902

I'll give you a simple example of how can you make some decision based on user authentication.

For this, I'll use Vuex as a central store since you'll commonly use user information across all your app. I'll assume that you're building an SPA with Vue and Firebase V9.

This is a simple store for users. Register this store with Vue (with .use()) in your main.js file (your entry point file).

import { createStore } from 'vuex'
const Store = createStore({
  state() {
    return {
      user: {
       uid: '',
       email: ''
      }
    }
  },
  mutations: {
   setUser (state, payload) {
     if (payload) {
       state.user.uid = payload.uid
       state.user.email = payload.email
       return
     }
     state.user.uid = ''
     state.user.email = ''
   }
  }
})
export Store

Now, at your App.vue (or your root component) you simple call onAuthStateChanged and run commits depending on User's state:

<template>
  <div>Your wonderful template...</div>
</template>
<script>
import { onAuthStateChanged } from "firebase/auth";
import { yourAuthService } from 'yourFirebaseInit'
export default {
  name: 'App',
  created () {
    onAuthStateChanged(yourAuthService, (user) => {
       if (user) {
         this.$store.commit('setUser', { uid: user.uid, email: user.email })
       } else {
         this.$store.commit('setUser', null)
       }
    })
  }
}
</script>

Finally, in your routes, you could do something like:

// we import the Store that we've created above.
import { Store } from 'your-store-path'
Router.beforeEach((to,from,next)=>{
    if(to.meta.requiresAuth && Store.state.user.uid === ''){
      next({path: 'login', query:{ redirect: to.fullPath }})
    } else{
      next()
    }
  })

This is a simple example of how can you implement an Authentication flow with Vue and Firebase V9.

Upvotes: 1

Related Questions