Vuejs ssr check user is authenticated for each request

前端 未结 1 1449
情歌与酒
情歌与酒 2021-01-22 16:11

I’m using this ssr boilerplate for my app, https://github.com/vuejs/vue-hackernews-2.0

I don’t know how to implement logic for checking is user authenticated for each us

相关标签:
1条回答
  • 2021-01-22 16:56

    Answering on my issue, next approach - is what I searched, this vue router middleware will check user, before sending other requests(in my components methods like asyncData), then put user's info into store:

    // router/index.js

    export function createRouter (cookies) {
      const router = new Router({ ... })
    
      router.beforeEach((to, from, next) => {
        // this route requires auth, check if logged in
        // if not, redirect to login page.
        if (to.matched.some(record => record.meta.requiresAuth)) {
          if (router.app.$store) {
            router.app.$store
              .dispatch('FETCH_CURRENT_USER', cookies)
              .then(next)
              .catch(() => next('/signin'))
          } else {
            next()
          }
        } else {
          next()
        }
    
        return router
    }
    

    // store/actions.js

    export default {
      FETCH_CURRENT_USER: ({ commit }, cookie) => {
        const values = {
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json',
            Origin: FRONTEND_HOST,
            Cookie: cookie
          }
        }
    
        return fetch(`${API_HOST}/api/v1/users/me`, values)
          .then(handleStatus)
          .then(handleJSON)
          .then(json => commit('SET_CURRENT_USER', json))
      }
    }
    
    0 讨论(0)
提交回复
热议问题