User redirect and authentication with middleware o

2019-08-27 18:18发布

I'm trying to redirect a user to a login page if the user is not logged in when he tries to access certain pages with the following code.

// middlware/authenticated.js
import firebase from 'firebase'

export default function ({ store, redirect }) {
  let user = firebase.auth().currentUser   
  store.state.user = user //this doesn't work
  if (!user) {
    console.log('redirect')
    return redirect('/login')   
  }
}

However, the problem is with this code when I refresh a page I'm redirected to login page although without using the middleware, I can stay in the same page with logged in. For some reasons, which I don't know why, firebase can't work in middleware.

How should I modify this middleware or implement this function?

Thanks.

//middleware/authenticated.js
export default function ({
  store,
  redirect
}) {
  if (!store.getters['index/isAuthenticated']) {
    return redirect('/login')
  }
}
//post.vue
  async mounted () {
    if (process.browser) {
      let user;
      if (!this.user) user = await auth(); // this auth is a plugin
      await Promise.all([
        this.user ? Promise.resolve() : this.$store.dispatch("setUser", { user: user || null })
      ]);
      this.isLoaded = true;
    }
  },
//plugins/auth.js
import firebase from '~/plugins/firebase'

function auth () {
  return new Promise((resolve, reject) => {
    firebase.auth().onAuthStateChanged((user) => {
      resolve(user || false)
    })
  })
}
export default auth

1条回答
可以哭但决不认输i
2楼-- · 2019-08-27 18:22

By default Firebase persists the users logged in status on successful authentication. This example uses the session, to store the user uid and cookies to store the users token and used in situations where the sessions has ended (example when browser is closed) and then a new session started but where the user is still authenticated according to Firebase. In cases like these the user will not need to sign in to view protected resources.

Your basic Middleware to protect it should look like this (if you have a Store Module called User)

export default function ({ store, redirect }) {
  if (!store.getters['modules/user/isAuthenticated']) {
    return redirect('/auth/signin')
  }
}

In your main Store you use the ServerInit Function to get the User if there is one saved in the Cookies and load it into your User Store Module which will be used for verification in the Middleware.

Your User Store Module should look like this, and keep in mind that you remove the Cookie when you Log the User out so that he is fully logged out.

I used the things i mentioned above as the beginning of my Authentication and modified it a bit, which you can also do. Most of the credit goes to davidroyer who has set up this nice Github Repo which includes all needed files as a good example on how to accomplish your goal.

查看更多
登录 后发表回答