auth.ts 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. import { defineStore } from 'pinia'
  2. import { ref, computed } from 'vue'
  3. import type { User, UserRole } from '../types'
  4. import { login, logout } from '../api/auth'
  5. import type { LoginMenu } from '../api/auth'
  6. import { getTeamSimpleList } from '../api/team'
  7. export const useAuthStore = defineStore('auth', () => {
  8. // State
  9. const token = ref<string>('')
  10. const user = ref<User | null>(null)
  11. const roleInfo = ref<{
  12. roleId?: number
  13. roleName?: string
  14. roleKey?: string
  15. homePath?: string
  16. menus?: LoginMenu[]
  17. permissions?: string[]
  18. endpoints?: string[]
  19. } | null>(null)
  20. // Getters
  21. const isLoggedIn = computed(() => !!token.value)
  22. const userName = computed(() => user.value?.name || '')
  23. const userRole = computed(() => user.value?.role || '')
  24. const userInfo = computed(() => user.value)
  25. const homePath = computed(() => roleInfo.value?.homePath || '')
  26. const userEndpoints = computed(() => roleInfo.value?.endpoints || [])
  27. // 由账号绑定的可登录端点推导所属业务端
  28. const endpointToRole = (endpoints?: string[]): UserRole | null => {
  29. const map: Record<string, UserRole> = {
  30. 'mp-sales': 'sales',
  31. 'mp-dispatch': 'dispatch',
  32. 'mp-construction': 'construction',
  33. }
  34. for (const code of endpoints || []) {
  35. if (map[code]) return map[code]
  36. }
  37. return null
  38. }
  39. // Actions
  40. async function doLogin(
  41. username: string,
  42. password: string,
  43. selectedRole?: 'mp-sales' | 'mp-dispatch' | 'mp-construction'
  44. ) {
  45. const res = await login({ username, password, roleType: selectedRole })
  46. let teamName = ''
  47. try {
  48. const teams = await getTeamSimpleList()
  49. const team = teams.find((t) => t.value === res.teamId)
  50. teamName = team?.label || ''
  51. } catch {
  52. teamName = ''
  53. }
  54. const finalRole = endpointToRole(res.endpoints)
  55. if (!finalRole) {
  56. uni.showToast({ title: '当前账号未配置可登录端点,无法登录', icon: 'none' })
  57. throw new Error('当前账号未配置可登录端点')
  58. }
  59. const userData: User = {
  60. id: String(res.userId),
  61. name: res.nickName || res.userName,
  62. phone: res.phonenumber || res.phone || '',
  63. avatar: res.avatar,
  64. role: finalRole,
  65. department: res.deptName || res.dept?.deptName || '',
  66. deptId: res.deptId || res.dept?.deptId,
  67. employeeNo: res.staffCode || res.employeeNo || '',
  68. email: res.email || '',
  69. hireDate: res.entryDate || res.hireDate || '',
  70. team: teamName || res.teamName || res.team || '',
  71. teamId: res.teamId,
  72. postNames: res.postNames || '',
  73. dutyStatus: res.dutyStatus || '',
  74. skillLevel: res.skillLevel || '',
  75. certifications: res.certifications || '',
  76. tags: res.tags || '',
  77. skillTags: res.skillTags || '',
  78. currentTaskId: res.currentTaskId,
  79. status: 'active',
  80. }
  81. const roleData = {
  82. roleId: res.roleId,
  83. roleName: res.roleName,
  84. roleKey: res.roleKey,
  85. homePath: res.homePath,
  86. menus: res.menus,
  87. permissions: res.permissions,
  88. endpoints: res.endpoints,
  89. }
  90. user.value = userData
  91. roleInfo.value = roleData
  92. token.value = res.token
  93. // 保存到本地存储
  94. uni.setStorageSync('token', res.token)
  95. uni.setStorageSync('user', JSON.stringify(userData))
  96. uni.setStorageSync('roleInfo', JSON.stringify(roleData))
  97. return finalRole
  98. }
  99. async function doLogout() {
  100. try {
  101. await logout()
  102. } catch {
  103. // 忽略登出失败
  104. }
  105. token.value = ''
  106. user.value = null
  107. roleInfo.value = null
  108. uni.removeStorageSync('token')
  109. uni.removeStorageSync('user')
  110. uni.removeStorageSync('roleInfo')
  111. }
  112. // 兼容旧代码的别名
  113. const logout = doLogout
  114. function checkLogin() {
  115. const savedToken = uni.getStorageSync('token')
  116. const savedUser = uni.getStorageSync('user')
  117. const savedRoleInfo = uni.getStorageSync('roleInfo')
  118. if (savedToken && savedUser) {
  119. token.value = savedToken
  120. try {
  121. user.value = JSON.parse(savedUser)
  122. } catch {
  123. user.value = null
  124. }
  125. }
  126. if (savedRoleInfo) {
  127. try {
  128. roleInfo.value = JSON.parse(savedRoleInfo)
  129. } catch {
  130. roleInfo.value = null
  131. }
  132. }
  133. }
  134. return {
  135. token,
  136. user,
  137. roleInfo,
  138. isLoggedIn,
  139. userName,
  140. userRole,
  141. userInfo,
  142. homePath,
  143. userEndpoints,
  144. doLogin,
  145. doLogout,
  146. logout,
  147. checkLogin,
  148. }
  149. })