user.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import config from '@/config'
  2. import storage from '@/utils/storage'
  3. import constant from '@/utils/constant'
  4. import { login, logout, getInfo } from '@/api/login'
  5. import { getToken, setToken, removeToken } from '@/utils/auth'
  6. const baseUrl = config.baseUrl
  7. const user = {
  8. state: {
  9. token: getToken(),
  10. name: storage.get(constant.name),
  11. avatar: storage.get(constant.avatar),
  12. roles: storage.get(constant.roles),
  13. permissions: storage.get(constant.permissions)
  14. },
  15. mutations: {
  16. SET_TOKEN: (state, token) => {
  17. state.token = token
  18. },
  19. SET_NAME: (state, name) => {
  20. state.name = name
  21. storage.set(constant.name, name)
  22. },
  23. SET_AVATAR: (state, avatar) => {
  24. state.avatar = avatar
  25. storage.set(constant.avatar, avatar)
  26. },
  27. SET_ROLES: (state, roles) => {
  28. state.roles = roles
  29. storage.set(constant.roles, roles)
  30. },
  31. SET_PERMISSIONS: (state, permissions) => {
  32. state.permissions = permissions
  33. storage.set(constant.permissions, permissions)
  34. }
  35. },
  36. actions: {
  37. // 登录
  38. Login({ commit }, userInfo) {
  39. const username = userInfo.username.trim()
  40. const password = userInfo.password
  41. const code = userInfo.code
  42. const uuid = userInfo.uuid
  43. return new Promise((resolve, reject) => {
  44. login(username, password, code, uuid).then(res => {
  45. setToken(res.token)
  46. commit('SET_TOKEN', res.token)
  47. resolve()
  48. }).catch(error => {
  49. reject(error)
  50. })
  51. })
  52. },
  53. // 获取用户信息
  54. GetInfo({ commit, state }) {
  55. return new Promise((resolve, reject) => {
  56. getInfo().then(res => {
  57. const user = res.user
  58. const avatar = (user == null || user.avatar == "" || user.avatar == null) ? require("@/static/images/profile.jpg") : baseUrl + user.avatar
  59. const username = (user == null || user.userName == "" || user.userName == null) ? "" : user.userName
  60. if (res.roles && res.roles.length > 0) {
  61. commit('SET_ROLES', res.roles)
  62. commit('SET_PERMISSIONS', res.permissions)
  63. } else {
  64. commit('SET_ROLES', ['ROLE_DEFAULT'])
  65. }
  66. commit('SET_NAME', username)
  67. commit('SET_AVATAR', avatar)
  68. resolve(res)
  69. }).catch(error => {
  70. reject(error)
  71. })
  72. })
  73. },
  74. // 退出系统
  75. LogOut({ commit, state }) {
  76. return new Promise((resolve, reject) => {
  77. logout(state.token).then(() => {
  78. commit('SET_TOKEN', '')
  79. commit('SET_ROLES', [])
  80. commit('SET_PERMISSIONS', [])
  81. removeToken()
  82. storage.clean()
  83. resolve()
  84. }).catch(error => {
  85. reject(error)
  86. })
  87. })
  88. }
  89. }
  90. }
  91. export default user