import { getGlobalData, setGlobalData } from '../utils/globalData'; import Page from './Page'; import { clearInterval, setInterval } from './Scheduler'; export interface AuthState { __auth__: { login: boolean; } } const ScopeUserInfoKey = '__scopeUserInfo__'; abstract class Auth { /** 是否已setLoginState过 */ private isInit = false; /** 登录状态 */ public get loginState() { try { return getGlobalData().__auth__.login; } catch(err) { return false; } } /** 设置登录状态 */ public setLoginState(value: boolean) { setGlobalData({ __auth__: { login: value } }); } protected abstract code2Session(code: string): Promise; /** 登录初始化时调用 */ public ready(callback: (state: boolean) => void) { if (!this.isInit) { const timer = setInterval(() => { if (this.isInit) { callback(this.loginState); clearInterval(timer); } return true; }, 100); } else { callback(this.loginState); } } /** 更新登录状态 */ public updateLoginState(instance: Page) { instance.setData({ __loginState__: this.loginState }); } private checkSession() { return new Promise((reslove) => { wx.checkSession({ success: (res) => { reslove(true); }, fail: () => { reslove(false); } }); }); } /** * 调用微信登录后再调用code2Session获取userChaceId * @param isAppLaunch 是否是在APP.onLaunch处调用的 * @returns {Promise} 登录是否成功 */ public wxLogin(): Promise { return new Promise(async (resolve, reject) => { if (this.loginState && await this.checkSession()) { this.isInit = true; resolve(true); } else { wx.login({ success: async (res) => { this.isInit = true; if (res.code && await this.code2Session(res.code)) { resolve(true); } else { resolve(false); } }, fail: (err) => { this.isInit = true; resolve(false); throw err; } }); } }); } /** 储存用户授权状态 * @description 只储存已授权的状态,避免二次授权 */ public saveScopeUserInfo() { wx.setStorage({ key: ScopeUserInfoKey, data: true }); } /** 读取用户授权状态 */ public getScopeUserInfo(): boolean { return wx.getStorageSync(ScopeUserInfoKey) || false; } } export default Auth;