const auth = require('./utils/auth') const permission = require('./utils/permission') const { resetLoading } = require('./utils/loading') const idleSession = require('./utils/idle-session') const { IDLE_TIMEOUT_MS, IDLE_WARNING_MS } = require('./utils/config') const permissionApi = require('./api/permission') const authApi = require('./api/auth') function buildCurrentShop(userInfo) { if (!userInfo || !userInfo.shopId) { return null } return { id: userInfo.shopId, shopName: userInfo.shopName || '' } } App({ globalData: { isLoggedIn: false, userInfo: null, currentShop: null, permissions: [], permissionCodes: [], pageDirtyFlags: {} }, onLaunch() { idleSession.init({ timeoutMs: IDLE_TIMEOUT_MS, warningMs: IDLE_WARNING_MS, isLoggedIn: () => auth.isLoggedIn(), onLogout: () => this.handleIdleLogout() }) this.bootstrapSession() }, onShow() { idleSession.onAppShow() }, onHide() { idleSession.onAppHide() }, bootstrapSession() { resetLoading() const userInfo = auth.getStoredUserInfo() const currentShop = auth.getCurrentShop() || buildCurrentShop(userInfo) const permissions = auth.getStoredPermissions() if (currentShop) { auth.setCurrentShop(currentShop) } this.globalData.isLoggedIn = auth.isLoggedIn() this.globalData.userInfo = userInfo this.globalData.currentShop = currentShop this.setPermissionState(permissions) if (this.globalData.isLoggedIn && !permissions.length) { this.loadCurrentPermissions().catch(() => undefined) } }, setPermissionState(permissions) { const list = Array.isArray(permissions) ? permissions : [] this.globalData.permissions = list this.globalData.permissionCodes = permission.getPermissionCodes(list) }, async setAdminSession(payload) { auth.setSession(payload) this.bootstrapSession() await this.loadCurrentPermissions().catch(() => []) }, async loadCurrentPermissions() { if (!auth.isLoggedIn()) { auth.clearPermissions() this.setPermissionState([]) return [] } const permissions = await permissionApi.getCurrentUserPermissions() auth.setPermissions(permissions) this.setPermissionState(permissions) return permissions }, refreshUserInfo(userInfo) { auth.updateStoredUserInfo(userInfo) if (userInfo && userInfo.shopId) { auth.setCurrentShop({ id: userInfo.shopId, shopName: userInfo.shopName || '' }) } this.bootstrapSession() }, clearAdminSession() { auth.clearSession() this.globalData.isLoggedIn = false this.globalData.userInfo = null this.globalData.currentShop = null this.globalData.pageDirtyFlags = {} this.setPermissionState([]) }, async handleIdleLogout() { if (!auth.isLoggedIn()) { return } try { await authApi.logout() } catch (error) {} this.clearAdminSession() wx.showToast({ title: '长时间未操作,已退出登录', icon: 'none' }) setTimeout(() => { wx.reLaunch({ url: '/pages/login/index' }) }, 260) }, async switchAdminShop(shopId) { const payload = await authApi.switchShop(shopId) await this.setAdminSession(payload) return payload } })