103 lines
2.9 KiB
JavaScript
103 lines
2.9 KiB
JavaScript
const auth = require('./utils/auth')
|
|
const authApi = require('./api/auth')
|
|
const { BRAND_CONFIG } = require('./utils/config')
|
|
|
|
App({
|
|
globalData: {
|
|
appName: BRAND_CONFIG.appName,
|
|
shopName: BRAND_CONFIG.defaultShopName,
|
|
userInfo: null,
|
|
planningNeedRefresh: false,
|
|
wechatLoginState: null
|
|
},
|
|
|
|
onLaunch() {
|
|
this.bootstrapSession()
|
|
this.bootstrapWechatLogin()
|
|
},
|
|
|
|
getWechatCode() {
|
|
return new Promise((resolve, reject) => {
|
|
wx.login({
|
|
success: result => result.code ? resolve(result.code) : reject(new Error('未获取到微信登录凭证')),
|
|
fail: reject
|
|
})
|
|
})
|
|
},
|
|
|
|
async bootstrapWechatLogin() {
|
|
try {
|
|
const status = await authApi.wechatStatus(await this.getWechatCode())
|
|
this.publishWechatLoginState(status)
|
|
const preference = auth.getLoginPreference()
|
|
if (!preference.rememberMe || status.status !== 'READY') {
|
|
auth.clearSession()
|
|
this.globalData.userInfo = null
|
|
this.goLoginIfNeeded()
|
|
return
|
|
}
|
|
const result = await authApi.wechatQuickLogin({
|
|
wxCode: await this.getWechatCode(),
|
|
preferredShopId: preference.preferredShopId,
|
|
agreementAccepted: true,
|
|
agreementVersions: preference.agreementVersions || {},
|
|
clientType: 'WECHAT_MINI'
|
|
})
|
|
this.publishWechatLoginState(result)
|
|
if (result.status === 'SUCCESS' && result.accessToken) {
|
|
this.setSession(result)
|
|
wx.reLaunch({ url: '/pages/planning/index' })
|
|
return
|
|
}
|
|
wx.reLaunch({ url: '/pages/login/index' })
|
|
} catch (error) {
|
|
auth.clearSession()
|
|
this.globalData.userInfo = null
|
|
this.publishWechatLoginState({
|
|
status: 'ERROR',
|
|
message: error.message || '自动登录失败,请点击重试'
|
|
})
|
|
this.goLoginIfNeeded()
|
|
}
|
|
},
|
|
|
|
goLoginIfNeeded() {
|
|
const pages = getCurrentPages()
|
|
const current = pages.length ? pages[pages.length - 1].route : ''
|
|
if (current !== 'pages/login/index') wx.reLaunch({ url: '/pages/login/index' })
|
|
},
|
|
|
|
publishWechatLoginState(state) {
|
|
this.globalData.wechatLoginState = state
|
|
const pages = getCurrentPages()
|
|
const current = pages.length ? pages[pages.length - 1] : null
|
|
if (current && current.route === 'pages/login/index' && typeof current.setData === 'function') {
|
|
current.setData({ loginState: state })
|
|
}
|
|
},
|
|
|
|
bootstrapSession() {
|
|
const session = auth.getSession()
|
|
this.globalData.userInfo = session.userInfo || null
|
|
if (session.shopName) {
|
|
this.globalData.shopName = session.shopName
|
|
}
|
|
},
|
|
|
|
setSession(session) {
|
|
auth.setSession(session)
|
|
this.bootstrapSession()
|
|
},
|
|
|
|
clearSession() {
|
|
auth.clearSession()
|
|
this.globalData.userInfo = null
|
|
},
|
|
|
|
logoutDevice() {
|
|
auth.clearDeviceLoginState()
|
|
this.globalData.userInfo = null
|
|
this.globalData.wechatLoginState = null
|
|
}
|
|
})
|