A client-side project is being developed using firebase and vue. After a successful login by the user, the authService object gets updated in the Login component, but not in the router. The authService is utilized in both the Login component and AdminNavbar component. In my understanding, the onAuthStateChanged method should update the user variable at each login and logout event. While this functionality works in the Login component, it does not work in the router, causing the app to always redirect to the login page.
Below is the shared code for firebase and authService:
import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/database';
const firebaseConfig = {
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
const initializeAuth = new Promise(resolve => {
firebase.auth().onAuthStateChanged(user => {
authService.setUser(user);
resolve(user);
console.log(user);
})
})
const authService = {
user: null,
authenticated () {
return initializeAuth.then(user => {
return user && !user.isAnonymous
})
},
setUser (user) {
this.user = user
},
login (email, password) {
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION).then(function() {
firebase.auth().signInWithEmailAndPassword(email, password)
}).catch(function(error) {
console.log(error);
});
},
logout () {
firebase.auth().signOut().then(() => {
console.log('logout done')
})
}
}
export const db = firebaseApp.database();
export const hadithRef = db.ref('hadith');
export default authService;
Below is the shared code for the router:
import Vue from "vue";
import VueRouter from 'vue-router';
Vue.use(VueRouter);
// import components
import authService from './firebase.js';
const router = new VueRouter({
mode: 'history',
routes: [
// path, name, and component information are included here
]
});
router.beforeEach((to, from, next) => {
// The user variable is still null even after the user logs in, but it is not null in the Login component.
console.log(authService.user);
if (to.path == '/hadith/query' && authService.user == null) next({ path: '/login' })
else if (to.path == '/hadith/add' && authService.user == null) next({ path: '/login' })
else if (to.path == '/hadith/update' && authService.user == null) next({ path: '/login' })
else next()
});
export default router;
main.js code is shared below:
import Vue from 'vue'
import '@babel/polyfill'
import 'mutationobserver-shim'
import './plugins/bootstrap-vue';
import './plugins/vuefire';
Vue.config.productionTip = false;
import App from './App.vue';
import router from './plugins/hrouter';
new Vue({
render: h => h(App),
router
}).$mount('#app')