welfare-admin/src/store/modules/user.js

96 lines
2.4 KiB
JavaScript

import storage from 'store'
import { login, getLoginUser, logout } from '@/api/login'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { welcome } from '@/utils/util'
const user = {
state: {
token: '',
name: '',
welcome: '',
avatar: '',
roles: [],
buttons: [], // 按钮权限
info: {}
},
mutations: {
SET_TOKEN: (state, token) => {
state.token = token
},
SET_NAME: (state, { name, welcome }) => {
state.name = name
state.welcome = welcome
},
SET_AVATAR: (state, avatar) => {
state.avatar = avatar
},
SET_ROLES: (state, roles) => {
state.roles = roles
},
SET_INFO: (state, info) => {
state.info = info
},
SET_BUTTONS: (state, buttons) => {
state.buttons = buttons
}
},
actions: {
// 登录
Login({ commit }, userInfo) {
return new Promise((resolve, reject) => {
login(userInfo).then(response => {
storage.set(ACCESS_TOKEN, response.token, 24 * 60 * 60 * 1000)
commit('SET_TOKEN', response.token)
resolve()
}).catch(error => {
reject('后端未启动或代理错误')
})
})
},
// 获取用户信息
GetInfo({ commit }) {
return new Promise((resolve, reject) => {
getLoginUser().then(response => {
if (response.code === 200) {
const data = response.data
commit('SET_ROLES', 1)
commit('SET_BUTTONS', data.permissions)
commit('SET_INFO', data.user)
commit('SET_NAME', { name: data.user.userName, welcome: welcome() })
if (data.user.avatar != null) {
commit('SET_AVATAR', process.env.VUE_APP_API_BASE_URL + '/sysFileInfo/preview?id=' + data.user.avatar)
}
resolve(data)
} else {
reject(new Error(data.msg))
}
}).catch(error => {
reject(error)
})
})
},
// 登出
Logout({ commit, state }) {
return new Promise((resolve) => {
logout().then(() => {
resolve()
}).catch(() => {
resolve()
}).finally(() => {
commit('SET_TOKEN', '')
commit('SET_ROLES', [])
commit('SET_BUTTONS', [])
commit('SET_ROUTERS', [])
storage.remove(ACCESS_TOKEN)
})
})
}
}
}
export default user