I'm implementing for the first time Firebase in my Quasar App (with Vue 3). I've created the boot file firebase.js and this is its content:
import { boot } from 'quasar/wrappers'
import { initializeApp } from 'firebase/app';
import { getAnalytics } from "firebase/analytics";
// "async" is optional;
// more info on params: https://v2.quasar.dev/quasar-cli/boot-files
const firebaseConfig = {
apiKey: 'XXX',
authDomain: 'XXX',
projectId: 'XXX',
storageBucket: 'XXX',
messagingSenderId: 'XXX',
appId: 'XXX',
measurementId: 'XXX'
};
const firebaseApp = initializeApp(firebaseConfig);
const analyticsApp = getAnalytics(firebaseApp);
firebaseApp.getCurrentUser = () => {
return new Promise((resolve, reject) => {
const unsubscribe = firebaseApp.auth().onAuthStateChanged(user => {
unsubscribe();
resolve(user);
}, reject);
})
};
export default boot(({ app }) => {
app.config.globalProperties.$firebase = firebaseApp;
app.config.globalProperties.$analytics = analyticsApp;
})
The initialization seems to work fine. Now I must add a function to my index.ts located into router dirctory which allow me to redirect to a specific page when the user is not authenticated.
Router.beforeEach(async (to, from, next) => {
const auth = to.meta.requiresAuth
if (auth && !await $firebase.getCurrentUser()) {
next('/');
} else {
next();
}
})
$firebase must reference the globalproperties item. But whatever I've changed I'm unable to access the property.
Can you help me?
Roberto
Looking carefully into Quasar documentation I've made all the changes in the firebase.js file which now is like this.
/* eslint-disable */
import { boot } from 'quasar/wrappers'
import { initializeApp } from 'firebase/app';
import { getAnalytics } from "firebase/analytics";
const firebaseConfig = {
apiKey: 'XXX',
authDomain: 'XXX',
projectId: 'XXX',
storageBucket: 'XXX',
messagingSenderId: 'XXX',
appId: 'XXX',
measurementId: 'XXX'
};
const firebase = initializeApp(firebaseConfig);
const analytics = getAnalytics(firebase);
firebase.getCurrentUser = () => {
return new Promise((resolve, reject) => {
const unsubscribe = firebase.auth().onAuthStateChanged(user => {
unsubscribe();
resolve(user);
}, reject);
})
};
export default boot(({ app, router, store }) => {
app.config.globalProperties.$firebase = firebase;
app.config.globalProperties.$analytics = analytics;
router.beforeEach(async (to, from, next) => {
const auth = to.meta.requiresAuth
if (auth && !await firebase.getCurrentUser()) {
next('/');
} else {
next();
}
})
})
export { firebase, analytics };
Essentially I've changed the export boot clause adding router and store in it and I've added router.beforeEach in the clause.
I've made a debug session and the function is called everytime a route change occurs.
Roberto