user.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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 code = userInfo.code
  42. const uuid = userInfo.uuid
  43. return new Promise((resolve, reject) => {
  44. login(username, password, code, uuid).then(res => {
  45. res = res.data;
  46. // 设置 token
  47. setToken(res)
  48. resolve()
  49. }).catch(error => {
  50. reject(error)
  51. })
  52. })
  53. },
  54. // 获取用户信息
  55. GetInfo({ commit, state }) {
  56. return new Promise((resolve, reject) => {
  57. getInfo().then(res => {
  58. res = res.data; // 读取 data 数据
  59. const user = res.user
  60. const avatar = (user == null || user.avatar === "" || user.avatar == null) ? require("@/static/images/profile.jpg") : user.avatar
  61. const nickname = (user == null || user.nickname === "" || user.nickname == null) ? "" : user.nickname
  62. if (res.roles && res.roles.length > 0) {
  63. commit('SET_ROLES', res.roles)
  64. commit('SET_PERMISSIONS', res.permissions)
  65. } else {
  66. commit('SET_ROLES', ['ROLE_DEFAULT'])
  67. }
  68. commit('SET_NAME', nickname)
  69. commit('SET_AVATAR', avatar)
  70. resolve(res)
  71. }).catch(error => {
  72. reject(error)
  73. })
  74. })
  75. },
  76. // 退出系统
  77. LogOut({ commit, state }) {
  78. return new Promise((resolve, reject) => {
  79. logout(state.token).then(() => {
  80. commit('SET_TOKEN', '')
  81. commit('SET_ROLES', [])
  82. commit('SET_PERMISSIONS', [])
  83. removeToken()
  84. storage.clean()
  85. resolve()
  86. }).catch(error => {
  87. reject(error)
  88. })
  89. })
  90. }
  91. }
  92. }
  93. export default user