init.uts 7.0 KB
Newer Older
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
1 2 3
// 导入 autoReportPushClientId 模块,将再重新登录会 token 续期后自动将客户端上报到服务端
// import reportPushClientId from '@/uni_modules/uni-id-pages-x/lib/autoReportPushClientId.uts'

A
Anne_LXM 已提交
4
// 导入配置
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
5 6 7
import config from '@/uni_modules/uni-id-pages-x/config.uts'
import {state} from '@/uni_modules/uni-id-pages-x/store.uts';

A
Anne_LXM 已提交
8 9 10 11 12
// uni-id的云对象
const uniIdCo = uniCloud.importObject('uni-id-co', {
  customUI: true
})
// 用户配置的登录方式、是否打开调试模式
A
Anne_LXM 已提交
13 14 15
const configLoginTypes = config.getArray<string>('loginTypes');
const loginTypes = configLoginTypes == null ? [] as string[] : configLoginTypes;

DCloud_JSON's avatar
init  
DCloud_JSON 已提交
16
const debug = config.getBoolean('debug') as boolean;
A
Anne_LXM 已提交
17

A
Anne_LXM 已提交
18
// #ifdef APP && uniVersion >= 3.98
DCloud_JSON's avatar
DCloud_JSON 已提交
19
import Univerify from '@/uni_modules/uni-id-pages-x/lib/Univerify.uts'
A
Anne_LXM 已提交
20 21
// #endif

DCloud_JSON's avatar
DCloud_JSON 已提交
22

