简体   繁体   中英

Nuxt don't see a authenticated user

I am doing user authentication, but I ran into a problem. First, when loading, the middleware is loaded, it does not see the authorized user through $fire.auth.onAuthStateChanged. And if you go to another page (without reloading page), user is appear. How to make him see it at the first boot?

Here is my middleware

export default function ({app, route, redirect}) {
  console.log('middleware')
  app.$fire.auth.onAuthStateChanged(user => {
    if (user) {
      console.log('user+')
      if (route.path === perm.signin || route.path === perm.signup) {
        return redirect('/')
      }
    } else {
      console.log('user-')
      if (route.path !== perm.signin || route.path !== perm.signup) {
        return redirect(perm.signin)
      }
    }
  })
}

and what I received (1st pic) when first enter to app in console.log (middleware, user-). But if I go to another page I receive middleware, user+.

在此处输入图像描述

I need user + to be on the first start

onAuthStateChanged fires the callback you provided as argument after the middleware has run. In other words the callback's return statements are not being run when the middleware runs. You could either ensure the middleware is called after the first authentication attempt, but this would slow down the initial startup of the application. So you could expose the nuxt router to the onAuthStateChanged handler and router.push('/login') or router.push('/somewhere') from there.

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