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 { setToken, removeToken } from '@/utils/auth'
  6. const baseUrl = config.baseUrl
  7. const user = {
  8. state: {
  9. id: 0, // 用户编号
  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_ID: (state, id) => {
  17. state.id = id
  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 captchaVerification = userInfo.captchaVerification
  42. return new Promise((resolve, reject) => {
  43. login(username, password, captchaVerification).then(res => {
  44. res = res.data;
  45. // 设置 token
  46. setToken(res)
  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. res = res.data; // 读取 data 数据
  58. const user = res.user
  59. const avatar = (user == null || user.avatar === "" || user.avatar == null) ? require("@/static/images/profile.jpg") : user.avatar
  60. const nickname = (user == null || user.nickname === "" || user.nickname == null) ? "" : user.nickname
  61. if (res.roles && res.roles.length > 0) {
  62. commit('SET_ROLES', res.roles)
  63. commit('SET_PERMISSIONS', res.permissions)
  64. } else {
  65. commit('SET_ROLES', ['ROLE_DEFAULT'])
  66. }
  67. commit('SET_NAME', nickname)
  68. commit('SET_AVATAR', avatar)
  69. resolve(res)
  70. }).catch(error => {
  71. reject(error)
  72. })
  73. })
  74. },
  75. // 退出系统
  76. LogOut({ commit, state }) {
  77. return new Promise((resolve, reject) => {
  78. logout(state.token).then(() => {
  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