| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123 |
- /**
- * 用户状态检查工具类
- * 用于检查用户是否被禁用,并在被禁用时显示提示
- * 支持实时刷新状态,当后台修改用户状态后能及时响应
- */
- const BASE_URL = 'https://api.zhongruanke.cn/api'
- export default {
- /**
- * 检查用户是否被禁用(每次操作都实时请求后端)
- * @param {boolean} useCache - 是否使用缓存,默认false(实时请求)
- * @returns {Promise<boolean>} true表示用户正常,false表示用户被禁用
- */
- async checkUserStatus(useCache = false) {
- try {
- const userId = uni.getStorageSync('userId')
- if (!userId) {
- return true // 未登录用户不检查
- }
-
- // 如果允许使用缓存,检查缓存(缓存有效期30秒,用于短时间内连续操作)
- if (useCache) {
- const cachedStatus = uni.getStorageSync('userStatus')
- const cacheTime = uni.getStorageSync('userStatusCacheTime')
- const now = Date.now()
-
- // 缓存有效期30秒(短时间内连续操作不重复请求)
- if (cachedStatus !== undefined && cacheTime && (now - cacheTime) < 30 * 1000) {
- return cachedStatus !== 0
- }
- }
-
- // 调用后端接口获取用户状态(实时请求)
- const [error, res] = await uni.request({
- url: `${BASE_URL}/user/status/${userId}`,
- method: 'GET',
- timeout: 5000
- })
-
- if (error) {
- console.error('检查用户状态失败:', error)
- return true // 网络错误时默认允许操作
- }
-
- if (res.statusCode === 200 && res.data && res.data.code === 200) {
- const status = res.data.data?.status
- const now = Date.now()
-
- // 更新缓存
- uni.setStorageSync('userStatus', status)
- uni.setStorageSync('userStatusCacheTime', now)
-
- if (status === 0) {
- return false // 用户被禁用
- }
- }
-
- return true
- } catch (e) {
- console.error('检查用户状态异常:', e)
- return true // 异常时默认允许操作
- }
- },
-
- /**
- * 显示用户被禁用的提示
- */
- showDisabledTip() {
- uni.showModal({
- title: '账号已被禁用',
- content: '您的当前账号违反规定已被禁用,如有疑问请联系客服',
- showCancel: false,
- confirmText: '我知道了'
- })
- },
-
- /**
- * 检查用户状态,如果被禁用则显示提示并返回false
- * 每次调用都会实时请求后端,确保状态最新
- * @returns {Promise<boolean>} true表示可以继续操作,false表示被禁用
- */
- async checkAndTip() {
- // 实时请求后端,不使用缓存,确保状态最新
- const isNormal = await this.checkUserStatus(false)
- if (!isNormal) {
- this.showDisabledTip()
- return false
- }
- return true
- },
-
- /**
- * 带缓存的状态检查(用于短时间内连续操作,减少请求)
- * 缓存有效期30秒
- * @returns {Promise<boolean>} true表示可以继续操作,false表示被禁用
- */
- async checkAndTipWithCache() {
- const isNormal = await this.checkUserStatus(true)
- if (!isNormal) {
- this.showDisabledTip()
- return false
- }
- return true
- },
-
- /**
- * 清除用户状态缓存(用于登录/登出时)
- */
- clearStatusCache() {
- uni.removeStorageSync('userStatus')
- uni.removeStorageSync('userStatusCacheTime')
- },
-
- /**
- * 强制刷新用户状态(绕过缓存)
- * @returns {Promise<boolean>} true表示用户正常,false表示用户被禁用
- */
- async refreshUserStatus() {
- this.clearStatusCache()
- return await this.checkUserStatus(false)
- }
- }
|