代码之家  ›  专栏  ›  技术社区  ›  Igor Komar

Vuejs ssr check用户已针对每个请求进行身份验证

  •  2
  • Igor Komar  · 技术社区  · 8 年前

    我在我的应用程序中使用这个ssr模板, https://github.com/vuejs/vue-hackernews-2.0

    我不知道如何实现逻辑来检查每个用户页面请求的用户是否经过身份验证,Im使用cookie存储用户的 token

    我发现路由器可以在渲染组件之前处理请求:

      router.beforeEach((to, from, next) => {
        if (to.matched.some(record => record.meta.requiresAuth)) {
          // this route requires auth, check if logged in
          // if not, redirect to login page.
          // isLoggedIn()
          //   .then(response => response.json())
          //   .then(json => {
          //     console.log(json[0])
          //     next()
          //   })
          //   .catch(error => {
          //     console.log(error)
          //     next()
          //   })
    
          const x = true
    
          if (!x) {
            next({
              path: '/signin',
              query: { redirect: to.fullPath }
            })
          } else {
            next()
          }
        } else {
          next() // make sure to always call next()!
        }
      })
    
      return router
    }
    

    但问题是,路由器开始在客户端和服务器端使用此代码,这在我的情况下有点不正确。

    如何发送请求 is user authenticated 只有一次,还是在客户端或服务器端?

    1 回复  |  直到 8 年前
        1
  •  4
  •   Igor Komar    8 年前

    回答我的问题,下一种方法-是我搜索的,这个vue路由器中间件将在发送其他请求之前检查用户(在我的组件方法中,如 asyncData ),然后将用户信息放入存储:

    // 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))
      }
    }