user.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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