import * as utils from './utils' import {weixinAuth} from './weixin' export class Store { device_name = window.navigator.userAgent.toLowerCase().match(/\((.*?)\)/)[1] || '' objects: any = {} alerted = false logined: any = {} loginPromise: any = null getKey() { let c = this.objects.config return `code-${c.appid}` } goAuth() { this.alerted = true // 禁止跳转之后的报错 utils.cacheSet(this.getKey(), '', 0) weixinAuth(window.location.href) throw new Error('go auth') } async login(vue = null, force = 0) { if (typeof vue === 'number') force = vue // 兼容以前的调用 return this.login2(force) } async login2(force = 0) { let route = this.objects.router.currentRoute if (!this.loginPromise && route.query.token) { // 通过url中的token来跳过登陆过程 this.logined.token = route.query.token this.loginPromise = Promise.resolve(this.logined) } if (!force && this.loginPromise) { return await this.loginPromise } this.objects.config.appid = route.query.appid || this.objects.config.appid let code = route.query.code let timestamp = route.query._ts || "0" let now = Math.round(new Date().getTime() / 1000) if (!code || now - +timestamp > 30) { code = utils.cacheGet(this.getKey()) } if (!code) { this.goAuth() } if (code && now - +timestamp < 30) { // 只有最新获取的code才能够更新缓存时间 utils.cacheSet(this.getKey(), code, 86400) } this.loginPromise = this.loginInner(code) return this.loginPromise } async loginInner(code) { let {data} = await this.objects.axios.post(`/api/mobile/user/login/loginByCode`, { code, device_name: this.device_name, }, {disableAlert: true}) if (data.code === 'WX_LOGIN_ERROR') { // 微信在登陆过程中,偶尔发生system error,只能够再次授权登陆 this.goAuth() } Object.assign(this.logined, data) return data } async bindPhone(options) { let {data} = await this.objects.axios.post('/api/mobile/user/login/wechatBindPhone', { ...options, device_name: this.device_name, code: utils.cacheGet(this.getKey()) }) if (data.code) { this.objects.Mint.Toast(data.message) } else { Object.assign(this.logined, data) } } globalParameter() { let {config} = this.objects return { device_id: utils.getDeviceId(), uid: this.logined.uid, token: this.logined.token, version: config.ver, appid: config.appid, openid: this.logined.openid, app_name: config.app_name, } } } export default new Store()