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

42 lines
779 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-02-03 14:09:27 +00:00
export const state = {
authUser: null
}
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 ({ commit }, { req }) {
if (req.session && req.session.authUser) {
commit('SET_USER', req.session.authUser)
2016-12-07 16:03:52 +00:00
}
},
2017-02-03 14:09:27 +00:00
login ({ commit }, { username, password }) {
return axios.post('/api/login', {
username,
password
})
.then((res) => {
commit('SET_USER', res.data)
})
.catch((error) => {
if (error.response.status === 401) {
throw new Error('Bad credentials')
2016-12-07 16:03:52 +00:00
}
2017-02-03 14:09:27 +00:00
})
},
2016-12-07 16:03:52 +00:00
2017-02-03 14:09:27 +00:00
logout ({ commit }) {
return axios.post('/api/logout')
.then(() => {
commit('SET_USER', null)
})
2016-12-07 16:03:52 +00:00
}
2017-02-03 14:09:27 +00:00
}