userAuth.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. /**
  2. * 用户认证和ID管理工具类
  3. */
  4. export default {
  5. /**
  6. * 智能获取用户ID(修复版)
  7. * @returns {number|null} 用户ID或null
  8. */
  9. getUserId() {
  10. console.log('=== userAuth.getUserId 方法调用 ===')
  11. // 首先检查是否真的已登录(通过token和userInfo判断)
  12. const token = uni.getStorageSync('token')
  13. const userInfo = uni.getStorageSync('userInfo')
  14. const storedUserId = uni.getStorageSync('userId')
  15. console.log('userAuth 登录状态检查:')
  16. console.log('- token存在:', !!token)
  17. console.log('- userInfo存在:', !!userInfo)
  18. console.log('- storedUserId:', storedUserId)
  19. console.log('- userInfo内容:', userInfo)
  20. // 如果有token和userInfo,说明确实已登录
  21. if (token && userInfo) {
  22. // 1. 优先从直接存储的userId获取(包括ID为1的情况)
  23. if (storedUserId !== null && storedUserId !== undefined && storedUserId !== '') {
  24. const finalUserId = parseInt(storedUserId)
  25. console.log('✅ userAuth已登录,从userId存储获取到用户ID:', finalUserId)
  26. return finalUserId
  27. }
  28. // 2. 从userInfo中获取
  29. const userIdFromInfo = userInfo.userId || userInfo.id || userInfo.user_id
  30. if (userIdFromInfo !== null && userIdFromInfo !== undefined) {
  31. const finalUserId = parseInt(userIdFromInfo)
  32. console.log('✅ userAuth已登录,从userInfo获取到用户ID:', finalUserId)
  33. // 同步更新userId存储
  34. uni.setStorageSync('userId', finalUserId)
  35. return finalUserId
  36. }
  37. // 3. 如果有登录信息但无法提取userId,使用默认值1
  38. console.log('⚠️ userAuth有登录信息但无法提取userId,使用默认userId: 1')
  39. uni.setStorageSync('userId', 1)
  40. return 1
  41. }
  42. // 4. 未登录状态
  43. console.log('❌ userAuth未登录状态,返回null')
  44. return null
  45. },
  46. /**
  47. * 检查用户是否已登录
  48. * @returns {boolean} 是否已登录
  49. */
  50. isLoggedIn() {
  51. const token = uni.getStorageSync('token')
  52. const userInfo = uni.getStorageSync('userInfo')
  53. const userId = this.getUserId()
  54. // 修复:允许userId为1的用户(测试用户)也被认为是已登录状态
  55. return !!(token && userInfo && userId)
  56. },
  57. /**
  58. * 获取用户信息
  59. * @returns {object|null} 用户信息对象或null
  60. */
  61. getUserInfo() {
  62. return uni.getStorageSync('userInfo') || null
  63. },
  64. /**
  65. * 获取用户token
  66. * @returns {string|null} token或null
  67. */
  68. getToken() {
  69. return uni.getStorageSync('token') || null
  70. },
  71. /**
  72. * 保存登录信息
  73. * @param {string} token - 登录token
  74. * @param {object} userInfo - 用户信息
  75. */
  76. saveLoginInfo(token, userInfo) {
  77. console.log('=== userAuth.saveLoginInfo ===')
  78. console.log('token:', token)
  79. console.log('userInfo:', userInfo)
  80. // 保存token和用户信息
  81. uni.setStorageSync('token', token)
  82. uni.setStorageSync('userInfo', userInfo)
  83. // 提取并保存用户ID - 支持多种字段名和数据类型
  84. const userId = userInfo?.userId || userInfo?.id || userInfo?.user_id
  85. if (userId !== null && userId !== undefined) {
  86. // 确保userId是数字类型
  87. const finalUserId = parseInt(userId)
  88. uni.setStorageSync('userId', finalUserId)
  89. console.log('✅ 登录信息保存成功')
  90. console.log('- 原始userId:', userId, '(类型:', typeof userId, ')')
  91. console.log('- 处理后userId:', finalUserId, '(类型:', typeof finalUserId, ')')
  92. } else {
  93. console.warn('⚠️ 用户信息中未找到userId字段')
  94. console.warn('userInfo keys:', Object.keys(userInfo || {}))
  95. }
  96. },
  97. /**
  98. * 清除登录信息
  99. */
  100. clearLoginInfo() {
  101. uni.removeStorageSync('token')
  102. uni.removeStorageSync('userInfo')
  103. uni.removeStorageSync('userId')
  104. uni.removeStorageSync('rememberedAccount')
  105. console.log('登录信息已清除')
  106. },
  107. /**
  108. * 检查并处理登录状态
  109. * @param {object} options - 配置选项
  110. * @param {boolean} options.requireLogin - 是否要求必须登录
  111. * @param {boolean} options.allowTestUser - 是否允许使用测试用户(ID=1)
  112. * @param {string} options.redirectUrl - 登录后重定向的URL
  113. * @returns {Promise<number|null>} 返回用户ID或null
  114. */
  115. async checkLoginStatus(options = {}) {
  116. const {
  117. requireLogin = true,
  118. allowTestUser = false,
  119. redirectUrl = ''
  120. } = options
  121. const token = this.getToken()
  122. const userInfo = this.getUserInfo()
  123. const userId = this.getUserId()
  124. // 未登录情况
  125. if (!token || !userInfo) {
  126. if (requireLogin) {
  127. return new Promise((resolve) => {
  128. uni.showModal({
  129. title: '需要登录',
  130. content: '请先登录后继续使用',
  131. showCancel: !requireLogin,
  132. cancelText: '取消',
  133. confirmText: '去登录',
  134. success: (res) => {
  135. if (res.confirm) {
  136. const loginUrl = `/pages/page3/page3${redirectUrl ? '?redirect=' + encodeURIComponent(redirectUrl) : ''}`
  137. uni.navigateTo({ url: loginUrl })
  138. }
  139. resolve(null)
  140. }
  141. })
  142. })
  143. }
  144. return null
  145. }
  146. // 登录信息异常情况
  147. if (!userId || userId === 1) {
  148. if (allowTestUser && userId === 1) {
  149. console.log('允许使用测试用户')
  150. return 1
  151. }
  152. return new Promise((resolve) => {
  153. uni.showModal({
  154. title: '登录信息异常',
  155. content: '登录信息不完整,是否重新登录?',
  156. showCancel: allowTestUser,
  157. cancelText: '使用测试账号',
  158. confirmText: '重新登录',
  159. success: (res) => {
  160. if (res.confirm) {
  161. this.clearLoginInfo()
  162. const loginUrl = `/pages/page3/page3${redirectUrl ? '?redirect=' + encodeURIComponent(redirectUrl) : ''}`
  163. uni.navigateTo({ url: loginUrl })
  164. resolve(null)
  165. } else if (allowTestUser) {
  166. console.log('用户选择使用测试账号')
  167. resolve(1)
  168. } else {
  169. resolve(null)
  170. }
  171. }
  172. })
  173. })
  174. }
  175. // 登录正常
  176. return userId
  177. }
  178. }