简体   繁体   English

Nuxt auth对自定义请求更新auth

[英]Nuxt auth update auth on custom requests

From nuxt auth website I saw this: 从nuxt auth网站,我看到了以下内容:

setUserToken(token)
Returns: Promise
Set the auth token and fetch the user using the new token and current strategy.

TIP: This function can properly set the user after registration

this.$auth.setUserToken(token)
  .then(() => this.$toast.success('User set!'))

Tried to use it and it said method is undefined, looked up in the source files and none of methods are like this one. 试图使用它,它表示方法是未定义的,已在源文件中查找,并且没有一种方法与此类似。

I am not very good with this but, how would I set user and token with nuxt/auth module after registration or anything but login/loginWith? 我对此不太满意,但是注册后如何使用nuxt / auth模块或除login / loginWith之外的任何方式设置用户和令牌?

If there is no option for that why is it there on documentation? 如果没有选择,为什么在文档中有?

I would also need to know if I need to create custom auth do I need to use both cookies and localstorage or just one of them? 我还需要知道是否需要创建自定义身份验证,我需要同时使用cookieslocalstorage还是仅使用其中之一? It says that cookies are used for server side and storage for client side. 它说cookie用于服务器端,存储用于客户端。 Can I use just cookies and on nuxtServerInit get cookie for token and set token and user data fetched by api within vuex store? 我可以仅使用cookie并在nuxtServerInit获取cookie的令牌,并设置在vuex存储中api获取的令牌和用户数据吗? Then use it from there if it is needed? 然后从那里使用它(如果需要)?

Nuxt/auth module hurt my brain so long and today I created custom module: Nuxt / auth模块很久以来一直困扰着我的大脑,今天我创建了自定义模块:

First I have this store structure: 首先,我有这个商店结构:

store/
-- index.js
-- mutations.js
-- actions.js
-- state.js
-- getters.js
middleware/
-- redirectIfAuth.js
-- redirectIfNotAuth.js
layouts/
default.vue -> has redirectIfNotAuth.js
guest.vue -> has redirectIfAuth.js
pages/
-- login/
---- index.vue -> uses guest.vue as layout
-- dashboard/
----- index.vue -> uses default.vue as layout without declaration

Inside Index.js I have: Index.js里面,我有:

import state from './state'
import * as actions from './actions'
import * as mutations from './mutations'
import * as getters from './getters'

export default {
  state,
  getters,
  mutations,
  actions,
  modules: {}
}

Inside State.js I have: State.js内部,我有:

export default () => ({
  user: null,
  token: null,
  headers: null
})

Inside Actions.js I have: Actions.js内部,我有:

const cookieparser = process.server ? require('cookieparser') : undefined
// importing server based cookie library

export async function nuxtServerInit ({ commit }, { req, res }) {

  // If we have any axios requests we need to add async/await
  // And since this works on server mode, we don't need to check is it server

  let token = null
  if (req.headers.cookie) {
    const parsed = cookieparser.parse(req.headers.cookie)
    try {
      token = parsed.authToken
    } catch (e) {
      console.log(e)
    }
  }
  // If we have token within cookies we get user data from api and we pass Autorization headers with token
  if (token !== null && token !== false) {
    await axios.get('/api/auth/me', {
      headers: {
        'Authorization': token
      }
    }).then((response) => {
      // If  we get user data we set it to store
      commit('setUser', response.data.data)
      commit('setToken', token)
      commit('setHeaders', token)
    }).catch((error) => {
      // If we get error, we should logout user by removing data within cookies and store
      // Additionally you can create specific code error on backend to check if token is expired or invalid
      // and then check for status code and then remove data
      commit('setUser', null)
      commit('setToken', null)
      res.setHeader('Set-Cookie', [`authToken=false; expires=Thu, 01 Jan 1970 00:00:00 GMT`])
      // This is only way I found useful for removing cookies from node server
      console.warn(error)
    })
  }
}

Inside Mutations.js I have: Mutations.js内部,我有:

export const setToken = (state, payload) => state.token = payload

export const setUser = (state, payload) => state.user = payload

export const setHeaders = (state, payload) => {
  state.headers = {
    headers: {
      'Authorization': payload
    }
  }
}

