Last active
February 21, 2019 23:44
-
-
Save michaeltcoelho/9330d2a3ecaf485a3d61e36aead951c6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// auth.js in nuxtjs/store | |
export const state = () => { | |
return { | |
session: { | |
user: null, | |
token: null | |
} | |
} | |
} | |
export const mutations = { | |
SET_TOKEN(state, token) { | |
state.session.token = token | |
}, | |
SET_CURRENT_USER(state, user) { | |
state.session.user = user | |
} | |
} | |
export const actions = { | |
async nuxtServerInit({ dispatch }, { req }) { | |
const token = getTokenFromCookie(req) | |
if (token) { | |
await dispatch('refreshSession', { token }) | |
} | |
}, | |
setToken({ commit }, token) { | |
Cookie.set('token', token) | |
commit('SET_TOKEN', token) | |
this.$axios.setToken(token, 'Token') | |
}, | |
me({ commit }) { | |
this.$axios | |
.get('/auth/me') | |
.then(({ data }) => { | |
commit('SET_CURRENT_USER', data) | |
}) | |
.catch(err => { | |
console.log(err) | |
}) | |
}, | |
refreshSession({ dispatch }, { token }) { | |
dispatch('setToken', token) | |
dispatch('me') | |
}, | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// index.js in nuxtjs/store | |
export const actions = { | |
async nuxtServerInit({ dispatch }, context) { | |
await dispatch('auth/nuxtServerInit', context) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment