简体   繁体   中英

use firebase auth with vue 3 route guard

I have the needings to use firebase auth with vue router.

I have this simple guard, but I've noticed that sometimes the users will see for a while the pages also if they are not logged.

router.beforeEach( async (to, from) => {
    onAuthStateChanged( getAuth(app), (user) => {
        console.log(user, to.meta.requireAuth)
        if( to.meta.requireAuth && !user ) {
            return {
                 name: 'Signin'
            }
        }
    })
})

I also have this kind of control inside my components, but I'm looking for something global to use to prevent unregistered users to see the app.

Any suggestion?

You can wrap the onAuthStateChanged in a Promise and make your before each an async function.

// in some global file
export async function getCurrentUser(): Promise<User | null> {
  return new Promise((resolve, reject) => {
    const unsubscribe = auth.onAuthStateChanged((user) => {
      unsubscribe();
      resolve(user);
    }, reject);
  });
}
// your router file
router.beforeEach(async (to, from, next) => {
  if (to.matched.some((record) => record.meta.publicAccess)) {
    next();
  } else {
    const currentUser = await getCurrentUser();
    if (currentUser) {
      next();
    } else {
      next({ name: "Login" });
    }
  }
});
// Your route object
{
      name: "Login",
      path: "/login",
      component: () => import("@/views/authentication/Login.vue"),
}

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