DCloud_JSON's avatar
init  
DCloud_JSON 已提交
23
export default async function () {
A
Anne_LXM 已提交
24 25 26
  // 有打开调试模式的情况下
  if (debug) {
    // 1. 检查本地uni-id-pages中配置的登录方式,服务器端是否已经配置正确。否则提醒并引导去配置
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
27
    // 调用云对象,获取服务端已正确配置的登录方式
A
Anne_LXM 已提交
28
    uniIdCo.getSupportedLoginType().then((res:UTSJSONObject)=>{
DCloud_JSON's avatar
DCloud_JSON 已提交
29
      // console.log('7777res',res)
A
Anne_LXM 已提交
30
      let supportedLoginType = res.getArray<string>('supportedLoginType')
A
Anne_LXM 已提交
31
      // console.log('supportedLoginType: ',supportedLoginType);
DCloud_JSON's avatar
DCloud_JSON 已提交
32 33
      if(supportedLoginType == null){
        supportedLoginType = []
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
34
      }
DCloud_JSON's avatar
DCloud_JSON 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
      // 登录方式,服务端和客户端的映射关系
      const data:UTSJSONObject = {
        "univerify": 'univerify',
        "username": 'username-password',
        "weixin": 'weixin',
        "qq": 'qq',
        "xiaomi": 'xiaomi',
        "sinaweibo": 'sinaweibo',
        "taobao": 'taobao',
        "facebook": 'facebook',
        "google": 'google',
        "alipay": 'alipay',
        "apple": 'apple',
        "weixinMobile": 'weixin'
      };
      // 遍历客户端配置的登录方式,与服务端比对。并在错误时抛出错误提示
A
Anne_LXM 已提交
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
      // const list = loginTypes?.filter((type:string):boolean =>type != 'smsCode')
      // ?.filter((type:string):boolean =>{
      //   let currentType = data.getString(type);
      //   if(currentType == null){
      //     currentType = ""
      //   }
      //   return supportedLoginType?.includes(currentType) != true
      // })
      const list:Array<string> = [];
      console.log('loginTypes: ',loginTypes);
      for (let i = 0; i < loginTypes.length; i++) {
        const type = loginTypes[i];
        if (type != 'smsCode') {
          let currentType = data.getString(type);
          if (currentType === null) {
            currentType = '';
          }
          if (!supportedLoginType.includes(currentType)) {
            list.push(type);
          }
DCloud_JSON's avatar
DCloud_JSON 已提交
71
        }
A
Anne_LXM 已提交
72 73
      }
      if (list.length != 0) {
DCloud_JSON's avatar
DCloud_JSON 已提交
74
        console.error(
A
Anne_LXM 已提交
75
      		`错误:前端启用的登录方式:${list.join(',')};没有在服务端完成配置。配置文件路径:"/uni_modules/uni-config-center/uniCloud/cloudfunctions/common/uni-config-center/uni-id/config.json"`
DCloud_JSON's avatar
DCloud_JSON 已提交
76 77
        )
      }
A
Anne_LXM 已提交
78 79 80
    })
  }

A
Anne_LXM 已提交
81
  // #ifdef APP && uniVersion >= 3.98
A
Anne_LXM 已提交
82
  // 如果uni-id-pages配置的登录功能有一键登录,有则执行预登录(异步)
A
Anne_LXM 已提交
83
  if (loginTypes.includes('univerify')) {
DCloud_JSON's avatar
DCloud_JSON 已提交
84 85 86 87 88 89 90 91 92 93 94 95
    const myUniverify = new Univerify()
    const univerifyManager = uni.getUniverifyManager();
    univerifyManager.preLogin({
      success() {
        console.log("pre login success");
      },
      fail(err : PreLoginFail) {
        console.error("pre login fail => " + JSON.stringify(err));
      }
    } as PreLoginOptions);


A
Anne_LXM 已提交
96 97 98 99 100 101 102 103 104 105
    const handleInterceptor = (geturl:string)=>{
      if (geturl.indexOf("/uni_modules/uni-id-pages-x/pages/login/login") == 0) {
        let url = decodeURIComponent(geturl)
        let param:UTSJSONObject = {};
        // 获取链接后面的参数部分
        let urlSplit = url!.split('?')
        let type = '';
        if(urlSplit.length > 1){
          let keyValuePairs = urlSplit[1].split('&'); // 将参数按&分隔为键值对数组
          // console.log('keyValuePairs: ',keyValuePairs);
DCloud_JSON's avatar
DCloud_JSON 已提交
106 107 108 109
          keyValuePairs.forEach(keyValuePair => {
            let [key, value] = keyValuePair.split('='); // 将键值对按等号分隔为键和值
            param[key] = value;
          });
A
Anne_LXM 已提交
110 111
          if(typeof param["type"] == 'string'){
            type = param["type"] as string
DCloud_JSON's avatar
DCloud_JSON 已提交
112
          }
A
Anne_LXM 已提交
113 114 115 116 117 118 119
        }
        if(type == ''){
          type = loginTypes[0];
        }
        if(type == "univerify"){
          myUniverify.verify(true)
          throw new Error('第一优先级是一键登录(且可用),就直接调用一键登录,不打开登录页面')
DCloud_JSON's avatar
DCloud_JSON 已提交
120 121
        }
      }
A
Anne_LXM 已提交
122 123 124 125 126 127 128 129 130 131 132
    }

    uni.addInterceptor('navigateTo',{
      invoke:(e:NavigateToOptions)=>{
        handleInterceptor(e.url)
      }
    })
    uni.addInterceptor('redirectTo',{
      invoke:(e:RedirectToOptions)=>{
        handleInterceptor(e.url)
      }
DCloud_JSON's avatar
DCloud_JSON 已提交
133
    })
A
Anne_LXM 已提交
134
  }
A
Anne_LXM 已提交
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149

  // #endif

  // // 3. 绑定clientDB错误事件
  // // clientDB对象
  // const db = uniCloud.database()
  // db.on('error', onDBError)
  // // clientDB的错误提示
  // function onDBError ({
  //   code, // 错误码详见https://uniapp.dcloud.net.cn/uniCloud/clientdb?id=returnvalue
  //   message
  // }) {
  //   // console.error('onDBError', {code,message});
  // }
  // // 解绑clientDB错误事件
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
150 151 152
  // // db.off('error', onDBError)


153 154
  // needLogin相关代码-start(此代码仅为版本兼容提示使用,如已知晓可删除)
  const needLogin = config.getArray<string>('needLogin')
A
Anne_LXM 已提交
155 156
  const uniCompileVersionCode = uni.getSystemInfoSync().uniCompileVersionCode
  if(needLogin != null && (uniCompileVersionCode >= 3.99 ) ){
157 158 159 160 161 162 163 164 165 166 167
    const tipText = "uni-id-pages x v1.0.4+ 不再支持配置项config.needLogin,请升级HBuilderX 版本为3.99+,使用更强大 uni-id-router替代。详情查看:https://uniapp.dcloud.net.cn/uniCloud/uni-id/summary.html#uni-id-router"
    console.error(tipText)
    uni.showModal({
      content: tipText,
      showCancel: false,
      confirmText:"知道了"
    });
  }else{
    const checkNeedLogin = (url:string):boolean=>{
      if(state.isLogin){
        return false
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
168
      }
169 170 171
      if (needLogin != null) {
        return needLogin.every((item:string):boolean => {
          return item == url || new RegExp(item).test(url)
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
172
        })
173 174
      }else{
        return false
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
175 176
      }
    }
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
    uni.addInterceptor('navigateTo',{
      invoke:(e:NavigateToOptions)=>{
        if (checkNeedLogin(e.url)) {
          uni.showToast({
            title: '请先登录',
            icon: 'none'
          })
          e.url = "/uni_modules/uni-id-pages-x/pages/login/login?uniIdRedirectUrl=" + encodeURIComponent(e.url)
        }
      }
    })
    uni.addInterceptor('redirectTo',{
      invoke:(e:RedirectToOptions)=>{
        if (checkNeedLogin(e.url)) {
          uni.showToast({
            title: '请先登录',
            icon: 'none'
          })
          e.url = "/uni_modules/uni-id-pages-x/pages/login/login?uniIdRedirectUrl=" + encodeURIComponent(e.url)
        }
      }
    })
  }
  // needLogin相关代码-end

A
Anne_LXM 已提交
202
}