Inside Getters.js I have: Getters.js我有:

export const getUser = (state) => state.user
export const getToken = (state) => state.token
export const getHeaders = (state) => state.headers

Second I created two middlewares and it seems like nuxt middlewares work on both server and client sides, so I needed to require both libraries for server and client side Then I checked which side it is and then try to get token for further investigations If you include and don't check for server and client but use one of them, your templates wont render but show undefined errors for req on client instead and on server it wont show anything. 其次,我创建了两个中间件,并且看起来nuxt中间件在服务器和客户端上都可以工作,因此我需要在服务器和客户端上都需要库,然后我检查了哪一侧,然后尝试获取令牌以进行进一步的调查。不检查服务器和客户端,但使用其中一个,你的模板不会渲染,但显示为未定义的错误req客户端,而不是和服务器,它不会显示任何东西。

Inside redirectIfAuth.js I have: redirectIfAuth.js内部,我有:

const cookieparser = process.server ? require('cookieparser') : undefined
const Cookie = process.client ? require('js-cookie') : undefined
export default function ({ app, redirect, req }) {
  let token = null
  if (process.server) {
    if (req.headers.cookie) {
      const parsed = cookieparser.parse(req.headers.cookie)
      try {
        token = parsed.authToken
      } catch (e) {
        console.log(e)
      }
    }
  } else if (process.client) {
    token = Cookie.get('authToken')
  }
  if (token && token !== false) {
    app.store.commit('setToken', token)
    app.store.commit('setHeaders', token)
    if (app.store.state.user) {
      if (app.store.state.user.roles.includes('customer')) {
        return redirect({
          name: 'customer-slug',
          params: { slug: app.store.state.user.username }
        })
      } else if (app.store.state.user.roles.includes('admin')) {
        return redirect({
          name: 'dashboard'
        })
      } else {
        return redirect({
          name: 'index'
        })
      }
    } else {
      return redirect({
        name: 'index'
      })
    }
  }
}

Inside redirectIfNotAuth.js I have: redirectIfNotAuth.js内部,我有:

const cookieparser = process.server ? require('cookieparser') : undefined
const Cookie = process.client ? require('js-cookie') : undefined
export default function ({ app, redirect, route, req }) {
  let token = null
  if (process.server) {
    if (req.headers.cookie) {
      const parsed = cookieparser.parse(req.headers.cookie)
      try {
        token = parsed.authToken
      } catch (e) {
        console.log(e)
      }
    }
  } else if (process.client) {
    token = Cookie.get('authToken')
  }
  if (token === null || token === false) {
    return redirect({
      name: 'login',
      query: {
        redirect: route.fullPath
      }
    })
  }
}

Now we use these middlewares within pages or layouts as: 现在,我们在页面或布局中使用以下中间件:

export default {
  middleware: ['redirectIfAuth']
}

Or 要么

export default {
  middleware: ['redirectIfNotAuth']
}

Login: 登录:

async login () {
      if (this.form.email !== '' && this.form.password !== '') {
        await this.$axios.post('/api/auth/login', this.form).then((response) => {
          this.$store.commit('setUser', response.data.data)
          this.$store.commit('setToken', 'Bearer ' + response.data.meta.access_token)
          this.$store.commit('setHeaders', 'Bearer ' + response.data.meta.access_token)
          Cookie.set('authToken', 'Bearer ' + response.data.meta.access_token, { expires: 365 })
          // Cookie.set('authUser', response.data.data, { expires: 365 }) if you need user data within cookies
          if (this.$route.query.redirect) {
            this.$router.push(this.$route.query.redirect)
          }
          this.$router.push('/')
        })
      }
    }

Logout: 登出:

async logout () {
   await this.$axios.post('/api/auth/logout', {}, this.headers)
   // Cookie.remove('authUser') if exists
   Cookie.remove('authToken')
   this.$router.push('/')
}

I hope this helps someone or someone get idea from this to make something else. 我希望这可以帮助某人或某人从中得到一些想法,从而做出其他事情。 I had million problems with official nuxt auth and only this helped me sort things out... 我在使用nuxt官方认证时遇到了数百万个问题,只有这样才能帮助我解决问题...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM