Nuxt/examples/auth-routes/store/index.js

38 lines
857 B
JavaScript
Raw Normal View History

2017-02-03 14:09:27 +00:00
import axios from 'axios'
2016-12-07 16:03:52 +00:00
2017-05-29 15:00:01 +00:00
export const state = () => ({
2017-02-03 14:09:27 +00:00
authUser: null
2017-05-29 15:00:01 +00:00
})
2016-12-07 16:03:52 +00:00
2017-02-03 14:09:27 +00:00
export const mutations = {
SET_USER: function (state, user) {
state.authUser = user
}
}
2016-12-07 16:03:52 +00:00
2017-02-03 14:09:27 +00:00
export const actions = {
// nuxtServerInit is called by Nuxt.js before server-rendering every page
2017-10-31 13:43:55 +00:00
nuxtServerInit({ commit }, { req }) {
2017-02-03 14:09:27 +00:00
if (req.session && req.session.authUser) {
commit('SET_USER', req.session.authUser)
2016-12-07 16:03:52 +00:00
}
},
2017-10-31 13:43:55 +00:00
async login({ commit }, { username, password }) {
try {
const { data } = await axios.post('/api/login', { username, password })
commit('SET_USER', data)
} catch (error) {
if (error.response && error.response.status === 401) {
2017-02-03 14:09:27 +00:00
throw new Error('Bad credentials')
2016-12-07 16:03:52 +00:00
}
throw error
}
2017-02-03 14:09:27 +00:00
},
2016-12-07 16:03:52 +00:00
2017-10-31 13:43:55 +00:00
async logout({ commit }) {
await axios.post('/api/logout')
commit('SET_USER', null)
2016-12-07 16:03:52 +00:00
}
2017-02-03 14:09:27 +00:00
}