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

38 lines
847 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 (state, user) {
2017-02-03 14:09:27 +00:00
state.authUser = user
}
}
2016-12-07 16:03:52 +00:00
2017-02-03 14:09:27 +00:00
export const actions = {
2020-11-30 22:44:04 +00:00
// nuxtServerInit is called by Nuxt before server-rendering every page
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
}
},
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
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
}