init.uts 6.4 KB
Newer Older
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// 导入 autoReportPushClientId 模块,将再重新登录会 token 续期后自动将客户端上报到服务端
// import reportPushClientId from '@/uni_modules/uni-id-pages-x/lib/autoReportPushClientId.uts'

// 导入配置
import config from '@/uni_modules/uni-id-pages-x/config.uts'

import {state} from '@/uni_modules/uni-id-pages-x/store.uts';

// uni-id的云对象
const uniIdCo = uniCloud.importObject('uni-id-co', {
  customUI: true
})
// 用户配置的登录方式、是否打开调试模式
const loginTypes = config.getArray<string>('loginTypes');
const debug = config.getBoolean('debug') as boolean;
雪洛's avatar
雪洛 已提交
16 17

// #ifdef APP
DCloud_JSON's avatar
DCloud_JSON 已提交
18
import Univerify from '@/uni_modules/uni-id-pages-x/lib/Univerify.uts'
雪洛's avatar
雪洛 已提交
19
// #endif
DCloud_JSON's avatar
DCloud_JSON 已提交
20

DCloud_JSON's avatar
init  
DCloud_JSON 已提交
21 22 23 24 25
export default async function () {
  // 有打开调试模式的情况下
  if (debug) {
    // 1. 检查本地uni-id-pages中配置的登录方式,服务器端是否已经配置正确。否则提醒并引导去配置
    // 调用云对象,获取服务端已正确配置的登录方式
DCloud_JSON's avatar
DCloud_JSON 已提交
26 27
    uniIdCo.getSupportedLoginType().then(res=>{
      // console.log('7777res',res)
雪洛's avatar
雪洛 已提交
28
      let supportedLoginType = res.getArray('supportedLoginType')
DCloud_JSON's avatar
DCloud_JSON 已提交
29 30
      if(supportedLoginType == null){
        supportedLoginType = []
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
31
      }
DCloud_JSON's avatar
DCloud_JSON 已提交
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
      // 登录方式,服务端和客户端的映射关系
      const data:UTSJSONObject = {
        "smsCode": 'mobile-code',
        "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'
      };
      // 遍历客户端配置的登录方式,与服务端比对。并在错误时抛出错误提示
      const list = loginTypes?.filter((type:string):boolean =>{
        let currentType = data.getString(type);
        if(currentType == null){
          currentType = ""
        }
        return !(supportedLoginType.includes(currentType))
      })
      if (list?.length != 0) {
        console.error(
      		`错误:前端启用的登录方式:${list?.join(',')};没有在服务端完成配置。配置文件路径:"/uni_modules/uni-config-center/uniCloud/cloudfunctions/common/uni-config-center/uni-id/config.json"`
        )
      }
    })
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
62 63
  }

雪洛's avatar
雪洛 已提交
64
  // #ifdef APP
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
65
  // 如果uni-id-pages配置的登录功能有一键登录,有则执行预登录(异步)
DCloud_JSON's avatar
DCloud_JSON 已提交
66 67 68 69 70 71 72 73 74 75 76 77 78
  if (loginTypes != null && loginTypes.includes('univerify')) {
    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 已提交
79 80 81 82 83 84 85 86 87 88
    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 已提交
89 90 91 92
          keyValuePairs.forEach(keyValuePair => {
            let [key, value] = keyValuePair.split('='); // 将键值对按等号分隔为键和值
            param[key] = value;
          });
A
Anne_LXM 已提交
93 94
          if(typeof param["type"] == 'string'){
            type = param["type"] as string
DCloud_JSON's avatar
DCloud_JSON 已提交
95
          }
A
Anne_LXM 已提交
96 97 98 99 100 101 102
        }
        if(type == ''){
          type = loginTypes[0];
        }
        if(type == "univerify"){
          myUniverify.verify(true)
          throw new Error('第一优先级是一键登录(且可用),就直接调用一键登录,不打开登录页面')
DCloud_JSON's avatar
DCloud_JSON 已提交
103 104
        }
      }
A
Anne_LXM 已提交
105 106 107 108 109 110 111 112 113 114 115
    }

    uni.addInterceptor('navigateTo',{
      invoke:(e:NavigateToOptions)=>{
        handleInterceptor(e.url)
      }
    })
    uni.addInterceptor('redirectTo',{
      invoke:(e:RedirectToOptions)=>{
        handleInterceptor(e.url)
      }
DCloud_JSON's avatar
DCloud_JSON 已提交
116 117
    })

A
Anne_LXM 已提交
118 119
  }

DCloud_JSON's avatar
init  
DCloud_JSON 已提交
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
  // #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错误事件
  // // db.off('error', onDBError)


137 138
  // needLogin相关代码-start(此代码仅为版本兼容提示使用,如已知晓可删除)
  const needLogin = config.getArray<string>('needLogin')
雪洛's avatar
雪洛 已提交
139
  const uniCompileVersionCode = uni.getSystemInfoSync().uniCompileVersionCode as number
140 141 142 143 144 145 146 147 148 149 150 151
  if(needLogin != null && (uniCompileVersionCode > 3.99 || uniCompileVersionCode == 3.99) ){
    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 已提交
152
      }
153 154 155
      if (needLogin != null) {
        return needLogin.every((item:string):boolean => {
          return item == url || new RegExp(item).test(url)
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
156
        })
157 158
      }else{
        return false
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
159 160
      }
    }
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
    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

DCloud_JSON's avatar
init  
DCloud_JSON 已提交
186
}