zhaojs
2023-05-24 92514beb315f5778df2849341dcffb3bb257160c
no message
已添加14个文件
已修改9个文件
640 ■■■■■ 文件已修改
uniapp/.hbuilderx/launch.json 30 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
uniapp/components/colGoods.vue 14 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
uniapp/components/rowGoods.vue 4 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
uniapp/manifest.json 7 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
uniapp/pages.json 14 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
uniapp/pages/index/index.vue 15 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
uniapp/pages/login/setInviteCode.vue 7 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
uniapp/pages/login/wxlogin.vue 105 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
uniapp/pages/rankinglist/xianbao.vue 71 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
uniapp/pages/search/searchResult.vue 1 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
uniapp/uniCloud-aliyun/cloudfunctions/getPhoneNumber/getPhoneNumber.param.json 4 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
uniapp/uniCloud-aliyun/cloudfunctions/getPhoneNumber/index.js 35 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
uniapp/uniCloud-aliyun/cloudfunctions/getPhoneNumber/package.json 7 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
uniapp/uni_modules/uni-config-center/changelog.md 6 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
uniapp/uni_modules/uni-config-center/package.json 81 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
uniapp/uni_modules/uni-config-center/readme.md 93 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
uniapp/uni_modules/uni-config-center/uniCloud/cloudfunctions/common/uni-config-center/index.js 1 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
uniapp/uni_modules/uni-config-center/uniCloud/cloudfunctions/common/uni-config-center/package.json 9 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
uniapp/uni_modules/uni-id-common/changelog.md 32 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
uniapp/uni_modules/uni-id-common/package.json 84 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
uniapp/uni_modules/uni-id-common/readme.md 3 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
uniapp/uni_modules/uni-id-common/uniCloud/cloudfunctions/common/uni-id-common/index.js 1 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
uniapp/uni_modules/uni-id-common/uniCloud/cloudfunctions/common/uni-id-common/package.json 16 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
uniapp/.hbuilderx/launch.json
@@ -4,19 +4,23 @@
    "version" : "0.0",
    "configurations" : [
        {
            "app-plus" : {
                "launchtype" : "local"
            },
            "default" : {
                "launchtype" : "local"
            },
            "h5" : {
                "launchtype" : "local"
            },
            "mp-weixin" : {
                "launchtype" : "local"
            },
            "type" : "uniCloud"
            "app-plus" :
            {
                "launchtype" : "remote"
            },
            "default" :
            {
                "launchtype" : "local"
            },
            "h5" :
            {
                "launchtype" : "local"
            },
            "mp-weixin" :
            {
                "launchtype" : "local"
            },
            "type" : "uniCloud"
        },
        {
            "openVueDevtools" : true,
uniapp/components/colGoods.vue
@@ -41,7 +41,12 @@
                    <view class="saleNum-box" v-if="items.monthSales!=''">
                        å·²å”®{{items.monthSales}}
                    </view>
                    <!-- <view class="saleNum-box" v-if="items.shopName!=''">
                        åº—铺:{{items.shopName}}
                    </view> -->
                </view>
                <view class="shopname">{{items.shopName}}</view>
            </view>
        </view>
    </view>
@@ -61,6 +66,15 @@
</script>
<style lang="scss">
    .shopname{
            font-size: 11px;
            display: flex;
            align-items: flex-start;
            width: 100%;
            color: #999999;
            margin: 2px 0;
    }
    .items-container {
        width: 346rpx;
        height: 100%;
uniapp/components/rowGoods.vue
@@ -36,7 +36,9 @@
                <view class="saleNum-content" v-if="items.monthSales!=''">
                    å·²å”®{{items.monthSales}}
                </view>
    <view class="saleNum-content" v-if="items.shopName!=''">
        {{items.shopName}}
    </view>
                <view class="shopEnter-bar rowCen">
                    <!-- <view class="storename">
                        {{items.shopName}}
uniapp/manifest.json
@@ -2,8 +2,8 @@
    "name" : "大返官",
    "appid" : "__UNI__FC8858A",
    "description" : "大返官app",
    "versionName" : "1.1.0",
    "versionCode" : 110,
    "versionName" : "1.1.1",
    "versionCode" : 111,
    "transformPx" : false,
    /* 5+App特有相关 */
    "app-plus" : {
@@ -98,7 +98,8 @@
                        "appid" : "wx275c371de3f6791e",
                        "appsecret" : "68af726473c8ee8c42d6a29fc0014fe4",
                        "UniversalLinks" : "https://verification.ushopvip.com/uni-universallinks/__UNI__FC8858A/"
                    }
                    },
                    "univerify" : {}
                },
                "maps" : {
                    "amap" : {
uniapp/pages.json
@@ -457,6 +457,16 @@
                }
            }
        },
        // çº¿æŠ¥
        {
            "path": "pages/rankinglist/xianbao",
            "style": {
                "navigationStyle": "custom",
                "app-plus": {
                    "titleNView": false
                }
            }
        },
        // è¶…级分类
        /* {
            "path": "pages/classify/classify",
@@ -867,10 +877,10 @@
                "text": "疯抢榜"
            },
            {
                "pagePath": "pages/find/find",
                "pagePath": "pages/rankinglist/xianbao",
                "iconPath": "static/images/tabBar/find.png",
                "selectedIconPath": "static/images/tabBar/findactive.png",
                "text": "逛逛"
                "text": "线报"
            },
            {
                "pagePath": "pages/community/community",
uniapp/pages/index/index.vue
@@ -122,13 +122,17 @@
            }
        },
        onLoad() {
            this.getCategoryList();
            this.getPopBannerInfo();
        },
        onShow() {
            if(!this.hasLogin){
                setTimeout(function(){
                    
                    uni.reLaunch({
                        url:"/pages/login/wxlogin"
                    })
                },3000);
                },1000);
                return;
            }
            var user= uni.getStorageSync('userInfo');
@@ -139,16 +143,9 @@
                    uni.reLaunch({
                        url:"/pages/login/wxlogin"
                    })
                },3000);
                },1000);
                return;
            }
            else
            {
                this.getCategoryList();
                this.getPopBannerInfo();
            }
        },
        onShow() {
            if(this.categoryList){
                this.getCategoryList();
            }
uniapp/pages/login/setInviteCode.vue
@@ -76,8 +76,11 @@
                    confirmText:'联系推荐人',
                    success:function(res)
                    {
                        that.isShowCode=res.cancel;
                        console.log(that.isShowCode)
                        if (res.confirm) {
                            that.isShowCode=true;
                        } else if (res.cancel) {
                            that.isShowCode=false;
                        }
                    }
                });
            },
uniapp/pages/login/wxlogin.vue
@@ -8,9 +8,16 @@
                <image class="logoIcon" src="../../static/images/mine/wxwhite.png" mode=""></image>
                <view>微信一键登录</view>
            </view>
            <view class="goaccount rowCenCen" @tap="goaccount()">
            <view v-if="isSupportMob" class="goaccount rowCenCen" @tap="mobileLogin()">
                <view>本机手机号一键登录/注册</view>
            </view>
            <view v-else class="goaccount rowCenCen" @tap="goaccount()">
                <view>手机号登录/注册</view>
            </view>
            <view style="margin-top: 20px;" v-if="isother"  @tap="goaccount()">
                æ‰‹æœºå·ç™»å½•/注册
            </view>
        </view>
        <view class="bottom-fixed colCen">
@@ -28,6 +35,7 @@
        mapMutations
    } from 'vuex';
    import titleBar from '../../components/backTitlebar.vue'
    const univerifyManager = uni.getUniverifyManager();
    export default {
        components: {
            titleBar
@@ -37,7 +45,9 @@
                appInfo: '',
                ifPasslogin: false,
                isread: false,
                haswxlogin: false
                haswxlogin: false,
                isSupportMob:false,
                isother:false
            }
        },
        onLoad() {
@@ -46,6 +56,7 @@
            console.log(getApp().globalData.ifwt)
            //this.haswxlogin = this.appInfo.iosExamine ? false : (getApp().globalData.ifwt == 1 ? true : false)
            this.haswxlogin = getApp().globalData.ifwt == 1 ? true :false;
            this.isSupportMoblie();
        },
        methods: {
            ...mapMutations(['login']),
@@ -62,6 +73,96 @@
                    })
                }
            },
            isSupportMoblie()
            {
                var that=this;
                uni.preLogin({
                    provider: 'univerify',
                    success(){  //预登录成功
                        // æ˜¾ç¤ºä¸€é”®ç™»å½•选项
                        that.isSupportMob=true;
                    },
                    fail(res){  // é¢„登录失败
                        // ä¸æ˜¾ç¤ºä¸€é”®ç™»å½•选项(或置灰)
                    // æ ¹æ®é”™è¯¯ä¿¡æ¯åˆ¤æ–­å¤±è´¥åŽŸå› ï¼Œå¦‚æœ‰éœ€è¦å¯å°†é”™è¯¯æäº¤ç»™ç»Ÿè®¡æœåŠ¡å™¨
                        console.log(res)
                        console.log(res.errMsg)
                    }
                })
            },
            doMobileLogin(mobRes)
            {
                var that=this;
                uniCloud.callFunction({
                  name: 'getPhoneNumber', // ä½ çš„云函数名称
                  data: {
                    'access_token': mobRes.access_token, // å®¢æˆ·ç«¯ä¸€é”®ç™»å½•接口返回的access_token
                    'openid': mobRes.openid // å®¢æˆ·ç«¯ä¸€é”®ç™»å½•接口返回的openid
                  }
                }).then(res => {
                    console.log(res)
                    that.targetToIndex(res.result.data);
                  // ç™»å½•成功,可以关闭一键登录授权界面了
                  univerifyManager.close();
                }).catch(err=>{
                    // å¤„理错误
                    console.log(err)
                    uni.hideLoading();
                    that.$alert('获取手机号码失败,请使用其他方式登录')
                    setTimeout(function(){
                        univerifyManager.close();
                    },2000);
                })
            },
            mobileLogin()
            {
                var that=this;
                if (this.isread) {
                    univerifyManager.login({
                        provider: 'univerify',
                        univerifyStyle: { // è‡ªå®šä¹‰ç™»å½•框样式
                        "fullScreen":false,
                        "authButton":
                        {
                            "normalColor":"#F73314",
                            "highlightColor":"#F73314"
                        }
                      },
                    success(res){ // ç™»å½•成功
                        console.log(res.authResult);
                        that.doMobileLogin(res.authResult);
                        },
                        fail(res){  // ç™»å½•失败
                        console.log(res)
                            if(res.errCode==30002)
                            {//切换登录方式
                                that.isother=true;
                            }
                            else
                            {
                                that.$alert('获取手机号码失败,请使用其他方式登录')
                                setTimeout(function(){
                                    univerifyManager.close();
                                },2000);
                            }
                            that.isother=true;
                        }
                    })
                    }
                    else
                    {
                        uni.showToast({
                            title: '请先阅读并同意《用户协议》和《隐私协议》',
                            icon: "none",
                        })
                    }
            },
            targetToIndex(e)
            {
                var that = this;
uniapp/pages/rankinglist/xianbao.vue
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,71 @@
<template>
    <view>
        <web-view :webview-styles="webviewStyles" :src="webviewUrl" @message='received'></web-view>
    </view>
</template>
<script>
    //var wv
    export default {
        data() {
            return {
                webviewUrl: '',
                webviewStyles: {
                    progress: {
                        color: '#EE1B14'
                    }
                },
            }
        },
        onLoad(options) {
            if(!this.hasLogin){
                uni.reLaunch({
                    url:"/pages/login/wxlogin"
                })
            }
            else{
                const value = uni.getStorageSync('userInfo');
                this.webviewUrl = encodeURI('http://dfgapp.ushopvip.com/html/xianbao.html?token='+value.token);
            }
        },
        onReady() {
          this.clearMuiBack();
        },
        methods: {
            received(e) {
                console.log(e.detail.data[0].type)
                if(e.detail.data[0].type=='getToken'){
                    const token = uni.getStorageSync('userInfo').token;
                    var currentWebview = this.$scope.$getAppWebview()
                    var wv = currentWebview.children()[0]
                    wv.evalJS('localStorage.setItem("ZZTOKEN",' + JSON.stringify(token) + ')');
                }
            },
            // å…³é—­mui返回
              clearMuiBack() {
                // #ifdef APP-PLUS
                var currentWebview = this.$scope.$getAppWebview().children()[0];
                //监听注入的js
                currentWebview.addEventListener("loaded", function() {
                  currentWebview.evalJS("mui.init({keyEventBind: {backbutton: false }});");
                });
                // #endif
              },
        },
        onNavigationBarButtonTap(e) {
            // #ifdef APP-PLUS
            const currentWebview = this.$scope.$getAppWebview(); //此对象相当于html5plus里的plus.webview.currentWebview()。在uni-app里vue页面直接使用plus.webview.currentWebview()无效,非v3编译模式使用this.$mp.page.$getAppWebview()
            var wv = currentWebview.children()[0]
            wv.reload();
            // #endif
            console.log(JSON.stringify(e))
        },
    }
</script>
<style>
</style>
uniapp/pages/search/searchResult.vue
@@ -264,6 +264,7 @@
                }).then(e => {
                    if (e.code != 0) return that.$alert(e.msg)
                    uni.stopPullDownRefresh();
                    console.log(e.data)
                    var res = e.data;
                    if (res.list.length < 10) {
                        that.canloadmore = false
uniapp/uniCloud-aliyun/cloudfunctions/getPhoneNumber/getPhoneNumber.param.json
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,4 @@
// æœ¬æ–‡ä»¶ä¸­çš„json内容将在云函数【运行】时作为参数传给云函数。
// é…ç½®æ•™ç¨‹å‚考:https://uniapp.dcloud.net.cn/uniCloud/rundebug.html#runparam
{
}
uniapp/uniCloud-aliyun/cloudfunctions/getPhoneNumber/index.js
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,35 @@
'use strict';
exports.main = async (event, context) => {
    // event里包含着客户端提交的参数
      const res = await uniCloud.getPhoneNumber({
          appid: '__UNI__FC8858A', // æ›¿æ¢æˆè‡ªå·±å¼€é€šä¸€é”®ç™»å½•的应用的DCloud appid
          provider: 'univerify',
          apiKey: 'df2247e74aa8dae4f9f26e7bbd3d2cc5', // åœ¨å¼€å‘者中心开通服务并获取apiKey
          apiSecret: '6dbc847c9605c8bb5ed8a9afa4e72ceb', // åœ¨å¼€å‘者中心开通服务并获取apiSecret
          access_token: event.access_token,
          openid: event.openid
      })
      if(!res.success)
      {
          return {
              code:-1,
              msg:'获取手机号失败'
          }
      }
      var apiUrl='http://dfgapp.ushopvip.com/api/user/mobilelogin';
      const apiRes = await uniCloud.httpclient.request(apiUrl, {
          method: 'POST',
          data: {
            mobile: res.phoneNumber,
            captcha:'000',
            ismobouth:true
          },
          contentType: 'json', // æŒ‡å®šä»¥application/json发送data内的数据
          dataType: 'json' // æŒ‡å®šè¿”回值为json格式,自动进行parse
        })
      //console.log(res); // res里包含手机号
      // æ‰§è¡Œç”¨æˆ·ä¿¡æ¯å…¥åº“等操作,正常情况下不要把完整手机号返回给前端
      // å¦‚果数据库在uniCloud上,可以直接入库
      // å¦‚果数据库不在uniCloud上,可以通过 uniCloud.httpclient API,将手机号通过http方式传递给其他服务器的接口,详见:https://uniapp.dcloud.net.cn/uniCloud/cf-functions?id=httpclient
      return apiRes
};
uniapp/uniCloud-aliyun/cloudfunctions/getPhoneNumber/package.json
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,7 @@
{
  "name": "getPhoneNumber",
  "dependencies": {},
  "extensions": {
    "uni-cloud-jql": {}
  }
}
uniapp/uni_modules/uni-config-center/changelog.md
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,6 @@
## 0.0.3(2022-11-11)
- ä¿®å¤ config æ–¹æ³•获取根节点为数组格式配置时错误的转化为了对象的Bug
## 0.0.2(2021-04-16)
- ä¿®æ”¹æ’ä»¶package信息
## 0.0.1(2021-03-15)
- åˆå§‹åŒ–项目
uniapp/uni_modules/uni-config-center/package.json
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,81 @@
{
  "id": "uni-config-center",
  "displayName": "uni-config-center",
  "version": "0.0.3",
  "description": "uniCloud é…ç½®ä¸­å¿ƒ",
  "keywords": [
    "配置",
    "配置中心"
],
  "repository": "",
  "engines": {
    "HBuilderX": "^3.1.0"
  },
"dcloudext": {
    "sale": {
      "regular": {
        "price": "0.00"
      },
      "sourcecode": {
        "price": "0.00"
      }
    },
    "contact": {
      "qq": ""
    },
    "declaration": {
      "ads": "无",
      "data": "无",
      "permissions": "无"
    },
    "npmurl": "",
    "type": "unicloud-template-function"
  },
  "directories": {
    "example": "../../../scripts/dist"
  },
  "uni_modules": {
    "dependencies": [],
    "encrypt": [],
    "platforms": {
      "cloud": {
        "tcb": "y",
        "aliyun": "y"
      },
      "client": {
        "App": {
          "app-vue": "u",
          "app-nvue": "u"
        },
        "H5-mobile": {
          "Safari": "u",
          "Android Browser": "u",
          "微信浏览器(Android)": "u",
          "QQ浏览器(Android)": "u"
        },
        "H5-pc": {
          "Chrome": "u",
          "IE": "u",
          "Edge": "u",
          "Firefox": "u",
          "Safari": "u"
        },
        "小程序": {
          "微信": "u",
          "阿里": "u",
          "百度": "u",
          "字节跳动": "u",
          "QQ": "u"
        },
        "快应用": {
          "华为": "u",
          "联盟": "u"
        },
        "Vue": {
            "vue2": "y",
            "vue3": "u"
        }
      }
    }
  }
}
uniapp/uni_modules/uni-config-center/readme.md
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,93 @@
# ä¸ºä»€ä¹ˆä½¿ç”¨uni-config-center
实际开发中很多插件需要配置文件才可以正常运行,如果每个插件都单独进行配置的话就会产生下面这样的目录结构
```bash
cloudfunctions
└─────common å…¬å…±æ¨¡å—
        â”œâ”€plugin-a // æ’ä»¶A对应的目录
        â”‚  â”œâ”€index.js
        â”‚  â”œâ”€config.json // plugin-a对应的配置文件
        â”‚  â””─other-file.cert  // plugin-a依赖的其他文件
        â””─plugin-b // plugin-b对应的目录
           â”œâ”€index.js
           â””─config.json // plugin-b对应的配置文件
```
假设插件作者要发布一个项目模板,里面使用了很多需要配置的插件,无论是作者发布还是用户使用都是一个大麻烦。
uni-config-center就是用了统一管理这些配置文件的,使用uni-config-center后的目录结构如下
```bash
cloudfunctions
└─────common å…¬å…±æ¨¡å—
        â”œâ”€plugin-a // æ’ä»¶A对应的目录
        â”‚  â””─index.js
        â”œâ”€plugin-b // plugin-b对应的目录
        â”‚  â””─index.js
        â””─uni-config-center
           â”œâ”€index.js // config-center入口文件
           â”œâ”€plugin-a
           â”‚  â”œâ”€config.json  // plugin-a对应的配置文件
           â”‚  â””─other-file.cert  // plugin-a依赖的其他文件
           â””─plugin-b
              â””─config.json  // plugin-b对应的配置文件
```
使用uni-config-center后的优势
- é…ç½®æ–‡ä»¶ç»Ÿä¸€ç®¡ç†ï¼Œåˆ†ç¦»æ’件主体和配置信息,更新插件更方便
- æ”¯æŒå¯¹config.json设置schema,插件使用者在HBuilderX内编写config.json文件时会有更好的提示(后续HBuilderX会提供支持)
# ç”¨æ³•
在要使用uni-config-center的公共模块或云函数内引入uni-config-center依赖,请参考:[使用公共模块](https://uniapp.dcloud.net.cn/uniCloud/cf-common)
```js
const createConfig = require('uni-config-center')
const uniIdConfig = createConfig({
    pluginId: 'uni-id', // æ’ä»¶id
    defaultConfig: { // é»˜è®¤é…ç½®
        tokenExpiresIn: 7200,
        tokenExpiresThreshold: 600,
    },
    customMerge: function(defaultConfig, userConfig) { // è‡ªå®šä¹‰é»˜è®¤é…ç½®å’Œç”¨æˆ·é…ç½®çš„合并规则,不设置的情况侠会对默认配置和用户配置进行深度合并
        // defaudltConfig é»˜è®¤é…ç½®
        // userConfig ç”¨æˆ·é…ç½®
        return Object.assign(defaultConfig, userConfig)
    }
})
// ä»¥å¦‚下配置为例
// {
//   "tokenExpiresIn": 7200,
//   "passwordErrorLimit": 6,
//   "bindTokenToDevice": false,
//   "passwordErrorRetryTime": 3600,
//   "app-plus": {
//     "tokenExpiresIn": 2592000
//   },
//   "service": {
//     "sms": {
//       "codeExpiresIn": 300
//     }
//   }
// }
// èŽ·å–é…ç½®
uniIdConfig.config() // èŽ·å–å…¨éƒ¨é…ç½®ï¼Œæ³¨æ„ï¼šuni-config-center内不存在对应插件目录时会返回空对象
uniIdConfig.config('tokenExpiresIn') // æŒ‡å®šé”®å€¼èŽ·å–é…ç½®ï¼Œè¿”å›žï¼š7200
uniIdConfig.config('service.sms.codeExpiresIn') // æŒ‡å®šé”®å€¼èŽ·å–é…ç½®ï¼Œè¿”å›žï¼š300
uniIdConfig.config('tokenExpiresThreshold', 600) // æŒ‡å®šé”®å€¼èŽ·å–é…ç½®ï¼Œå¦‚æžœä¸å­˜åœ¨åˆ™å–ä¼ å…¥çš„é»˜è®¤å€¼ï¼Œè¿”å›žï¼š600
// èŽ·å–æ–‡ä»¶ç»å¯¹è·¯å¾„
uniIdConfig.resolve('custom-token.js') // èŽ·å–uni-config-center/uni-id/custom-token.js文件的路径
// å¼•用文件(require)
uniIDConfig.requireFile('custom-token.js') // ä½¿ç”¨require方式引用uni-config-center/uni-id/custom-token.js文件。文件不存在时返回undefined,文件内有其他错误导致require失败时会抛出错误。
// åˆ¤æ–­æ˜¯å¦åŒ…含某文件
uniIDConfig.hasFile('custom-token.js') // é…ç½®ç›®å½•是否包含某文件,true: æ–‡ä»¶å­˜åœ¨ï¼Œfalse: æ–‡ä»¶ä¸å­˜åœ¨
```
uniapp/uni_modules/uni-config-center/uniCloud/cloudfunctions/common/uni-config-center/index.js
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1 @@
"use strict";var t=require("fs"),r=require("path");function e(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var n=e(t),o=e(r),i="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var u=function(t){var r={exports:{}};return t(r,r.exports),r.exports}((function(t,r){var e="__lodash_hash_undefined__",n=9007199254740991,o="[object Arguments]",u="[object Function]",c="[object Object]",a=/^\[object .+?Constructor\]$/,f=/^(?:0|[1-9]\d*)$/,s={};s["[object Float32Array]"]=s["[object Float64Array]"]=s["[object Int8Array]"]=s["[object Int16Array]"]=s["[object Int32Array]"]=s["[object Uint8Array]"]=s["[object Uint8ClampedArray]"]=s["[object Uint16Array]"]=s["[object Uint32Array]"]=!0,s[o]=s["[object Array]"]=s["[object ArrayBuffer]"]=s["[object Boolean]"]=s["[object DataView]"]=s["[object Date]"]=s["[object Error]"]=s[u]=s["[object Map]"]=s["[object Number]"]=s[c]=s["[object RegExp]"]=s["[object Set]"]=s["[object String]"]=s["[object WeakMap]"]=!1;var l="object"==typeof i&&i&&i.Object===Object&&i,h="object"==typeof self&&self&&self.Object===Object&&self,p=l||h||Function("return this")(),_=r&&!r.nodeType&&r,v=_&&t&&!t.nodeType&&t,d=v&&v.exports===_,y=d&&l.process,g=function(){try{var t=v&&v.require&&v.require("util").types;return t||y&&y.binding&&y.binding("util")}catch(t){}}(),b=g&&g.isTypedArray;function j(t,r,e){switch(e.length){case 0:return t.call(r);case 1:return t.call(r,e[0]);case 2:return t.call(r,e[0],e[1]);case 3:return t.call(r,e[0],e[1],e[2])}return t.apply(r,e)}var w,O,m,A=Array.prototype,z=Function.prototype,M=Object.prototype,x=p["__core-js_shared__"],C=z.toString,F=M.hasOwnProperty,U=(w=/[^.]+$/.exec(x&&x.keys&&x.keys.IE_PROTO||""))?"Symbol(src)_1."+w:"",S=M.toString,I=C.call(Object),P=RegExp("^"+C.call(F).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),T=d?p.Buffer:void 0,q=p.Symbol,E=p.Uint8Array,$=T?T.allocUnsafe:void 0,D=(O=Object.getPrototypeOf,m=Object,function(t){return O(m(t))}),k=Object.create,B=M.propertyIsEnumerable,N=A.splice,L=q?q.toStringTag:void 0,R=function(){try{var t=vt(Object,"defineProperty");return t({},"",{}),t}catch(t){}}(),G=T?T.isBuffer:void 0,V=Math.max,W=Date.now,H=vt(p,"Map"),J=vt(Object,"create"),K=function(){function t(){}return function(r){if(!xt(r))return{};if(k)return k(r);t.prototype=r;var e=new t;return t.prototype=void 0,e}}();function Q(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r<e;){var n=t[r];this.set(n[0],n[1])}}function X(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r<e;){var n=t[r];this.set(n[0],n[1])}}function Y(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r<e;){var n=t[r];this.set(n[0],n[1])}}function Z(t){var r=this.__data__=new X(t);this.size=r.size}function tt(t,r){var e=Ot(t),n=!e&&wt(t),o=!e&&!n&&At(t),i=!e&&!n&&!o&&Ft(t),u=e||n||o||i,c=u?function(t,r){for(var e=-1,n=Array(t);++e<t;)n[e]=r(e);return n}(t.length,String):[],a=c.length;for(var f in t)!r&&!F.call(t,f)||u&&("length"==f||o&&("offset"==f||"parent"==f)||i&&("buffer"==f||"byteLength"==f||"byteOffset"==f)||dt(f,a))||c.push(f);return c}function rt(t,r,e){(void 0!==e&&!jt(t[r],e)||void 0===e&&!(r in t))&&ot(t,r,e)}function et(t,r,e){var n=t[r];F.call(t,r)&&jt(n,e)&&(void 0!==e||r in t)||ot(t,r,e)}function nt(t,r){for(var e=t.length;e--;)if(jt(t[e][0],r))return e;return-1}function ot(t,r,e){"__proto__"==r&&R?R(t,r,{configurable:!0,enumerable:!0,value:e,writable:!0}):t[r]=e}Q.prototype.clear=function(){this.__data__=J?J(null):{},this.size=0},Q.prototype.delete=function(t){var r=this.has(t)&&delete this.__data__[t];return this.size-=r?1:0,r},Q.prototype.get=function(t){var r=this.__data__;if(J){var n=r[t];return n===e?void 0:n}return F.call(r,t)?r[t]:void 0},Q.prototype.has=function(t){var r=this.__data__;return J?void 0!==r[t]:F.call(r,t)},Q.prototype.set=function(t,r){var n=this.__data__;return this.size+=this.has(t)?0:1,n[t]=J&&void 0===r?e:r,this},X.prototype.clear=function(){this.__data__=[],this.size=0},X.prototype.delete=function(t){var r=this.__data__,e=nt(r,t);return!(e<0)&&(e==r.length-1?r.pop():N.call(r,e,1),--this.size,!0)},X.prototype.get=function(t){var r=this.__data__,e=nt(r,t);return e<0?void 0:r[e][1]},X.prototype.has=function(t){return nt(this.__data__,t)>-1},X.prototype.set=function(t,r){var e=this.__data__,n=nt(e,t);return n<0?(++this.size,e.push([t,r])):e[n][1]=r,this},Y.prototype.clear=function(){this.size=0,this.__data__={hash:new Q,map:new(H||X),string:new Q}},Y.prototype.delete=function(t){var r=_t(this,t).delete(t);return this.size-=r?1:0,r},Y.prototype.get=function(t){return _t(this,t).get(t)},Y.prototype.has=function(t){return _t(this,t).has(t)},Y.prototype.set=function(t,r){var e=_t(this,t),n=e.size;return e.set(t,r),this.size+=e.size==n?0:1,this},Z.prototype.clear=function(){this.__data__=new X,this.size=0},Z.prototype.delete=function(t){var r=this.__data__,e=r.delete(t);return this.size=r.size,e},Z.prototype.get=function(t){return this.__data__.get(t)},Z.prototype.has=function(t){return this.__data__.has(t)},Z.prototype.set=function(t,r){var e=this.__data__;if(e instanceof X){var n=e.__data__;if(!H||n.length<199)return n.push([t,r]),this.size=++e.size,this;e=this.__data__=new Y(n)}return e.set(t,r),this.size=e.size,this};var it,ut=function(t,r,e){for(var n=-1,o=Object(t),i=e(t),u=i.length;u--;){var c=i[it?u:++n];if(!1===r(o[c],c,o))break}return t};function ct(t){return null==t?void 0===t?"[object Undefined]":"[object Null]":L&&L in Object(t)?function(t){var r=F.call(t,L),e=t[L];try{t[L]=void 0;var n=!0}catch(t){}var o=S.call(t);n&&(r?t[L]=e:delete t[L]);return o}(t):function(t){return S.call(t)}(t)}function at(t){return Ct(t)&&ct(t)==o}function ft(t){return!(!xt(t)||function(t){return!!U&&U in t}(t))&&(zt(t)?P:a).test(function(t){if(null!=t){try{return C.call(t)}catch(t){}try{return t+""}catch(t){}}return""}(t))}function st(t){if(!xt(t))return function(t){var r=[];if(null!=t)for(var e in Object(t))r.push(e);return r}(t);var r=yt(t),e=[];for(var n in t)("constructor"!=n||!r&&F.call(t,n))&&e.push(n);return e}function lt(t,r,e,n,o){t!==r&&ut(r,(function(i,u){if(o||(o=new Z),xt(i))!function(t,r,e,n,o,i,u){var a=gt(t,e),f=gt(r,e),s=u.get(f);if(s)return void rt(t,e,s);var l=i?i(a,f,e+"",t,r,u):void 0,h=void 0===l;if(h){var p=Ot(f),_=!p&&At(f),v=!p&&!_&&Ft(f);l=f,p||_||v?Ot(a)?l=a:Ct(j=a)&&mt(j)?l=function(t,r){var e=-1,n=t.length;r||(r=Array(n));for(;++e<n;)r[e]=t[e];return r}(a):_?(h=!1,l=function(t,r){if(r)return t.slice();var e=t.length,n=$?$(e):new t.constructor(e);return t.copy(n),n}(f,!0)):v?(h=!1,d=f,y=!0?(g=d.buffer,b=new g.constructor(g.byteLength),new E(b).set(new E(g)),b):d.buffer,l=new d.constructor(y,d.byteOffset,d.length)):l=[]:function(t){if(!Ct(t)||ct(t)!=c)return!1;var r=D(t);if(null===r)return!0;var e=F.call(r,"constructor")&&r.constructor;return"function"==typeof e&&e instanceof e&&C.call(e)==I}(f)||wt(f)?(l=a,wt(a)?l=function(t){return function(t,r,e,n){var o=!e;e||(e={});var i=-1,u=r.length;for(;++i<u;){var c=r[i],a=n?n(e[c],t[c],c,e,t):void 0;void 0===a&&(a=t[c]),o?ot(e,c,a):et(e,c,a)}return e}(t,Ut(t))}(a):xt(a)&&!zt(a)||(l=function(t){return"function"!=typeof t.constructor||yt(t)?{}:K(D(t))}(f))):h=!1}var d,y,g,b;var j;h&&(u.set(f,l),o(l,f,n,i,u),u.delete(f));rt(t,e,l)}(t,r,u,e,lt,n,o);else{var a=n?n(gt(t,u),i,u+"",t,r,o):void 0;void 0===a&&(a=i),rt(t,u,a)}}),Ut)}function ht(t,r){return bt(function(t,r,e){return r=V(void 0===r?t.length-1:r,0),function(){for(var n=arguments,o=-1,i=V(n.length-r,0),u=Array(i);++o<i;)u[o]=n[r+o];o=-1;for(var c=Array(r+1);++o<r;)c[o]=n[o];return c[r]=e(u),j(t,this,c)}}(t,r,Pt),t+"")}var pt=R?function(t,r){return R(t,"toString",{configurable:!0,enumerable:!1,value:(e=r,function(){return e}),writable:!0});var e}:Pt;function _t(t,r){var e,n,o=t.__data__;return("string"==(n=typeof(e=r))||"number"==n||"symbol"==n||"boolean"==n?"__proto__"!==e:null===e)?o["string"==typeof r?"string":"hash"]:o.map}function vt(t,r){var e=function(t,r){return null==t?void 0:t[r]}(t,r);return ft(e)?e:void 0}function dt(t,r){var e=typeof t;return!!(r=null==r?n:r)&&("number"==e||"symbol"!=e&&f.test(t))&&t>-1&&t%1==0&&t<r}function yt(t){var r=t&&t.constructor;return t===("function"==typeof r&&r.prototype||M)}function gt(t,r){if(("constructor"!==r||"function"!=typeof t[r])&&"__proto__"!=r)return t[r]}var bt=function(t){var r=0,e=0;return function(){var n=W(),o=16-(n-e);if(e=n,o>0){if(++r>=800)return arguments[0]}else r=0;return t.apply(void 0,arguments)}}(pt);function jt(t,r){return t===r||t!=t&&r!=r}var wt=at(function(){return arguments}())?at:function(t){return Ct(t)&&F.call(t,"callee")&&!B.call(t,"callee")},Ot=Array.isArray;function mt(t){return null!=t&&Mt(t.length)&&!zt(t)}var At=G||function(){return!1};function zt(t){if(!xt(t))return!1;var r=ct(t);return r==u||"[object GeneratorFunction]"==r||"[object AsyncFunction]"==r||"[object Proxy]"==r}function Mt(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=n}function xt(t){var r=typeof t;return null!=t&&("object"==r||"function"==r)}function Ct(t){return null!=t&&"object"==typeof t}var Ft=b?function(t){return function(r){return t(r)}}(b):function(t){return Ct(t)&&Mt(t.length)&&!!s[ct(t)]};function Ut(t){return mt(t)?tt(t,!0):st(t)}var St,It=(St=function(t,r,e){lt(t,r,e)},ht((function(t,r){var e=-1,n=r.length,o=n>1?r[n-1]:void 0,i=n>2?r[2]:void 0;for(o=St.length>3&&"function"==typeof o?(n--,o):void 0,i&&function(t,r,e){if(!xt(e))return!1;var n=typeof r;return!!("number"==n?mt(e)&&dt(r,e.length):"string"==n&&r in e)&&jt(e[r],t)}(r[0],r[1],i)&&(o=n<3?void 0:o,n=1),t=Object(t);++e<n;){var u=r[e];u&&St(t,u,e,o)}return t})));function Pt(t){return t}t.exports=It}));const c=Object.prototype.hasOwnProperty,a=(t,r)=>c.call(t,r);class f{constructor({pluginId:t,defaultConfig:r={},customMerge:e,root:n}){this.pluginId=t,this.defaultConfig=r,this.pluginConfigPath=o.default.resolve(n||__dirname,t),this.customMerge=e,this._config=void 0}resolve(t){return o.default.resolve(this.pluginConfigPath,t)}hasFile(t){return n.default.existsSync(this.resolve(t))}requireFile(t){try{return require(this.resolve(t))}catch(t){if("MODULE_NOT_FOUND"===t.code)return;throw t}}_getUserConfig(){return this.requireFile("config.json")}config(t,r){if(!this._config){const t=this._getUserConfig();this._config=Array.isArray(t)?t:(this.customMerge||u)(this.defaultConfig,t)}let e=this._config;return t?function(t,r,e){if("number"==typeof r)return t[r];if("symbol"==typeof r)return a(t,r)?t[r]:e;const n="string"!=typeof(o=r)?o:o.split(".").reduce(((t,r)=>(r.split(/\[([^}]+)\]/g).forEach((r=>r&&t.push(r))),t)),[]);var o;let i=t;for(let t=0;t<n.length;t++){const r=n[t];if(!a(i,r))return e;i=i[r]}return i}(e,t,r):e}}const s=new class{constructor(){this._configMap=new Map}plugin({pluginId:t,defaultConfig:r,customMerge:e,root:n=__dirname,cache:o=!0}){if(this._configMap.has(t)&&o)return this._configMap.get(t);const i=new f({pluginId:t,defaultConfig:r,customMerge:e,root:n});return o&&this._configMap.set(t,i),i}};var l=s.plugin.bind(s);module.exports=l;
uniapp/uni_modules/uni-config-center/uniCloud/cloudfunctions/common/uni-config-center/package.json
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,9 @@
{
  "name": "uni-config-center",
  "version": "0.0.3",
  "description": "配置中心",
  "main": "index.js",
  "keywords": [],
  "author": "DCloud",
  "license": "Apache-2.0"
}
uniapp/uni_modules/uni-id-common/changelog.md
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,32 @@
## 1.0.16(2023-04-25)
- æ–°å¢žmaxTokenLength配置,用于限制数据库用户记录token数组的最大长度
## 1.0.15(2023-04-06)
- ä¿®å¤éƒ¨åˆ†è¯­è¨€å›½é™…化出错的Bug
## 1.0.14(2023-03-07)
- ä¿®å¤ admin用户包含其他角色时未包含在token的Bug
## 1.0.13(2022-07-21)
- ä¿®å¤ åˆ›å»ºtoken时未传角色权限信息生成的token不正确的bug
## 1.0.12(2022-07-15)
- æå‡ä¸Žæ—§ç‰ˆæœ¬uni-id的兼容性(补充读取配置文件时回退平台app-plus、h5),但是仍推荐使用新平台名进行配置(app、web)
## 1.0.11(2022-07-14)
- ä¿®å¤ éƒ¨åˆ†æƒ…况下报`read property 'reduce' of undefined`的错误
## 1.0.10(2022-07-11)
- å°†token存储在用户表的token字段内,与旧版本uni-id保持一致
## 1.0.9(2022-07-01)
- checkToken兼容token内未缓存角色权限的情况,此时将查库获取角色权限
## 1.0.8(2022-07-01)
- ä¿®å¤clientDB默认依赖时部分情况下获取不到uni-id配置的Bug
## 1.0.7(2022-06-30)
- ä¿®å¤config文件不合法时未抛出具体错误的Bug
## 1.0.6(2022-06-28)
- ç§»é™¤æ’件内的数据表schema
## 1.0.5(2022-06-27)
- ä¿®å¤ä½¿ç”¨å¤šåº”用配置时报`Cannot read property 'appId' of undefined`的Bug
## 1.0.4(2022-06-27)
- ä¿®å¤ä½¿ç”¨è‡ªå®šä¹‰token内容功能报错的Bug [详情](https://ask.dcloud.net.cn/question/147945)
## 1.0.2(2022-06-23)
- å¯¹é½æ—§ç‰ˆæœ¬uni-id默认配置
## 1.0.1(2022-06-22)
- è¡¥å……对uni-config-center的依赖
## 1.0.0(2022-06-21)
- æä¾›uni-id token创建、校验、刷新接口,简化旧版uni-id公共模块
uniapp/uni_modules/uni-id-common/package.json
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,84 @@
{
    "id": "uni-id-common",
    "displayName": "uni-id-common",
    "version": "1.0.16",
    "description": "包含uni-id token生成、校验、刷新功能的云函数公共模块",
    "keywords": [
        "uni-id-common",
        "uniCloud",
        "token",
        "权限"
    ],
    "repository": "https://gitcode.net/dcloud/uni-id-common",
    "engines": {
        "HBuilderX": "^3.1.0"
    },
    "dcloudext": {
        "sale": {
            "regular": {
                "price": "0.00"
            },
            "sourcecode": {
                "price": "0.00"
            }
        },
        "contact": {
            "qq": ""
        },
        "declaration": {
            "ads": "无",
            "data": "无",
            "permissions": "无"
        },
        "npmurl": "",
        "type": "unicloud-template-function"
    },
    "uni_modules": {
        "dependencies": ["uni-config-center"],
        "encrypt": [],
        "platforms": {
            "cloud": {
                "tcb": "y",
                "aliyun": "y"
            },
            "client": {
                "Vue": {
                    "vue2": "u",
                    "vue3": "u"
                },
                "App": {
                    "app-vue": "u",
                    "app-nvue": "u"
                },
                "H5-mobile": {
                    "Safari": "u",
                    "Android Browser": "u",
                    "微信浏览器(Android)": "u",
                    "QQ浏览器(Android)": "u"
                },
                "H5-pc": {
                    "Chrome": "u",
                    "IE": "u",
                    "Edge": "u",
                    "Firefox": "u",
                    "Safari": "u"
                },
                "小程序": {
                    "微信": "u",
                    "阿里": "u",
                    "百度": "u",
                    "字节跳动": "u",
                    "QQ": "u",
                    "钉钉": "u",
                    "快手": "u",
                    "飞书": "u",
                    "京东": "u"
                },
                "快应用": {
                    "华为": "u",
                    "联盟": "u"
                }
            }
        }
    }
}
uniapp/uni_modules/uni-id-common/readme.md
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,3 @@
# uni-id-common
文档请参考:[uni-id-common](https://uniapp.dcloud.net.cn/uniCloud/uni-id-common.html)
uniapp/uni_modules/uni-id-common/uniCloud/cloudfunctions/common/uni-id-common/index.js
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1 @@
"use strict";var e,t=(e=require("crypto"))&&"object"==typeof e&&"default"in e?e.default:e;const n={TOKEN_EXPIRED:"uni-id-token-expired",CHECK_TOKEN_FAILED:"uni-id-check-token-failed",PARAM_REQUIRED:"uni-id-param-required",ACCOUNT_EXISTS:"uni-id-account-exists",ACCOUNT_NOT_EXISTS:"uni-id-account-not-exists",ACCOUNT_CONFLICT:"uni-id-account-conflict",ACCOUNT_BANNED:"uni-id-account-banned",ACCOUNT_AUDITING:"uni-id-account-auditing",ACCOUNT_AUDIT_FAILED:"uni-id-account-audit-failed",ACCOUNT_CLOSED:"uni-id-account-closed"};function i(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}function r(e){if(!e)return;const t=e.match(/^(\d+).(\d+).(\d+)/);return t?t.slice(1,4).map(e=>parseInt(e)):void 0}function o(e,t){const n=r(e),i=r(t);return n?i?function(e,t){const n=Math.max(e.length,t.length);for(let i=0;i<n;i++){const n=e[i],r=t[i];if(n>r)return 1;if(n<r)return-1}return 0}(n,i):1:i?-1:0}const s={"uni-id-token-expired":30203,"uni-id-check-token-failed":30202};function c(e){const{errCode:t,errMsgValue:n}=e;e.errMsg=this._t(t,n),t in s&&(e.code=s[t]),delete e.errMsgValue}function a(e){return"object"===(i=e,Object.prototype.toString.call(i).slice(8,-1).toLowerCase())&&e.errCode&&(t=e.errCode,Object.values(n).includes(t))&&!!e.errCode;var t,i}let u={"zh-Hans":{"uni-id-token-expired":"登录状态失效,token已过期","uni-id-check-token-failed":"token校验未通过","uni-id-param-required":"缺少参数: {param}","uni-id-account-exists":"此账号已注册","uni-id-account-not-exists":"此账号未注册","uni-id-account-conflict":"用户账号冲突","uni-id-account-banned":"从账号已封禁","uni-id-account-auditing":"此账号正在审核中","uni-id-account-audit-failed":"此账号审核失败","uni-id-account-closed":"此账号已注销"},en:{"uni-id-token-expired":"The login status is invalid, token has expired","uni-id-check-token-failed":"Check token failed","uni-id-param-required":"Parameter required: {param}","uni-id-account-exists":"Account exists","uni-id-account-not-exists":"Account does not exists","uni-id-account-conflict":"User account conflict","uni-id-account-banned":"Account has been banned","uni-id-account-auditing":"Account audit in progress","uni-id-account-audit-failed":"Account audit failed","uni-id-account-closed":"Account has been closed"}};try{const e=require.resolve("uni-config-center/uni-id/lang/index.js");u=function(e,t){const n=Object.keys(e);n.push(...Object.keys(t));const i={};for(let r=0;r<n.length;r++){const o=n[r];i[o]=Object.assign({},e[o],t[o])}return i}(u,require(e))}catch(e){}var d=u;function l(e){return e.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function h(e){return JSON.parse((t=function(e){var t=4-(e=e.toString()).length%4;if(4!==t)for(var n=0;n<t;++n)e+="=";return e.replace(/-/g,"+").replace(/_/g,"/")}(e),Buffer.from(t,"base64").toString("utf-8")));var t}function f(e){return l((t=JSON.stringify(e),Buffer.from(t,"utf-8").toString("base64")));var t}function p(e,n){return l(t.createHmac("sha256",n).update(e).digest("base64"))}const k=function(e,t){if("string"!=typeof e)throw new Error("Invalid token");const n=e.split(".");if(3!==n.length)throw new Error("Invalid token");const[i,r,o]=n;if(p(i+"."+r,t)!==o)throw new Error("Invalid token");const s=h(i);if("HS256"!==s.alg||"JWT"!==s.typ)throw new Error("Invalid token");const c=h(r);if(1e3*c.exp<Date.now()){const e=new Error("Token expired");throw e.name="TokenExpiredError",e}return c},g=function(e,t,n={}){const{expiresIn:i}=n;if(!i)throw new Error("expiresIn is required");const r=parseInt(Date.now()/1e3),o={...e,iat:r,exp:r+n.expiresIn},s=f({alg:"HS256",typ:"JWT"})+"."+f(o);return s+"."+p(s,t)},I=uniCloud.database(),_=I.command,C=I.collection("uni-id-users"),T=I.collection("uni-id-roles");class m{constructor({uniId:e}={}){this.uid=null,this.userRecord=null,this.userPermission=null,this.oldToken=null,this.oldTokenPayload=null,this.uniId=e,this.config=this.uniId._getConfig(),this.clientInfo=this.uniId._clientInfo,this.checkConfig()}checkConfig(){const{tokenExpiresIn:e,tokenExpiresThreshold:t}=this.config;if(t>=e)throw new Error("Config error, tokenExpiresThreshold should be less than tokenExpiresIn");t>e/2&&console.warn(`Please check whether the tokenExpiresThreshold configuration is set too large, tokenExpiresThreshold: ${t}, tokenExpiresIn: ${e}`)}get customToken(){return this.uniId.interceptorMap.get("customToken")}isTokenInDb(e){return o(e,"1.0.10")>=0}async getUserRecord(){if(this.userRecord)return this.userRecord;const e=await C.doc(this.uid).get();if(this.userRecord=e.data[0],!this.userRecord)throw{errCode:n.ACCOUNT_NOT_EXISTS};switch(this.userRecord.status){case void 0:case 0:break;case 1:throw{errCode:n.ACCOUNT_BANNED};case 2:throw{errCode:n.ACCOUNT_AUDITING};case 3:throw{errCode:n.ACCOUNT_AUDIT_FAILED};case 4:throw{errCode:n.ACCOUNT_CLOSED}}if(this.oldTokenPayload){if(this.isTokenInDb(this.oldTokenPayload.uniIdVersion)){if(-1===(this.userRecord.token||[]).indexOf(this.oldToken))throw{errCode:n.CHECK_TOKEN_FAILED}}if(this.userRecord.valid_token_date&&this.userRecord.valid_token_date>1e3*this.oldTokenPayload.iat)throw{errCode:n.TOKEN_EXPIRED}}return this.userRecord}async updateUserRecord(e){await C.doc(this.uid).update(e)}async getUserPermission(){if(this.userPermission)return this.userPermission;const e=(await this.getUserRecord()).role||[];if(0===e.length)return this.userPermission={role:[],permission:[]},this.userPermission;if(e.includes("admin"))return this.userPermission={role:e,permission:[]},this.userPermission;const t=await T.where({role_id:_.in(e)}).get(),n=(i=t.data.reduce((e,t)=>(t.permission&&e.push(...t.permission),e),[]),Array.from(new Set(i)));var i;return this.userPermission={role:e,permission:n},this.userPermission}async _createToken({uid:e,role:t,permission:i}={}){if(!t||!i){const e=await this.getUserPermission();t=e.role,i=e.permission}let r={uid:e,role:t,permission:i};if(this.uniId.interceptorMap.has("customToken")){const n=this.uniId.interceptorMap.get("customToken");if("function"!=typeof n)throw new Error("Invalid custom token file");r=await n({uid:e,role:t,permission:i})}const o=Date.now(),{tokenSecret:s,tokenExpiresIn:c,maxTokenLength:a=10}=this.config,u=g({...r,uniIdVersion:"1.0.16"},s,{expiresIn:c}),d=await this.getUserRecord(),l=(d.token||[]).filter(e=>{try{const t=this._checkToken(e);if(d.valid_token_date&&d.valid_token_date>1e3*t.iat)return!1}catch(e){if(e.errCode===n.TOKEN_EXPIRED)return!1}return!0});return l.push(u),l.length>a&&l.splice(0,l.length-a),await this.updateUserRecord({last_login_ip:this.clientInfo.clientIP,last_login_date:o,token:l}),{token:u,tokenExpired:o+1e3*c}}async createToken({uid:e,role:t,permission:i}={}){if(!e)throw{errCode:n.PARAM_REQUIRED,errMsgValue:{param:"uid"}};this.uid=e;const{token:r,tokenExpired:o}=await this._createToken({uid:e,role:t,permission:i});return{errCode:0,token:r,tokenExpired:o}}async refreshToken({token:e}={}){if(!e)throw{errCode:n.PARAM_REQUIRED,errMsgValue:{param:"token"}};this.oldToken=e;const t=this._checkToken(e);this.uid=t.uid,this.oldTokenPayload=t;const{uid:i}=t,{role:r,permission:o}=await this.getUserPermission(),{token:s,tokenExpired:c}=await this._createToken({uid:i,role:r,permission:o});return{errCode:0,token:s,tokenExpired:c}}_checkToken(e){const{tokenSecret:t}=this.config;let i;try{i=k(e,t)}catch(e){if("TokenExpiredError"===e.name)throw{errCode:n.TOKEN_EXPIRED};throw{errCode:n.CHECK_TOKEN_FAILED}}return i}async checkToken(e,{autoRefresh:t=!0}={}){if(!e)throw{errCode:n.PARAM_REQUIRED,errMsgValue:{param:"token"}};this.oldToken=e;const i=this._checkToken(e);this.uid=i.uid,this.oldTokenPayload=i;const{tokenExpiresThreshold:r}=this.config,{uid:o,role:s,permission:c}=i,a={role:s,permission:c};if(!s&&!c){const{role:e,permission:t}=await this.getUserPermission();a.role=e,a.permission=t}if(!r||!t){const e={code:0,errCode:0,...i,...a};return delete e.uniIdVersion,e}const u=Date.now();let d={};1e3*i.exp-u<1e3*r&&(d=await this._createToken({uid:o}));const l={code:0,errCode:0,...i,...a,...d};return delete l.uniIdVersion,l}}var E=Object.freeze({__proto__:null,checkToken:async function(e,{autoRefresh:t=!0}={}){return new m({uniId:this}).checkToken(e,{autoRefresh:t})},createToken:async function({uid:e,role:t,permission:n}={}){return new m({uniId:this}).createToken({uid:e,role:t,permission:n})},refreshToken:async function({token:e}={}){return new m({uniId:this}).refreshToken({token:e})}});const w=require("uni-config-center")({pluginId:"uni-id"});class x{constructor({context:e,clientInfo:t,config:n}={}){this._clientInfo=e?function(e){return{appId:e.APPID,platform:e.PLATFORM,locale:e.LOCALE,clientIP:e.CLIENTIP,deviceId:e.DEVICEID}}(e):t,this.config=n||this._getOriginConfig(),this.interceptorMap=new Map,w.hasFile("custom-token.js")&&this.setInterceptor("customToken",require(w.resolve("custom-token.js")));this._i18n=uniCloud.initI18n({locale:this._clientInfo.locale,fallbackLocale:"zh-Hans",messages:JSON.parse(JSON.stringify(d))}),d[this._i18n.locale]||this._i18n.setLocale("zh-Hans")}setInterceptor(e,t){this.interceptorMap.set(e,t)}_t(...e){return this._i18n.t(...e)}_parseOriginConfig(e){return Array.isArray(e)?e:e[0]?Object.values(e):e}_getOriginConfig(){if(w.hasFile("config.json")){let e;try{e=w.config()}catch(e){throw new Error("Invalid uni-id config file\n"+e.message)}return this._parseOriginConfig(e)}try{return this._parseOriginConfig(require("uni-id/config.json"))}catch(e){throw new Error("Invalid uni-id config file")}}_getAppConfig(){const e=this._getOriginConfig();return Array.isArray(e)?e.find(e=>e.dcloudAppid===this._clientInfo.appId)||e.find(e=>e.isDefaultConfig):e}_getPlatformConfig(){const e=this._getAppConfig();if(!e)throw new Error(`Config for current app (${this._clientInfo.appId}) was not found, please check your config file or client appId`);let t;switch("app-plus"===this._clientInfo.platform&&(this._clientInfo.platform="app"),"h5"===this._clientInfo.platform&&(this._clientInfo.platform="web"),this._clientInfo.platform){case"web":t="h5";break;case"app":t="app-plus"}const n=[{tokenExpiresIn:7200,tokenExpiresThreshold:1200,passwordErrorLimit:6,passwordErrorRetryTime:3600},e];t&&e[t]&&n.push(e[t]),n.push(e[this._clientInfo.platform]);const i=Object.assign(...n);return["tokenSecret","tokenExpiresIn"].forEach(e=>{if(!i||!i[e])throw new Error(`Config parameter missing, ${e} is required`)}),i}_getConfig(){return this._getPlatformConfig()}}for(const e in E)x.prototype[e]=E[e];function y(e){const t=new x(e);return new Proxy(t,{get(e,t){if(t in e&&0!==t.indexOf("_")){if("function"==typeof e[t])return(n=e[t],function(){let e;try{e=n.apply(this,arguments)}catch(e){if(a(e))return c.call(this,e),e;throw e}return i(e)?e.then(e=>(a(e)&&c.call(this,e),e),e=>{if(a(e))return c.call(this,e),e;throw e}):(a(e)&&c.call(this,e),e)}).bind(e);if("context"!==t&&"config"!==t)return e[t]}var n}})}x.prototype.createInstance=y;const A={createInstance:y};module.exports=A;
uniapp/uni_modules/uni-id-common/uniCloud/cloudfunctions/common/uni-id-common/package.json
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,16 @@
{
  "name": "uni-id-common",
  "version": "1.0.16",
  "description": "uni-id token生成、校验、刷新",
  "main": "index.js",
  "homepage": "https://uniapp.dcloud.io/uniCloud/uni-id-common.html",
  "repository": {
    "type": "git",
    "url": "git+https://gitee.com/dcloud/uni-id-common.git"
  },
  "author": "DCloud",
  "license": "Apache-2.0",
  "dependencies": {
    "uni-config-center": "file:../../../../../uni-config-center/uniCloud/cloudfunctions/common/uni-config-center"
  }
}