privacy.js 2.45 KB
import Storage from '@/utils/cache/storage'

const storage = new Storage()

const readStoredConsent = () => {
  const value = storage.get('privacyAgreed')
  return value === true || value === false ? value : null
}

const readNativeConsent = () => {
  // #ifdef APP-PLUS
  try {
    if (
      typeof plus !== 'undefined' &&
      plus.runtime &&
      typeof plus.runtime.isAgreePrivacy === 'function'
    ) {
      return plus.runtime.isAgreePrivacy() === true
    }
  } catch (error) {
    console.warn('[privacy] 原生隐私同意状态读取失败', error)
  }
  // #endif
  return null
}

const hasLegacyUserInfo = () => {
  const userInfo = storage.get('userInfo')
  return Boolean(
    userInfo &&
    (typeof userInfo !== 'object' || Object.keys(userInfo).length > 0)
  )
}

const persistConsent = async (value) => {
  try {
    await storage.set('privacyAgreed', value)
  } catch (error) {
    console.warn('[privacy] 隐私同意状态持久化失败', error)
  }
}

export default {
  state() {
    return {
      privacyAgreed: false
    }
  },
  getters: {
    hasPrivacyConsent: state => state.privacyAgreed === true
  },
  mutations: {
    SET_PRIVACY_CONSENT(state, value) {
      state.privacyAgreed = value === true
    }
  },
  actions: {
    async initializePrivacyConsent({ commit }) {
      // App 启动阶段同步 androidPrivacy.json 原生弹窗状态;
      // 登录页会单独重置为未勾选,要求用户手动确认。
      const nativeConsent = readNativeConsent()
      if (nativeConsent !== null) {
        commit('SET_PRIVACY_CONSENT', nativeConsent)
        await persistConsent(nativeConsent)
        return nativeConsent
      }

      const storedConsent = readStoredConsent()
      if (storedConsent !== null) {
        commit('SET_PRIVACY_CONSENT', storedConsent)
        return storedConsent
      }

      // 兼容老版本:已有有效登录信息表示用户曾在登录页勾选过隐私协议。
      const migratedConsent = hasLegacyUserInfo()
      commit('SET_PRIVACY_CONSENT', migratedConsent)
      await persistConsent(migratedConsent)
      return migratedConsent
    },
    async setPrivacyConsent({ commit }, value) {
      const agreed = value === true
      commit('SET_PRIVACY_CONSENT', agreed)
      await persistConsent(agreed)

      if (!agreed) {
        await uni.$logger?.disableRemote?.()
      }
      return agreed
    },
    resetPrivacyConsent({ dispatch }) {
      return dispatch('setPrivacyConsent', false)
    }
  }
}