UNPKG

react-app-shell

Version:

react打包脚本和example, 这里的版本请忽略

150 lines (127 loc) 4.34 kB
import React, {Component} from 'react'; import {withRouter} from 'react-router-dom'; import queryString from 'query-string'; import {AccountsType} from '../../constants'; import {localStore, tools} from '../../utils'; import {appConfig} from '../../config'; /** * 项目的二级目录 */ const basename = appConfig.basename; /** * 默认选项 * @type {{account: string}} */ const defaultOpptions = { account: AccountsType.MAIN, /** * 支持环境. * wechat: 只支持微信环境, 在其他浏览器里 页面无法打开 * all: 微信和普通浏览器环境 都可以打开, 微信会检查用户是否授权, 普通浏览器跳过 */ support: 'wechat' }; /** * 检查是否主动授权 * @param options * @returns {function(*): InnerComponent} */ export default function checkUserAuth(options = {}) { return (WrappedComponent) => { @withRouter class InnerComponent extends Component { constructor(props) { super(props); console.log('checkUserAuth >>>>> '); options = { ...defaultOpptions, ...options }; const {account, support} = options; let openIdKey; switch (account) { case AccountsType.MAIN: // 主公众号 openIdKey = appConfig.cookie.mainOpenIdKey; break; case AccountsType.ACTIVITY: // 活动公众号 openIdKey = appConfig.cookie.activityOpenIdKey; break; case AccountsType.BONNY: // 魔小兔公众号 openIdKey = appConfig.cookie.bonnyOpenIdKey; break; default: openIdKey = appConfig.cookie.mainOpenIdKey; break; } const openId = localStore.get(openIdKey) || ''; this.account = account; this.support = support; this.openId = openId; this.isWeChat = tools.isWeChat(); // 判断是否是微信浏览器 this.authUrl = this.getAuthUrl(); this.checkAuth(); } /** * 获取统一授权地址 * @returns {string} */ getAuthUrl = () => { // 本地开发环境 不处理 if (appConfig.env === 'development') return ''; let {from, isappinstalled, ...params} = queryString.parse(window.location.search); // 当前URL地址 let search = queryString.stringify(params); if (search) { search = `?${search}`; } let returnUrl = `${location.protocol}//${location.host}${location.pathname}${search}`; // 统一授权地址 // 需要两个参数: account 使用哪个微信公众号, returnUrl 前端应用地址 params = {}; params.account = this.account; params.returnUrl = encodeURIComponent(returnUrl); let authUrl = `${location.protocol}//${ location.host }${basename}/auth?${queryString.stringify(params)}`; return authUrl; }; /** * 检查用户主动授权的openId */ checkAuth = () => { /** * !!!本地开发环境, 跳过检查 */ if (appConfig.env === 'development') return; /** * !!!如果不是微信浏览器 并且 支持在其他浏览器里打开, 跳过检查 */ if (!this.isWeChat && this.support === 'all') { return; } // 如果已经授权过, 则不需要重复授权 if (this.openId) { return; } window.location.replace(this.authUrl); }; render() { // 1. 开发环境 // 2. 只支持微信环境 并且 已授权 拿到openId // 3. 支持其他浏览器打开 if ( appConfig.env === 'development' || (this.support === 'wechat' && this.openId) || this.support === 'all' ) { return <WrappedComponent {...this.props} authUrl={this.authUrl}/>; } return null; } } return InnerComponent; }; }