diff --git a/lang/i18n.js b/lang/i18n.js
index 934dfa73ac651f5baadc514771d9a05614987646..0cd806e5ce256348482d5166c1316ea493ffb54d 100644
--- a/lang/i18n.js
+++ b/lang/i18n.js
@@ -87,12 +87,6 @@ console.log(`
})
})
},1)
- //更新 uni-starter.config agreements
- let agreementsTitle = $i18n('agreementsTitle').split(',')
- let agreements = uniStarterConfig.about.agreements
- agreements[0].title = agreementsTitle[0]
- agreements[1].title = agreementsTitle[1]
- uniStarterConfig.about.agreements = agreements
}
initLanguageAfter()
uni.$on('changeLanguage', e => {
diff --git a/lang/zh-Hans.js b/lang/zh-Hans.js
index 7b9bb41c861374f7cc56a2b0111c357f03c2bfd6..9fe289e024168eece1de36b2abfe2750ee3c903d 100644
--- a/lang/zh-Hans.js
+++ b/lang/zh-Hans.js
@@ -108,7 +108,7 @@ export default {
},
settings:{
navigationBarTitle:"设置",
- userInfo: "个人资料",
+ userInfo: "账号资料",
changePassword: "修改密码",
clearTmp: "清理缓存",
pushServer: "推送功能",
diff --git a/pages.json b/pages.json
index a5070a2b2915e484b4e0a57e6ab7116592a12560..658c3418f2f5c3aad726573dd24919dd6812ca99 100644
--- a/pages.json
+++ b/pages.json
@@ -122,12 +122,13 @@
"style": {
"navigationBarTitleText": "注销账号"
}
- }, {
- "path": "uni_modules/uni-id-pages/pages/userinfo/userinfo",
- "style": {
- "navigationBarTitleText": "个人资料"
- }
- }, {
+ },
+ {
+ "path": "uni_modules/uni-id-pages/pages/userinfo/userinfo",
+ "style": {
+ "navigationBarTitleText": "个人资料"
+ }
+ },{
"path": "uni_modules/uni-id-pages/pages/userinfo/bind-mobile/bind-mobile",
"style": {
"navigationBarTitleText": "绑定手机号码"
diff --git a/pages/ucenter/settings/settings.vue b/pages/ucenter/settings/settings.vue
index 2ffa6c004810df9445d3b73d4504288e29663883..1dd1709f2bfd8c79bffbb178dd53e292f07f54bf 100644
--- a/pages/ucenter/settings/settings.vue
+++ b/pages/ucenter/settings/settings.vue
@@ -18,12 +18,8 @@
-
-
-
-
-
+
{{$t('settings.logOut')}}
{{$t('settings.login')}}
@@ -31,7 +27,8 @@
+
+
diff --git a/uni_modules/uni-id-pages/components/uni-id-pages-fab-login/uni-id-pages-fab-login.vue b/uni_modules/uni-id-pages/components/uni-id-pages-fab-login/uni-id-pages-fab-login.vue
index daddb7fc67fde53c09b77d71d55993dbab338144..b6ae82af4728cd760daa65404dc65bd666bcac09 100644
--- a/uni_modules/uni-id-pages/components/uni-id-pages-fab-login/uni-id-pages-fab-login.vue
+++ b/uni_modules/uni-id-pages/components/uni-id-pages-fab-login/uni-id-pages-fab-login.vue
@@ -15,12 +15,12 @@
+
+
diff --git a/uni_modules/uni-id-pages/pages/register/register.vue b/uni_modules/uni-id-pages/pages/register/register.vue
index 5ceaa25fda084bb1a9a0f781b4fe71526cdc1088..abd1de11e77e8549df60edd1314419a750bb5bf0 100644
--- a/uni_modules/uni-id-pages/pages/register/register.vue
+++ b/uni_modules/uni-id-pages/pages/register/register.vue
@@ -1,6 +1,13 @@
+
+
+
+
+
+ 用户名密码注册
+
@@ -25,7 +32,13 @@
-
+
+
+
+ 邮箱验证码注册
+ 已有账号?点此登录
+
+
@@ -50,12 +63,8 @@
focusUsername:false,
focusNickname:false,
focusPassword:false,
- focusPassword2:false
- }
- },
- computed:{
- passwordLength(){
- return config.password.length
+ focusPassword2:false,
+ logo: "/static/logo.png"
}
},
onReady() {
@@ -111,6 +120,16 @@
},
navigateBack() {
uni.navigateBack()
+ },
+ toLogin() {
+ uni.navigateTo({
+ url: '/uni_modules/uni-id-pages/pages/login/login-withpwd'
+ })
+ },
+ registerByEmail() {
+ uni.navigateTo({
+ url: '/uni_modules/uni-id-pages/pages/register/register-by-email'
+ })
}
}
}
@@ -118,9 +137,33 @@
diff --git a/uni_modules/uni-id-pages/pages/retrieve/retrieve.vue b/uni_modules/uni-id-pages/pages/retrieve/retrieve.vue
index 0b7a14bef43f2cdcbf841a9ffb63370bdbf8ec18..69450add33352b7a7881fb92feb3004d8bbbeca6 100644
--- a/uni_modules/uni-id-pages/pages/retrieve/retrieve.vue
+++ b/uni_modules/uni-id-pages/pages/retrieve/retrieve.vue
@@ -1,6 +1,13 @@
+
+
+
+
+
+ 通过手机验证码找回密码
+
+
+
+ 通过邮箱验证码找回密码
+
+
+
@@ -101,7 +114,8 @@
}
]
}
- }
+ },
+ logo: "/static/logo.png"
}
},
computed: {
@@ -187,6 +201,11 @@
console.log(key,'focus'+key);
this['focus'+key] = true
})
+ },
+ retrieveByEmail() {
+ uni.navigateTo({
+ url: '/uni_modules/uni-id-pages/pages/retrieve/retrieve-by-email'
+ })
}
}
}
@@ -195,7 +214,26 @@
diff --git a/uni_modules/uni-id-pages/pages/userinfo/bind-mobile/bind-mobile.vue b/uni_modules/uni-id-pages/pages/userinfo/bind-mobile/bind-mobile.vue
index 351c32b3b7fcba2c5d834fe8223973036275411d..22912d10d7dc076b01cf30e8efca046cc8ecc55c 100644
--- a/uni_modules/uni-id-pages/pages/userinfo/bind-mobile/bind-mobile.vue
+++ b/uni_modules/uni-id-pages/pages/userinfo/bind-mobile/bind-mobile.vue
@@ -1,6 +1,13 @@
+
+
+
+
+
+ 绑定手机号
+
@@ -20,7 +27,8 @@
code: "",
captcha: ""
},
- focusMobile:true
+ focusMobile:true,
+ logo: "/static/logo.png"
}
},
computed: {
@@ -90,6 +98,13 @@
padding: 50rpx;
padding-top: 10px;
}
+
+
+ @media screen and (min-width: 690px) {
+ .uni-content{
+ padding: 30px 40px 40px;
+ }
+ }
/* #ifndef APP-NVUE || VUE3 */
.uni-content ::v-deep .uni-easyinput__content {}
diff --git a/uni_modules/uni-id-pages/pages/userinfo/change_pwd/change_pwd.vue b/uni_modules/uni-id-pages/pages/userinfo/change_pwd/change_pwd.vue
index 724e47bbe2e063436f7c3cb6bfc383cfe9993eda..d41901f19f9a76ade2418d9319907c84553a9fb4 100644
--- a/uni_modules/uni-id-pages/pages/userinfo/change_pwd/change_pwd.vue
+++ b/uni_modules/uni-id-pages/pages/userinfo/change_pwd/change_pwd.vue
@@ -1,6 +1,13 @@
+
+
+
+
+
+ 修改密码
+
@import "@/uni_modules/uni-id-pages/common/login-page.scss";
- .uni-content {
- margin-top: 15px;
+ @media screen and (max-width: 690px) {
+ .uni-content{
+ margin-top: 15px;
+ }
+ }
+
+ @media screen and (min-width: 690px) {
+ .uni-content{
+ padding: 30px 40px 40px;
+ }
}
diff --git a/uni_modules/uni-id-pages/pages/userinfo/deactivate/deactivate.vue b/uni_modules/uni-id-pages/pages/userinfo/deactivate/deactivate.vue
index 817fbd3da808857afad3f1c657dde115d63638ec..160a4b62ff0b962d316af786597e009b81dc9510 100644
--- a/uni_modules/uni-id-pages/pages/userinfo/deactivate/deactivate.vue
+++ b/uni_modules/uni-id-pages/pages/userinfo/deactivate/deactivate.vue
@@ -1,6 +1,6 @@
-
+
一、注销是不可逆操作,注销后:\n
1.帐号将无法登录、无法找回。\n
@@ -64,7 +64,7 @@
diff --git a/uni_modules/uni-id-pages/pages/userinfo/userinfo.js b/uni_modules/uni-id-pages/pages/userinfo/userinfo.js
new file mode 100644
index 0000000000000000000000000000000000000000..86bbf772cd8d12107edafd6dea0ad86ff5dfda84
--- /dev/null
+++ b/uni_modules/uni-id-pages/pages/userinfo/userinfo.js
@@ -0,0 +1,166 @@
+const db = uniCloud.database();
+const usersTable = db.collection('uni-id-users')
+const uniIdCo = uniCloud.importObject("uni-id-co")
+export default {
+ data() {
+ return {
+ univerifyStyle: {
+ authButton: {
+ "title": "本机号码一键绑定", // 授权按钮文案
+ },
+ otherLoginButton: {
+ "title": "其他号码绑定",
+ }
+ },
+ userInfo: {
+ mobile: '',
+ nickname: ''
+ },
+ hasLogin: false,
+ hasPwd: false
+ }
+ },
+ async onShow() {
+ this.univerifyStyle.authButton.title = "本机号码一键绑定"
+ this.univerifyStyle.otherLoginButton.title = "其他号码绑定"
+ },
+ async onLoad() {
+ this.getUserInfo()
+ //判断当前用户是否有密码,否则就不显示密码修改功能
+ let res = await uniIdCo.getAccountInfo()
+ this.hasPwd = res.isPasswordSet
+ },
+ methods: {
+ login() {
+ uni.navigateTo({
+ url: '/uni_modules/uni-id-pages/pages/login/login-withoutpwd',
+ complete: (e) => {
+ console.log(e);
+ }
+ })
+ },
+ async logout() {
+ await uniIdCo.logout()
+ uni.removeStorageSync('uni_id_token');
+ uni.setStorageSync('uni_id_token_expired', 0)
+ uni.redirectTo({
+ url: '/uni_modules/uni-id-pages/pages/login/login-withoutpwd',
+ });
+ },
+ changePassword() {
+ uni.navigateTo({
+ url: '/uni_modules/uni-id-pages/pages/userinfo/change_pwd/change_pwd',
+ complete: (e) => {
+ console.log(e);
+ }
+ })
+ },
+ getUserInfo(e) {
+ uni.showLoading({
+ mask: true
+ });
+ usersTable.where("'_id' == $cloudEnv_uid").field('mobile,nickname').get().then(res => {
+ console.log({
+ res
+ });
+ this.userInfo = res.result.data[0]
+ console.log('this.userInfo', this.userInfo);
+ this.hasLogin = true
+ }).catch(e => {
+ this.userInfo = {}
+ this.hasLogin = false
+ console.log(e.message, e.errCode);
+ }).finally(e => {
+ // console.log(e);
+ uni.hideLoading()
+ })
+ },
+ bindMobile() {
+ // #ifdef APP-PLUS
+ uni.preLogin({
+ provider: 'univerify',
+ success: this.univerify(), //预登录成功
+ fail: (res) => { // 预登录失败
+ // 不显示一键登录选项(或置灰)
+ console.log(res)
+ this.bindMobileBySmsCode()
+ }
+ })
+ // #endif
+ // #ifdef MP-WEIXIN
+ this.$refs['bind-mobile'].open()
+ // #endif
+ // #ifdef H5
+ //...去用验证码绑定
+ this.bindMobileBySmsCode()
+ // #endif
+ },
+ univerify() {
+ uni.login({
+ "provider": 'univerify',
+ "univerifyStyle": this.univerifyStyle,
+ success: async e => {
+ console.log(e.authResult);
+ uniIdCo.bindMobileByUniverify(e.authResult).then(res => {
+ console.log(res);
+ this.getUserInfo()
+ }).catch(e => {
+ console.log(e);
+ }).finally(e => {
+ console.log(e);
+ uni.closeAuthView()
+ })
+ },
+ fail: (err) => {
+ console.log(err);
+ if (err.code == '30002' || err.code == '30001') {
+ this.bindMobileBySmsCode()
+ }
+ }
+ })
+ },
+ bindMobileBySmsCode() {
+ uni.navigateTo({
+ url: './bind-mobile/bind-mobile',
+ events: {
+ getUserInfo: () => {
+ this.getUserInfo()
+ }
+ },
+ complete(e) {
+ console.log(e);
+ }
+ })
+ },
+ setNickname(nickname) {
+ console.log(nickname);
+ if (nickname) {
+ usersTable.where('_id==$env.uid').update({
+ nickname
+ }).then(e => {
+ console.log(e);
+ if (e.result.updated) {
+ uni.showToast({
+ title: "更新成功",
+ icon: 'none'
+ });
+ this.userInfo.nickname = nickname
+ } else {
+ uni.showToast({
+ title: "没有改变",
+ icon: 'none'
+ });
+ }
+ })
+ this.$refs.dialog.close()
+ } else {
+ this.$refs.dialog.open()
+ }
+ },
+ deactivate() {
+ uni.navigateTo({
+ url: "/uni_modules/uni-id-pages/pages/userinfo/deactivate/deactivate"
+ })
+ }
+ }
+}
diff --git a/uni_modules/uni-id-pages/pages/userinfo/userinfo.vue b/uni_modules/uni-id-pages/pages/userinfo/userinfo.vue
index 2566cdcb5d98b4c8d98092dca0620101e82dedd0..c59c9c694d1edea9833d86257b49a248eb709175 100644
--- a/uni_modules/uni-id-pages/pages/userinfo/userinfo.vue
+++ b/uni_modules/uni-id-pages/pages/userinfo/userinfo.vue
@@ -1,80 +1,80 @@
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+ console.log({res});
+ this.userInfo = res.result.data[0]
+ console.log('this.userInfo', this.userInfo);
+ this.hasLogin = true
+ }).catch(e => {
+ this.userInfo = {}
+ this.hasLogin = false
+ console.log(e.message, e.errCode);
+ }).finally(e => {
+ // console.log(e);
+ uni.hideLoading()
+ })
+ },
+ bindMobile() {
+ // #ifdef APP-PLUS
+ uni.preLogin({
+ provider: 'univerify',
+ success: this.univerify(), //预登录成功
+ fail: (res) => { // 预登录失败
+ // 不显示一键登录选项(或置灰)
+ console.log(res)
+ this.bindMobileBySmsCode()
+ }
+ })
+ // #endif
+
+ // #ifdef MP-WEIXIN
+ this.$refs['bind-mobile'].open()
+ // #endif
+
+ // #ifdef H5
+ //...去用验证码绑定
+ this.bindMobileBySmsCode()
+ // #endif
+ },
+ univerify() {
+ uni.login({
+ "provider": 'univerify',
+ "univerifyStyle": this.univerifyStyle,
+ success: async e => {
+ console.log(e.authResult);
+ uniIdCo.bindMobileByUniverify(e.authResult).then(res => {
+ console.log(res);
+ this.getUserInfo()
+ }).catch(e => {
+ console.log(e);
+ }).finally(e=>{
+ console.log(e);
+ uni.closeAuthView()
+ })
+ },
+ fail: (err) => {
+ console.log(err);
+ if (err.code == '30002' || err.code == '30001') {
+ this.bindMobileBySmsCode()
+ }
+ }
+ })
+ },
+ bindMobileBySmsCode() {
+ uni.navigateTo({
+ url: './bind-mobile/bind-mobile',
+ events: {
+ getUserInfo: () => {
+ this.getUserInfo()
+ }
+ },
+ complete(e) {
+ console.log(e);
+ }
+ })
+ },
+ setNickname(nickname) {
+ console.log(nickname);
+ if (nickname) {
+ usersTable.where('_id==$env.uid').update({
+ nickname
+ }).then(e => {
+ console.log(e);
+ if (e.result.updated) {
+ uni.showToast({
+ title: "更新成功",
+ icon: 'none'
+ });
+ this.userInfo.nickname = nickname
+ } else {
+ uni.showToast({
+ title: "没有改变",
+ icon: 'none'
+ });
+ }
+ })
+ this.$refs.dialog.close()
+ } else {
+ this.$refs.dialog.open()
+ }
+ },
+ deactivate(){
+ uni.navigateTo({
+ url:"/uni_modules/uni-id-pages/pages/userinfo/deactivate/deactivate"
+ })
+ }
+ }
+ }
+
+
diff --git a/uni_modules/uni-id-pages/pages_init.json b/uni_modules/uni-id-pages/pages_init.json
new file mode 100644
index 0000000000000000000000000000000000000000..5d2a4e8b83b8b31097c4d57a989ef67b46ce78af
--- /dev/null
+++ b/uni_modules/uni-id-pages/pages_init.json
@@ -0,0 +1,87 @@
+
+{
+ "pages": [
+ {
+ "path": "uni_modules/uni-id-pages/pages/userinfo/deactivate/deactivate",
+ "style": {
+ "navigationBarTitleText": "注销账号"
+ }
+ },
+ {
+ "path": "uni_modules/uni-id-pages/pages/userinfo/userinfo",
+ "style": {
+ "navigationBarTitleText": "个人资料"
+ }
+ },
+ {
+ "path": "uni_modules/uni-id-pages/pages/userinfo/bind-mobile/bind-mobile",
+ "style": {
+ "navigationBarTitleText": "绑定手机号码"
+ }
+ },
+ {
+ "path": "uni_modules/uni-id-pages/pages/userinfo/cropImage/cropImage",
+ "style": {
+ "navigationBarTitleText": ""
+ }
+ },
+ {
+ "path": "uni_modules/uni-id-pages/pages/login/login-withoutpwd",
+ "style": {
+ "navigationBarTitleText": ""
+ }
+ },
+ {
+ "path": "uni_modules/uni-id-pages/pages/login/login-withpwd",
+ "style": {
+ "navigationBarTitleText": ""
+ }
+ },
+ {
+ "path": "uni_modules/uni-id-pages/pages/login/login-smscode",
+ "style": {
+ "navigationBarTitleText": "手机验证码登录"
+ }
+ },
+ {
+ "path": "uni_modules/uni-id-pages/pages/register/register",
+ "style": {
+ "navigationBarTitleText": "注册"
+ }
+ },
+ {
+ "path": "uni_modules/uni-id-pages/pages/register/register-by-email",
+ "style": {
+ "navigationBarTitleText": "邮箱验证码注册"
+ }
+ },
+ {
+ "path": "uni_modules/uni-id-pages/pages/retrieve/retrieve",
+ "style": {
+ "navigationBarTitleText": "重置密码"
+ }
+ },
+ {
+ "path": "uni_modules/uni-id-pages/pages/retrieve/retrieve-by-email",
+ "style": {
+ "navigationBarTitleText": "通过邮箱重置密码"
+ }
+ },
+ {
+ "path": "uni_modules/uni-id-pages/pages/common/webview/webview",
+ "style": {
+ "navigationBarTitleText": "",
+ "enablePullDownRefresh": false
+ }
+ }
+ ,{
+ "path" : "uni_modules/uni-id-pages/pages/userinfo/change_pwd/change_pwd",
+ "style" :
+ {
+ "navigationBarTitleText": "修改密码",
+ "enablePullDownRefresh": false
+ }
+
+ }
+ ]
+}
\ No newline at end of file
diff --git a/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/common/validator.js b/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/common/validator.js
index 7e0e33a304fa56c18923a365f26a6a305bc1b790..34878ca8b485267aa2aaf3681681fe068077e3a8 100644
--- a/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/common/validator.js
+++ b/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/common/validator.js
@@ -29,6 +29,21 @@ baseValidator.username = function (username) {
}
}
+baseValidator.password = function (password) {
+ const errCode = ERROR.INVALID_PASSWORD
+ if (!isValidString(password)) {
+ return {
+ errCode
+ }
+ }
+ if (password.length < 6) {
+ // 密码长度不能小于6
+ return {
+ errCode
+ }
+ }
+}
+
baseValidator.mobile = function (mobile) {
const errCode = ERROR.INVALID_MOBILE
if (!isValidString(mobile)) {
@@ -92,7 +107,7 @@ baseType.forEach((type) => {
}
})
-function tokenize (name) {
+function tokenize(name) {
let i = 0
const result = []
let token = ''
@@ -122,7 +137,7 @@ function tokenize (name) {
* 处理validator名
* @param {string} name
*/
-function parseValidatorName (name) {
+function parseValidatorName(name) {
const tokenList = tokenize(name)
let i = 0
let currentToken = tokenList[i]
@@ -172,7 +187,7 @@ function parseValidatorName (name) {
return result
}
-function getRuleCategory (rule) {
+function getRuleCategory(rule) {
switch (rule.type) {
case 'array':
return 'array'
@@ -183,7 +198,7 @@ function getRuleCategory (rule) {
}
}
-function isMatchUnionType (val, rule) {
+function isMatchUnionType(val, rule) {
if (!rule.children || rule.children.length === 0) {
return true
}
@@ -209,7 +224,7 @@ function isMatchUnionType (val, rule) {
return false
}
-function isMatchBaseType (val, rule) {
+function isMatchBaseType(val, rule) {
if (typeof baseValidator[rule.type] !== 'function') {
throw new Error(`invalid schema type: ${rule.type}`)
}
@@ -220,7 +235,7 @@ function isMatchBaseType (val, rule) {
return true
}
-function isMatchArrayType (arr, rule) {
+function isMatchArrayType(arr, rule) {
if (getType(arr) !== 'array') {
return false
}
@@ -249,11 +264,12 @@ const passwordRules = {
// 密码必须为字母、数字和特殊符号任意两种的组合
medium: /^(?![0-9]+$)(?![a-zA-Z]+$)(?![~!@#$%^&*_\-+=`|\\(){}[\]:;"'<>,.?/]+$)[0-9a-zA-Z~!@#$%^&*_\-+=`|\\(){}[\]:;"'<>,.?/]{8,16}$/,
// 密码必须包含字母和数字
- weak: /^(?=.*[0-9])(?=.*[a-zA-Z])[0-9a-zA-Z~!@#$%^&*_\-+=`|\\(){}[\]:;"'<>,.?/]{6,16}$/
+ weak: /^(?=.*[0-9])(?=.*[a-zA-Z])[0-9a-zA-Z~!@#$%^&*_\-+=`|\\(){}[\]:;"'<>,.?/]{6,16}$/,
+
}
-function createPasswordVerifier ({
- passwordStrength = 'medium'
+function createPasswordVerifier({
+ passwordStrength = ''
} = {}) {
return function (password) {
const passwordRegExp = passwordRules[passwordStrength]
@@ -275,28 +291,30 @@ function createPasswordVerifier ({
}
class Validator {
- constructor ({
- passwordStrength = 'medium'
+ constructor({
+ passwordStrength = ''
} = {}) {
this.baseValidator = baseValidator
this.customValidator = Object.create(null)
- this.mixin(
- 'password',
- createPasswordVerifier({
- passwordStrength
- })
- )
+ if (passwordStrength) {
+ this.mixin(
+ 'password',
+ createPasswordVerifier({
+ passwordStrength
+ })
+ )
+ }
}
- mixin (type, handler) {
+ mixin(type, handler) {
this.customValidator[type] = handler
}
- getRealBaseValidator (type) {
+ getRealBaseValidator(type) {
return this.customValidator[type] || this.baseValidator[type]
}
- get validator () {
+ get validator() {
return new Proxy({}, {
get: (_, prop) => {
if (typeof prop !== 'string') {
@@ -318,7 +336,7 @@ class Validator {
})
}
- validate (value = {}, schema = {}) {
+ validate(value = {}, schema = {}) {
for (const schemaKey in schema) {
let schemaValue = schema[schemaKey]
if (getType(schemaValue) === 'string') {
@@ -358,7 +376,7 @@ class Validator {
}
}
-function checkClientInfo (clientInfo) {
+function checkClientInfo(clientInfo) {
const stringNotRequired = {
required: false,
type: 'string'
diff --git a/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/common/validator.test.js b/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/common/validator.test.js
new file mode 100644
index 0000000000000000000000000000000000000000..092edccfedf315c67950db7a422180ec706e0cb4
--- /dev/null
+++ b/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/common/validator.test.js
@@ -0,0 +1,209 @@
+const assert = require('assert')
+const {
+ Validator
+} = require('./validator')
+const {
+ ERROR
+} = require('./error')
+const {
+ getType
+} = require('./utils')
+
+const testCaseList = [{
+ value: {
+ username: 'uname'
+ },
+ schema: {
+ username: 'username'
+ },
+ expected: undefined
+}, {
+ value: {
+ username: '123456'
+ },
+ schema: {
+ username: 'username'
+ },
+ expected: {
+ errCode: ERROR.INVALID_USERNAME
+ }
+}, {
+ value: {
+ username: '数字天堂'
+ },
+ schema: {
+ username: 'username'
+ },
+ expected: {
+ errCode: ERROR.INVALID_USERNAME
+ }
+}, {
+ value: {
+ password: '123456abc'
+ },
+ schema: {
+ password: 'password'
+ }
+}, {
+ value: {
+ password: '123456def'
+ },
+ schema: {
+ password: 'password'
+ },
+ mixin: [{
+ type: 'password',
+ handler: function (password) {
+ if (typeof password !== 'string' || password.length < 10) {
+ return {
+ errCode: ERROR.INVALID_PASSWORD
+ }
+ }
+ }
+ }],
+ expected: {
+ errCode: ERROR.INVALID_PASSWORD
+ }
+}, {
+ value: {
+ numberOrString: '123456'
+ },
+ schema: {
+ numberOrString: 'number|string'
+ }
+}, {
+ value: {
+ numberOrString: 123456
+ },
+ schema: {
+ numberOrString: 'number|string'
+ }
+}, {
+ value: {
+ numberOrString: '123456'
+ },
+ schema: {
+ numberOrString: 'string|number'
+ }
+}, {
+ value: {
+ numberOrString: 123456
+ },
+ schema: {
+ numberOrString: 'string|number'
+ }
+}, {
+ value: {
+ numberOrString: ['123456']
+ },
+ schema: {
+ numberOrString: 'array'
+ }
+}, {
+ value: {
+ numberOrString: [123456]
+ },
+ schema: {
+ numberOrString: 'array'
+ }
+}, {
+ value: {
+ numberOrString: [123456, '123456']
+ },
+ schema: {
+ numberOrString: 'array'
+ }
+}, {
+ value: {
+ numberOrString: ['123456']
+ },
+ schema: {
+ numberOrString: 'array'
+ }
+}, {
+ value: {
+ numberOrString: [123456]
+ },
+ schema: {
+ numberOrString: 'array'
+ }
+}, {
+ value: {
+ numberOrString: [123456, '123456']
+ },
+ schema: {
+ numberOrString: 'array'
+ }
+}, {
+ value: {
+ numberOrString: ['123456']
+ },
+ mixin: [{
+ type: '1to6',
+ handler: function (val) {
+ if (val !== '123456') {
+ return {
+ errCode: ERROR.INVALID_PARAM
+ }
+ }
+ }
+ }],
+ schema: {
+ numberOrString: 'array'
+ }
+}]
+
+function execTestCase ({
+ value = {},
+ schema = {},
+ mixin = [],
+ expected = undefined,
+ error = ''
+} = {}) {
+ const validator = new Validator()
+ for (let i = 0; i < mixin.length; i++) {
+ const {
+ type,
+ handler
+ } = mixin[i]
+ validator.mixin(type, handler)
+ }
+ let validateResult,
+ validateError
+ try {
+ validateResult = validator.validate(value, schema)
+ } catch (err) {
+ validateError = err
+ }
+ const tag = JSON.stringify({ value, schema })
+ if (error) {
+ if (typeof error === 'string') {
+ assert.strictEqual(validateError.message.indexOf(error) > -1, true, `[${tag}] error message error`)
+ } else if (getType(error) === 'regexp') {
+ assert.strictEqual(error.test(validateError), true, `[${tag}] error message error`)
+ } else {
+ throw new Error(`[${tag}] invalid test case`)
+ }
+ return
+ }
+ if (expected === undefined) {
+ assert.strictEqual(validateResult, undefined, `[${tag}] validate result error`)
+ return
+ }
+ const expectedKeys = Object.keys(expected)
+ let passResultCheck = true
+ for (let i = 0; i < expectedKeys.length; i++) {
+ const key = expectedKeys[i]
+ if (expected[key] !== validateResult[key]) {
+ passResultCheck = false
+ break
+ }
+ }
+ assert.strictEqual(passResultCheck, true, `[${tag}] validate result error`)
+}
+
+for (let i = 0; i < testCaseList.length; i++) {
+ console.log(`test case: ${i}`)
+ execTestCase(testCaseList[i])
+ console.log(`test case: ${i}, pass`)
+}
diff --git a/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/config/permission.js b/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/config/permission.js
index ce5b02df071216ab42fc79cec697dee2d5a2d050..f67725c6880d56611b9f236a82645671d05e3d90 100644
--- a/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/config/permission.js
+++ b/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/config/permission.js
@@ -7,6 +7,9 @@ module.exports = {
// permission: [] // 允许进行此操作的权限,包含任一权限均可操作。
// 权限角色均配置时,用户拥有任一权限或任一角色均可操作
},
+ updateUser: {
+ role: ['admin']
+ },
authorizeAppLogin: {
role: ['admin']
},
diff --git a/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/index.obj.js b/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/index.obj.js
index 2ee707321e28f66e204b8c44f8c32e4347a56959..2fe72784d4df867484864367263d6f4baf347974 100644
--- a/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/index.obj.js
+++ b/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/index.obj.js
@@ -18,7 +18,8 @@ const {
registerUser
} = require('./module/register/index')
const {
- addUser
+ addUser,
+ updateUser
} = require('./module/admin/index')
const {
login,
@@ -109,7 +110,7 @@ module.exports = {
this.hooks = this.configUtils.getHooks()
this.validator = new Validator({
- passwordStrength: this.config.passwordStrength || 'medium'
+ passwordStrength: this.config.passwordStrength
})
/**
* 示例:覆盖密码验证规则
@@ -216,6 +217,23 @@ module.exports = {
* @returns
*/
addUser,
+ /**
+ * 修改用户
+ * @tutorial https://uniapp.dcloud.net.cn/uniCloud/uni-id-pages.html#update-user
+ * @param {Object} params
+ * @param {String} params.id 要更新的用户id
+ * @param {String} params.username 用户名
+ * @param {String} params.password 密码
+ * @param {String} params.nickname 昵称
+ * @param {Array} params.authorizedApp 允许登录的AppID列表
+ * @param {Array} params.role 用户角色列表
+ * @param {String} params.mobile 手机号
+ * @param {String} params.email 邮箱
+ * @param {Array} params.tags 用户标签
+ * @param {Number} params.status 用户状态
+ * @returns
+ */
+ updateUser,
/**
* 授权用户登录应用
* @tutorial https://uniapp.dcloud.net.cn/uniCloud/uni-id-pages.html#authorize-app-login
@@ -490,4 +508,4 @@ module.exports = {
* @returns
*/
getSupportedLoginType
-}
+}
diff --git a/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/lib/utils/config.js b/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/lib/utils/config.js
index 11166d52994ec2c07c0daa2d7d2250f7e501989f..fdc71605c3a85cc8570d8ef547635c27bab917d2 100644
--- a/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/lib/utils/config.js
+++ b/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/lib/utils/config.js
@@ -4,8 +4,8 @@ const {
const createConfig = require('uni-config-center')
const requiredConfig = {
- 'web.h5-weixin': ['appid', 'appsecret'],
- 'web.web-weixin': ['appid', 'appsecret'],
+ 'web.weixin-h5': ['appid', 'appsecret'],
+ 'web.weixin-web': ['appid', 'appsecret'],
'app.weixin': ['appid', 'appsecret'],
'mp-weixin.weixin': ['appid', 'appsecret'],
'app.qq': ['appid', 'appsecret'],
diff --git a/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/lib/utils/login.js b/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/lib/utils/login.js
index 35fb0acbbe8a6ae0c26ee250f077c3e7ee0afc01..203bec431c9e130a8a7669fdd664f3a30c11bd51 100644
--- a/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/lib/utils/login.js
+++ b/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/lib/utils/login.js
@@ -8,6 +8,9 @@ const {
const {
ERROR
} = require('../../common/error')
+const {
+ logout
+} = require('./logout')
const PasswordUtils = require('./password')
async function realPreLogin (params = {}) {
@@ -173,10 +176,14 @@ async function postLogin (params = {}) {
extraData,
isThirdParty = false
} = params
+ const {
+ clientIP,
+ uniIdToken
+ } = this.getClientInfo()
const uid = user._id
const updateData = {
last_login_date: Date.now(),
- last_login_ip: this.getClientInfo().clientIP,
+ last_login_ip: clientIP,
...extraData
}
const {
@@ -185,6 +192,13 @@ async function postLogin (params = {}) {
} = await this.uniIdCommon.createToken({
uid
})
+
+ if (uniIdToken) {
+ try {
+ await logout.call(this)
+ } catch (error) {}
+ }
+
await userCollection.doc(uid).update(updateData)
await this.middleware.uniIdLog({
data: {
diff --git a/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/lib/utils/logout.js b/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/lib/utils/logout.js
new file mode 100644
index 0000000000000000000000000000000000000000..dc49fc7c97d71de625d1cbadcb32fb8180008039
--- /dev/null
+++ b/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/lib/utils/logout.js
@@ -0,0 +1,47 @@
+const {
+ dbCmd,
+ LOG_TYPE,
+ deviceCollection,
+ userCollection
+} = require('../../common/constants')
+
+async function logout() {
+ const {
+ uniIdToken,
+ deviceId
+ } = this.getClientInfo()
+ const {
+ uid
+ } = await this.uniIdCommon.checkToken(
+ uniIdToken,
+ {
+ autoRefresh: false
+ }
+ )
+
+ // 删除token
+ await userCollection.doc(uid).update({
+ token: dbCmd.pull(uniIdToken)
+ })
+
+ // 仅当device表的device_id和user_id均对应时才进行更新
+ await deviceCollection.where({
+ device_id: deviceId,
+ user_id: uid
+ }).update({
+ token_expired: 0
+ })
+ await this.middleware.uniIdLog({
+ data: {
+ user_id: uid
+ },
+ type: LOG_TYPE.LOGOUT
+ })
+ return {
+ errCode: 0
+ }
+}
+
+module.exports = {
+ logout
+}
\ No newline at end of file
diff --git a/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/lib/utils/qq.js b/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/lib/utils/qq.js
index 22a56520b533af6b64eb84377b28d89404429c6e..ebacbb1a99832aa263130ddeeceb78b2867d6e23 100644
--- a/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/lib/utils/qq.js
+++ b/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/lib/utils/qq.js
@@ -5,7 +5,7 @@ const {
ERROR
} = require('../../common/error')
-function getQQPlatform () {
+function getQQPlatform() {
const platform = this.clientPlatform
switch (platform) {
case 'app':
@@ -18,7 +18,7 @@ function getQQPlatform () {
}
}
-async function saveQQUserKey ({
+async function saveQQUserKey({
openid,
sessionKey, // QQ小程序用户sessionKey
accessToken, // App端QQ用户accessToken
@@ -45,14 +45,17 @@ async function saveQQUserKey ({
await this.uniOpenBridge.setUserAccessToken(keyObj, {
access_token: accessToken,
access_token_expired: accessTokenExpired
- }, Math.floor((accessTokenExpired - Date.now()) / 1000))
+ }, accessTokenExpired ?
+ Math.floor((accessTokenExpired - Date.now()) / 1000) :
+ 30 * 24 * 60 * 60
+ )
break
default:
break
}
}
-function generateQQCache ({
+function generateQQCache({
sessionKey, // QQ小程序用户sessionKey
accessToken, // App端QQ用户accessToken
accessTokenExpired // App端QQ用户accessToken过期时间
@@ -81,7 +84,7 @@ function generateQQCache ({
}
}
-function getQQOpenid ({
+function getQQOpenid({
userRecord
} = {}) {
const qqPlatform = getQQPlatform.call(this)
@@ -93,7 +96,7 @@ function getQQOpenid ({
return qqOpenidObj[`${qqPlatform}_${appId}`] || qqOpenidObj[qqPlatform]
}
-async function getQQCacheFallback ({
+async function getQQCacheFallback({
userRecord,
key
} = {}) {
@@ -106,7 +109,7 @@ async function getQQCacheFallback ({
return qqCache && qqCache[key]
}
-async function getQQCache ({
+async function getQQCache({
uid,
userRecord,
key
diff --git a/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/lib/utils/register.js b/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/lib/utils/register.js
index 3eae52af0bfe9034790ca17d308b725a6cf1bf0b..2ecd186e32133dc40cf09fab4d777bea6ec0f440 100644
--- a/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/lib/utils/register.js
+++ b/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/lib/utils/register.js
@@ -12,10 +12,13 @@ const {
getValidInviteCode,
generateInviteInfo
} = require('./fission')
+const {
+ logout
+} = require('./logout')
const PasswordUtils = require('./password')
const merge = require('lodash.merge')
-async function realPreRegister (params = {}) {
+async function realPreRegister(params = {}) {
const {
user
} = params
@@ -30,7 +33,7 @@ async function realPreRegister (params = {}) {
}
}
-async function preRegister (params = {}) {
+async function preRegister(params = {}) {
try {
await realPreRegister.call(this, params)
} catch (error) {
@@ -42,7 +45,7 @@ async function preRegister (params = {}) {
}
}
-async function preRegisterWithPassword (params = {}) {
+async function preRegisterWithPassword(params = {}) {
const {
user,
password
@@ -69,7 +72,7 @@ async function preRegisterWithPassword (params = {}) {
}
}
-async function thirdPartyRegister ({
+async function thirdPartyRegister({
user = {}
} = {}) {
return {
@@ -78,7 +81,7 @@ async function thirdPartyRegister ({
}
}
-async function postRegister (params = {}) {
+async function postRegister(params = {}) {
const {
user,
extraData = {},
@@ -93,7 +96,8 @@ async function postRegister (params = {}) {
channel,
scene,
clientIP,
- osName
+ osName,
+ uniIdToken
} = this.getClientInfo()
merge(user, extraData)
@@ -147,6 +151,12 @@ async function postRegister (params = {}) {
user.invite_time = inviteTime
}
+ if (uniIdToken) {
+ try {
+ await logout.call(this)
+ } catch (error) {}
+ }
+
const beforeRegister = this.hooks.beforeRegister
let userRecord = user
if (beforeRegister) {
diff --git a/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/lib/utils/weixin.js b/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/lib/utils/weixin.js
index fc27f77d69123efd6d0ba1e9b6968fed275802cf..8ff178f3c88a65c011773f11cc5947e234c6d086 100644
--- a/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/lib/utils/weixin.js
+++ b/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/lib/utils/weixin.js
@@ -78,7 +78,7 @@ async function saveWeixinUserKey ({
access_token: accessToken,
refresh_token: refreshToken,
access_token_expired: accessTokenExpired
- }, 30 * 24 * 3600)
+ }, 30 * 24 * 60 * 60)
break
default:
break
diff --git a/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/module/admin/add-user.js b/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/module/admin/add-user.js
index 988ee5b8e01457a6c11197c96b239dd59d6aff1f..6baa5752c017281a02a7250da8d39e0dbf54f55f 100644
--- a/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/module/admin/add-user.js
+++ b/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/module/admin/add-user.js
@@ -18,6 +18,10 @@ const PasswordUtils = require('../../lib/utils/password')
* @param {String} params.nickname 昵称
* @param {Array} params.authorizedApp 允许登录的AppID列表
* @param {Array} params.role 用户角色列表
+ * @param {String} params.mobile 手机号
+ * @param {String} params.email 邮箱
+ * @param {Array} params.tags 用户标签
+ * @param {Number} params.status 用户状态
* @returns
*/
module.exports = async function (params = {}) {
@@ -35,6 +39,22 @@ module.exports = async function (params = {}) {
role: {
require: false,
type: 'array'
+ },
+ mobile: {
+ required: false,
+ type: 'mobile'
+ },
+ email: {
+ required: false,
+ type: 'email'
+ },
+ tags: {
+ required: false,
+ type: 'array'
+ },
+ status: {
+ required: false,
+ type: 'number'
}
}
this.middleware.validate(params, schema)
@@ -43,11 +63,17 @@ module.exports = async function (params = {}) {
password,
authorizedApp,
nickname,
- role
+ role,
+ mobile,
+ email,
+ tags,
+ status
} = params
const userMatched = await findUser({
userQuery: {
- username
+ username,
+ mobile,
+ email
},
authorizedApp
})
@@ -65,17 +91,28 @@ module.exports = async function (params = {}) {
} = passwordUtils.generatePasswordHash({
password
})
-
- await userCollection.add({
+ const data = {
username,
password: passwordHash,
password_secret_version: version,
dcloud_appid: authorizedApp || [],
nickname,
- role: role || []
- })
+ role: role || [],
+ mobile,
+ email,
+ tags: tags || [],
+ status
+ }
+ if (email) {
+ data.email_confirmed = 1
+ }
+ if (mobile) {
+ data.mobile_confirmed = 1
+ }
+ await userCollection.add(data)
return {
- errCode: 0
+ errCode: 0,
+ errMsg: ''
}
}
diff --git a/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/module/admin/index.js b/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/module/admin/index.js
index 9c9c723d931d0114e35286eb91149fe059cf3b20..c8830f54d386f85177ee549b25af2dc5a5251601 100644
--- a/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/module/admin/index.js
+++ b/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/module/admin/index.js
@@ -1,3 +1,4 @@
module.exports = {
- addUser: require('./add-user')
+ addUser: require('./add-user'),
+ updateUser: require('./update-user')
}
diff --git a/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/module/admin/update-user.js b/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/module/admin/update-user.js
new file mode 100644
index 0000000000000000000000000000000000000000..5dc1b294fdd172071d2132b642f364f2d411c7df
--- /dev/null
+++ b/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/module/admin/update-user.js
@@ -0,0 +1,128 @@
+const {
+ findUser
+} = require('../../lib/utils/account')
+const {
+ ERROR
+} = require('../../common/error')
+const {
+ userCollection
+} = require('../../common/constants')
+const PasswordUtils = require('../../lib/utils/password')
+
+/**
+ * 修改用户
+ * @tutorial https://uniapp.dcloud.net.cn/uniCloud/uni-id-pages.html#update-user
+ * @param {Object} params
+ * @param {String} params.uid 要更新的用户id
+ * @param {String} params.username 用户名
+ * @param {String} params.password 密码
+ * @param {String} params.nickname 昵称
+ * @param {Array} params.authorizedApp 允许登录的AppID列表
+ * @param {Array} params.role 用户角色列表
+ * @param {String} params.mobile 手机号
+ * @param {String} params.email 邮箱
+ * @param {Array} params.tags 用户标签
+ * @param {Number} params.status 用户状态
+ * @returns
+ */
+module.exports = async function (params = {}) {
+ const schema = {
+ uid: 'string',
+ username: 'username',
+ password: {
+ required: false,
+ type: 'password'
+ },
+ authorizedApp: {
+ required: false,
+ type: 'array'
+ }, // 指定允许登录的app,传空数组或不传时表示可以不可以在任何端登录
+ nickname: {
+ required: false,
+ type: 'nickname'
+ },
+ role: {
+ require: false,
+ type: 'array'
+ },
+ mobile: {
+ required: false,
+ type: 'mobile'
+ },
+ email: {
+ required: false,
+ type: 'email'
+ },
+ tags: {
+ required: false,
+ type: 'array'
+ },
+ status: {
+ required: false,
+ type: 'number'
+ }
+ }
+
+ this.middleware.validate(params, schema)
+
+ const {
+ uid,
+ username,
+ password,
+ authorizedApp,
+ nickname,
+ role,
+ mobile,
+ email,
+ tags,
+ status
+ } = params
+
+ // 更新的用户数据字段
+ const data = {
+ username,
+ dcloud_appid: authorizedApp || [],
+ nickname,
+ role: role || [],
+ mobile,
+ email,
+ tags: tags || [],
+ status
+ }
+
+ // 更新用户名时验证用户名是否重新
+ if (username) {
+ const userMatched = await findUser({
+ userQuery: {
+ username
+ },
+ authorizedApp
+ })
+ if (userMatched.filter(user => user._id !== uid).length) {
+ throw {
+ errCode: ERROR.ACCOUNT_EXISTS
+ }
+ }
+ }
+
+ if (password) {
+ const passwordUtils = new PasswordUtils({
+ passwordSecret: this.config.passwordSecret
+ })
+ const {
+ passwordHash,
+ version
+ } = passwordUtils.generatePasswordHash({
+ password
+ })
+
+ data.password = passwordHash
+ data.password_secret_version = version
+ }
+
+ await userCollection.doc(uid).update(data)
+
+ return {
+ errCode: 0
+ }
+}
diff --git a/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/module/logout/logout.js b/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/module/logout/logout.js
index 98f2ddacc8aa772d6d1f41cff01b736da7d07f16..7d491c61d3d3702a7370354ac4f8de217d9f1223 100644
--- a/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/module/logout/logout.js
+++ b/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/module/logout/logout.js
@@ -1,9 +1,6 @@
const {
- dbCmd,
- LOG_TYPE,
- deviceCollection,
- userCollection
-} = require('../../common/constants')
+ logout
+} = require('../../lib/utils/logout')
/**
* 用户退出登录
@@ -11,37 +8,7 @@ const {
* @returns
*/
module.exports = async function () {
- const {
- uniIdToken,
- deviceId
- } = this.getClientInfo()
- const {
- uid
- } = await this.uniIdCommon.checkToken(
- uniIdToken,
- {
- autoRefresh: false
- }
- )
-
- // 删除token
- await userCollection.doc(uid).update({
- token: dbCmd.pull(uniIdToken)
- })
-
- // 仅当device表的device_id和user_id均对应时才进行更新
- await deviceCollection.where({
- device_id: deviceId,
- user_id: uid
- }).update({
- token_expired: 0
- })
- await this.middleware.uniIdLog({
- data: {
- user_id: uid
- },
- type: LOG_TYPE.LOGOUT
- })
+ await logout.call(this)
return {
errCode: 0
}
diff --git a/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/module/multi-end/remove-authorized-app.js b/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/module/multi-end/remove-authorized-app.js
index 6334e537009c01745f7d947c9246712bfa012310..df82184fa2c9e26c5db32910ca2110a0cb81eab0 100644
--- a/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/module/multi-end/remove-authorized-app.js
+++ b/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/module/multi-end/remove-authorized-app.js
@@ -16,7 +16,7 @@ module.exports = async function (params = {}) {
uid: 'string',
appId: 'string'
}
- this.moddleware.validate(params, schema)
+ this.middleware.validate(params, schema)
const {
uid,
appId
diff --git a/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/package.json b/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/package.json
index e8f580ac652b9890d5ceefa469010f719b89fe11..9f49a13454551545d56427d2c4082227049dd5af 100644
--- a/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/package.json
+++ b/uni_modules/uni-id-pages/uniCloud/cloudfunctions/uni-id-co/package.json
@@ -1,6 +1,6 @@
{
"name": "uni-id-co",
- "version": "1.0.10",
+ "version": "1.0.12",
"description": "",
"main": "index.js",
"keywords": [],
diff --git a/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/bridge-error.js b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/bridge-error.js
index b6cfe66170d1958f57cee2e3715fc4984682c379..95160a4390ade5693feaf7aa226a7d9d13765db1 100644
--- a/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/bridge-error.js
+++ b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/bridge-error.js
@@ -1,4 +1,4 @@
-'use strict';
+'use strict';
class BridgeError extends Error {
@@ -20,7 +20,7 @@ class BridgeError extends Error {
return this.message
}
}
-
-module.exports = {
- BridgeError
+
+module.exports = {
+ BridgeError
}
diff --git a/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/config.js b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/config.js
index a08f9973d0b1215db4832bb79b294f733947d652..2fb7d7b050baa9e6af2b38af9fe8725c311a7aed 100644
--- a/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/config.js
+++ b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/config.js
@@ -1,95 +1,95 @@
-'use strict';
-
-const {
- PlatformType
-} = require('./consts.js')
-
-const configCenter = require('uni-config-center')
-
-const OauthConfig = {
- 'weixin-mp': ['mp-weixin', 'oauth', 'weixin'],
- 'weixin-h5': ['web', 'oauth', 'weixin-h5']
-}
-
-class ConfigBase {
-
- constructor() {
- this._ready = false
- this._uniId = null
-
- const uniIdConfig = configCenter({
- pluginId: 'uni-id'
- })
-
- this._uniId = uniIdConfig.config()
-
- this._ready = true
- }
-
- getAppConfig(appid) {
- if (Array.isArray(this._uniId)) {
- return this._uniId.find((item) => {
- return (item.dcloudAppid === appid)
- })
- }
- return this._uniId
- }
-
- get ready() {
- return this._ready
- }
-}
-
-class AppConfig extends ConfigBase {
-
- constructor() {
- super()
- }
-
- get(appid, platform) {
- if (!this.isSupport(platform)) {
- return null
- }
-
- let appConfig = this.getAppConfig(appid)
- if (!appConfig) {
- return null
- }
-
- return this.getOauthConfig(appConfig, platform)
- }
-
- isSupport(platformName) {
- return (AppConfig.Support_Platforms.indexOf(platformName) >= 0)
- }
-
- getOauthConfig(appConfig, platformName) {
- let tree = OauthConfig[platformName]
- let node = appConfig
- for (let i = 0; i < tree.length; i++) {
- let nodeName = tree[i]
- if (node[nodeName]) {
- node = node[nodeName]
- } else {
- node = null
- break
- }
- }
-
- if (node && node.appid && node.appsecret) {
- return {
- appid: node.appid,
- secret: node.appsecret
- }
- }
-
- return null
- }
-}
-
-AppConfig.Support_Platforms = [PlatformType.WEIXIN_MP, PlatformType.WEIXIN_H5]
-
-
-module.exports = {
- AppConfig
+'use strict';
+
+const {
+ PlatformType
+} = require('./consts.js')
+
+const configCenter = require('uni-config-center')
+
+const OauthConfig = {
+ 'weixin-mp': ['mp-weixin', 'oauth', 'weixin'],
+ 'weixin-h5': ['web', 'oauth', 'weixin-h5']
+}
+
+class ConfigBase {
+
+ constructor() {
+ this._ready = false
+ this._uniId = null
+
+ const uniIdConfig = configCenter({
+ pluginId: 'uni-id'
+ })
+
+ this._uniId = uniIdConfig.config()
+
+ this._ready = true
+ }
+
+ getAppConfig(appid) {
+ if (Array.isArray(this._uniId)) {
+ return this._uniId.find((item) => {
+ return (item.dcloudAppid === appid)
+ })
+ }
+ return this._uniId
+ }
+
+ get ready() {
+ return this._ready
+ }
+}
+
+class AppConfig extends ConfigBase {
+
+ constructor() {
+ super()
+ }
+
+ get(appid, platform) {
+ if (!this.isSupport(platform)) {
+ return null
+ }
+
+ let appConfig = this.getAppConfig(appid)
+ if (!appConfig) {
+ return null
+ }
+
+ return this.getOauthConfig(appConfig, platform)
+ }
+
+ isSupport(platformName) {
+ return (AppConfig.Support_Platforms.indexOf(platformName) >= 0)
+ }
+
+ getOauthConfig(appConfig, platformName) {
+ let tree = OauthConfig[platformName]
+ let node = appConfig
+ for (let i = 0; i < tree.length; i++) {
+ let nodeName = tree[i]
+ if (node[nodeName]) {
+ node = node[nodeName]
+ } else {
+ node = null
+ break
+ }
+ }
+
+ if (node && node.appid && node.appsecret) {
+ return {
+ appid: node.appid,
+ secret: node.appsecret
+ }
+ }
+
+ return null
+ }
+}
+
+AppConfig.Support_Platforms = [PlatformType.WEIXIN_MP, PlatformType.WEIXIN_H5]
+
+
+module.exports = {
+ AppConfig
};
diff --git a/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/consts.js b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/consts.js
index 32077bc90cc55b6a2d5a1dec8eb746933a154d1f..6da817b9620336453e06025815a12d378249ebde 100644
--- a/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/consts.js
+++ b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/consts.js
@@ -1,19 +1,26 @@
-'use strict';
-
-const HTTP_STATUS = {
- SUCCESS: 200
-}
-
-const PlatformType = {
- WEIXIN_MP: 'weixin-mp',
- WEIXIN_H5: 'weixin-h5',
- WEIXIN_APP: 'weixin-app',
- WEIXIN_WEB: 'weixin-web',
- QQ_MP: 'qq-mp',
- QQ_APP: 'qq-app'
-}
-
-module.exports = {
- HTTP_STATUS,
- PlatformType
+'use strict';
+
+const TAG = "UNI_OPEN_BRIDGE"
+
+const HTTP_STATUS = {
+ SUCCESS: 200
+}
+
+const PlatformType = {
+ WEIXIN_MP: 'weixin-mp',
+ WEIXIN_H5: 'weixin-h5',
+ WEIXIN_APP: 'weixin-app',
+ WEIXIN_WEB: 'weixin-web',
+ QQ_MP: 'qq-mp',
+ QQ_APP: 'qq-app'
+}
+
+const ErrorCodeType = {
+ SYSTEM_ERROR: TAG + "_SYSTEM_ERROR"
+}
+
+module.exports = {
+ HTTP_STATUS,
+ PlatformType,
+ ErrorCodeType
}
diff --git a/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/index.js b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/index.js
index d1c1c62a9f67add06dda1247486bdb89dd2c3280..c6b3daff15392b1d351235a769f2011ed8e2e314 100644
--- a/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/index.js
+++ b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/index.js
@@ -1,210 +1,219 @@
-'use strict';
-
-const {
- PlatformType
-} = require('./consts.js')
-
-const {
- AppConfig
-} = require('./config.js')
-
-const {
- Storage,
- Factory
-} = require('./storage.js')
-
-const {
- BridgeError
-} = require('./bridge-error.js')
-
-const {
- WeixinServer
-} = require('./weixin-server.js')
-
-const appConfig = new AppConfig()
-
-class AccessToken extends Storage {
-
- constructor() {
- super('access-token', ['dcloudAppid', 'platform'])
- }
-
- async fallback(parameters) {
- const oauthConfig = appConfig.get(parameters.dcloudAppid, parameters.platform)
- const methodName = (parameters.platform === PlatformType.WEIXIN_MP) ? 'GetMPAccessTokenData' :
- 'GetH5AccessTokenData'
- const responseData = await WeixinServer[methodName](oauthConfig)
-
- const duration = responseData.expires_in
- delete responseData.expires_in
-
- return {
- value: responseData,
- duration
- }
- }
-}
-
-class UserAccessToken extends Storage {
-
- constructor() {
- super('user-access-token', ['dcloudAppid', 'platform', 'openid'])
- }
-}
-
-class SessionKey extends Storage {
-
- constructor() {
- super('session-key', ['dcloudAppid', 'platform', 'openid'])
- }
-}
-
-class Encryptkey extends Storage {
-
- constructor() {
- super('encrypt-key', ['dcloudAppid', 'platform', 'openid'])
- }
-
- getKeyString(key) {
- return `${super.getKeyString(key)}-${key.version}`
- }
-
- getExpiresIn(value) {
- if (value <= 0) {
- return 60
- }
- return value
- }
-
- async fallback(parameters) {
- const accessToken = await Factory.Get(AccessToken, parameters)
- const userSession = await Factory.Get(SessionKey, parameters)
-
- const responseData = await WeixinServer.GetUserEncryptKeyData({
- openid: parameters.openid,
- access_token: accessToken.access_token,
- session_key: userSession.session_key
- })
-
- const keyInfo = responseData.key_info_list.find((item) => {
- return item.version = parameters.version
- })
-
- const value = {
- encrypt_key: keyInfo.encrypt_key,
- iv: keyInfo.iv
- }
-
- return {
- value,
- duration: keyInfo.expire_in
- }
- }
-}
-
-class Ticket extends Storage {
-
- constructor() {
- super('ticket', ['dcloudAppid', 'platform'])
- }
-
- async fallback(parameters) {
- const accessToken = await Factory.Get(AccessToken, {
- dcloudAppid: parameters.dcloudAppid,
- platform: PlatformType.WEIXIN_H5
- })
-
- const responseData = await WeixinServer.GetH5TicketData(accessToken)
-
- const duration = responseData.expires_in
- delete responseData.expires_in
-
- return {
- value: responseData,
- duration
- }
- }
-}
-
-
-// exports
-
-async function getAccessToken(key, fallback) {
- return await Factory.Get(AccessToken, key, fallback)
-}
-
-async function setAccessToken(key, value, expiresIn) {
- await Factory.Set(AccessToken, key, value, expiresIn)
-}
-
-async function removeAccessToken(key) {
- await Factory.Remove(AccessToken, key)
-}
-
-async function getUserAccessToken(key, fallback) {
- return await Factory.Get(UserAccessToken, key, fallback)
-}
-
-async function setUserAccessToken(key, value, expiresIn) {
- await Factory.Set(UserAccessToken, key, value, expiresIn)
-}
-
-async function removeUserAccessToken(key) {
- await Factory.Remove(UserAccessToken, key)
-}
-
-async function getSessionKey(key, fallback) {
- return await Factory.Get(SessionKey, key, fallback)
-}
-
-async function setSessionKey(key, value, expiresIn) {
- await Factory.Set(SessionKey, key, value, expiresIn)
-}
-
-async function removeSessionKey(key) {
- await Factory.Remove(SessionKey, key)
-}
-
-async function getEncryptKey(key, fallback) {
- return await Factory.Get(Encryptkey, key, fallback)
-}
-
-async function setEncryptKey(key, value, expiresIn) {
- await Factory.Set(Encryptkey, key, value, expiresIn)
-}
-
-async function removeEncryptKey(key) {
- await Factory.Remove(Encryptkey, key)
-}
-
-async function getTicket(key, fallback) {
- return await Factory.Get(Ticket, key, fallback)
-}
-
-async function setTicket(key, value, expiresIn) {
- await Factory.Set(Ticket, key, value, expiresIn)
-}
-
-async function removeTicket(key) {
- await Factory.Remove(Ticket, key)
-}
-
-module.exports = {
- getAccessToken,
- setAccessToken,
- removeAccessToken,
- getUserAccessToken,
- setUserAccessToken,
- removeUserAccessToken,
- getSessionKey,
- setSessionKey,
- removeSessionKey,
- getEncryptKey,
- setEncryptKey,
- removeEncryptKey,
- getTicket,
- setTicket,
- removeTicket,
- PlatformType,
- WeixinServer
+'use strict';
+
+const {
+ PlatformType,
+ ErrorCodeType
+} = require('./consts.js')
+
+const {
+ AppConfig
+} = require('./config.js')
+
+const {
+ Storage,
+ Factory
+} = require('./storage.js')
+
+const {
+ BridgeError
+} = require('./bridge-error.js')
+
+const {
+ WeixinServer
+} = require('./weixin-server.js')
+
+const appConfig = new AppConfig()
+
+class AccessToken extends Storage {
+
+ constructor() {
+ super('access-token', ['dcloudAppid', 'platform'])
+ }
+
+ async fallback(parameters) {
+ const oauthConfig = appConfig.get(parameters.dcloudAppid, parameters.platform)
+ let methodName
+ if (parameters.platform === PlatformType.WEIXIN_MP) {
+ methodName = 'GetMPAccessTokenData'
+ } else if (parameters.platform === PlatformType.WEIXIN_H5) {
+ methodName = 'GetH5AccessTokenData'
+ } else {
+ throw new BridgeError(ErrorCodeType.SYSTEM_ERROR, "platform invalid")
+ }
+
+ const responseData = await WeixinServer[methodName](oauthConfig)
+
+ const duration = responseData.expires_in
+ delete responseData.expires_in
+
+ return {
+ value: responseData,
+ duration
+ }
+ }
+}
+
+class UserAccessToken extends Storage {
+
+ constructor() {
+ super('user-access-token', ['dcloudAppid', 'platform', 'openid'])
+ }
+}
+
+class SessionKey extends Storage {
+
+ constructor() {
+ super('session-key', ['dcloudAppid', 'platform', 'openid'])
+ }
+}
+
+class Encryptkey extends Storage {
+
+ constructor() {
+ super('encrypt-key', ['dcloudAppid', 'platform', 'openid'])
+ }
+
+ getKeyString(key) {
+ return `${super.getKeyString(key)}-${key.version}`
+ }
+
+ getExpiresIn(value) {
+ if (value <= 0) {
+ return 60
+ }
+ return value
+ }
+
+ async fallback(parameters) {
+ const accessToken = await Factory.Get(AccessToken, parameters)
+ const userSession = await Factory.Get(SessionKey, parameters)
+
+ const responseData = await WeixinServer.GetUserEncryptKeyData({
+ openid: parameters.openid,
+ access_token: accessToken.access_token,
+ session_key: userSession.session_key
+ })
+
+ const keyInfo = responseData.key_info_list.find((item) => {
+ return item.version = parameters.version
+ })
+
+ const value = {
+ encrypt_key: keyInfo.encrypt_key,
+ iv: keyInfo.iv
+ }
+
+ return {
+ value,
+ duration: keyInfo.expire_in
+ }
+ }
+}
+
+class Ticket extends Storage {
+
+ constructor() {
+ super('ticket', ['dcloudAppid', 'platform'])
+ }
+
+ async fallback(parameters) {
+ const accessToken = await Factory.Get(AccessToken, {
+ dcloudAppid: parameters.dcloudAppid,
+ platform: PlatformType.WEIXIN_H5
+ })
+
+ const responseData = await WeixinServer.GetH5TicketData(accessToken)
+
+ const duration = responseData.expires_in
+ delete responseData.expires_in
+
+ return {
+ value: responseData,
+ duration
+ }
+ }
+}
+
+
+// exports
+
+async function getAccessToken(key, fallback) {
+ return await Factory.Get(AccessToken, key, fallback)
+}
+
+async function setAccessToken(key, value, expiresIn) {
+ await Factory.Set(AccessToken, key, value, expiresIn)
+}
+
+async function removeAccessToken(key) {
+ await Factory.Remove(AccessToken, key)
+}
+
+async function getUserAccessToken(key, fallback) {
+ return await Factory.Get(UserAccessToken, key, fallback)
+}
+
+async function setUserAccessToken(key, value, expiresIn) {
+ await Factory.Set(UserAccessToken, key, value, expiresIn)
+}
+
+async function removeUserAccessToken(key) {
+ await Factory.Remove(UserAccessToken, key)
+}
+
+async function getSessionKey(key, fallback) {
+ return await Factory.Get(SessionKey, key, fallback)
+}
+
+async function setSessionKey(key, value, expiresIn) {
+ await Factory.Set(SessionKey, key, value, expiresIn)
+}
+
+async function removeSessionKey(key) {
+ await Factory.Remove(SessionKey, key)
+}
+
+async function getEncryptKey(key, fallback) {
+ return await Factory.Get(Encryptkey, key, fallback)
+}
+
+async function setEncryptKey(key, value, expiresIn) {
+ await Factory.Set(Encryptkey, key, value, expiresIn)
+}
+
+async function removeEncryptKey(key) {
+ await Factory.Remove(Encryptkey, key)
+}
+
+async function getTicket(key, fallback) {
+ return await Factory.Get(Ticket, key, fallback)
+}
+
+async function setTicket(key, value, expiresIn) {
+ await Factory.Set(Ticket, key, value, expiresIn)
+}
+
+async function removeTicket(key) {
+ await Factory.Remove(Ticket, key)
+}
+
+module.exports = {
+ getAccessToken,
+ setAccessToken,
+ removeAccessToken,
+ getUserAccessToken,
+ setUserAccessToken,
+ removeUserAccessToken,
+ getSessionKey,
+ setSessionKey,
+ removeSessionKey,
+ getEncryptKey,
+ setEncryptKey,
+ removeEncryptKey,
+ getTicket,
+ setTicket,
+ removeTicket,
+ PlatformType,
+ WeixinServer,
+ ErrorCodeType
}
diff --git a/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/storage.js b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/storage.js
index 8345be39c7032bab675371443610261377a8f9ef..b7395602c50e8e0a626c9b22f791c99835d2f2a8 100644
--- a/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/storage.js
+++ b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/storage.js
@@ -1,117 +1,117 @@
-'use strict';
-
-const {
- Validator
-} = require('./validator.js')
-
-const {
- CacheKeyCascade
-} = require('./uni-cloud-cache.js')
-
-class Storage {
-
- constructor(type, keys) {
- this._type = type || null
- this._keys = keys || []
- }
-
- async get(key, fallback) {
- this.validateKey(key)
- const result = await this.create(key, fallback).get()
- return result.value
- }
-
- async set(key, value, expiresIn) {
- this.validateKey(key)
- this.validateValue(value)
- const expires_in = this.getExpiresIn(expiresIn)
- if (expires_in !== 0) {
- await this.create(key).set(this.getValue(value), expires_in)
- }
- }
-
- async remove(key) {
- this.validateKey(key)
- await this.create(key).remove()
- }
-
- async ttl(key) {
- this.validateKey(key)
- // 后续考虑支持
- }
-
- getKeyString(key) {
- const keyArray = [Storage.Prefix]
- this._keys.forEach((name) => {
- keyArray.push(key[name])
- })
- keyArray.push(this._type)
- return keyArray.join(':')
- }
-
- getValue(value) {
- return value
- }
-
- getExpiresIn(value) {
- if (value !== undefined) {
- return value
- }
- return -1
- }
-
- validateKey(key) {
- Validator.Key(this._keys, key)
- }
-
- validateValue(value) {
- Validator.Value(value)
- }
-
- create(key, fallback) {
- const keyString = this.getKeyString(key)
- const options = {
- layers: [{
- type: 'database',
- key: keyString
- }, {
- type: 'redis',
- key: keyString
- }]
- }
- if (fallback !== null) {
- const fallbackFunction = fallback || this.fallback
- if (fallbackFunction) {
- options.fallback = async () => {
- return await fallbackFunction(key)
- }
- }
- }
- return new CacheKeyCascade(options)
- }
-}
-Storage.Prefix = "uni-id"
-
-const Factory = {
-
- async Get(T, key, fallback) {
- return await Factory.MakeUnique(T).get(key, fallback)
- },
-
- async Set(T, key, value, expiresIn) {
- await Factory.MakeUnique(T).set(key, value, expiresIn)
- },
-
- async Remove(T, key) {
- await Factory.MakeUnique(T).remove(key)
- },
-
- MakeUnique(T) {
- return new T()
- }
-}
-
-module.exports = {
- Storage,
- Factory
+'use strict';
+
+const {
+ Validator
+} = require('./validator.js')
+
+const {
+ CacheKeyCascade
+} = require('./uni-cloud-cache.js')
+
+class Storage {
+
+ constructor(type, keys) {
+ this._type = type || null
+ this._keys = keys || []
+ }
+
+ async get(key, fallback) {
+ this.validateKey(key)
+ const result = await this.create(key, fallback).get()
+ return result.value
+ }
+
+ async set(key, value, expiresIn) {
+ this.validateKey(key)
+ this.validateValue(value)
+ const expires_in = this.getExpiresIn(expiresIn)
+ if (expires_in !== 0) {
+ await this.create(key).set(this.getValue(value), expires_in)
+ }
+ }
+
+ async remove(key) {
+ this.validateKey(key)
+ await this.create(key).remove()
+ }
+
+ async ttl(key) {
+ this.validateKey(key)
+ // 后续考虑支持
+ }
+
+ getKeyString(key) {
+ const keyArray = [Storage.Prefix]
+ this._keys.forEach((name) => {
+ keyArray.push(key[name])
+ })
+ keyArray.push(this._type)
+ return keyArray.join(':')
+ }
+
+ getValue(value) {
+ return value
+ }
+
+ getExpiresIn(value) {
+ if (value !== undefined) {
+ return value
+ }
+ return -1
+ }
+
+ validateKey(key) {
+ Validator.Key(this._keys, key)
+ }
+
+ validateValue(value) {
+ Validator.Value(value)
+ }
+
+ create(key, fallback) {
+ const keyString = this.getKeyString(key)
+ const options = {
+ layers: [{
+ type: 'database',
+ key: keyString
+ }, {
+ type: 'redis',
+ key: keyString
+ }]
+ }
+ if (fallback !== null) {
+ const fallbackFunction = fallback || this.fallback
+ if (fallbackFunction) {
+ options.fallback = async () => {
+ return await fallbackFunction(key)
+ }
+ }
+ }
+ return new CacheKeyCascade(options)
+ }
+}
+Storage.Prefix = "uni-id"
+
+const Factory = {
+
+ async Get(T, key, fallback) {
+ return await Factory.MakeUnique(T).get(key, fallback)
+ },
+
+ async Set(T, key, value, expiresIn) {
+ await Factory.MakeUnique(T).set(key, value, expiresIn)
+ },
+
+ async Remove(T, key) {
+ await Factory.MakeUnique(T).remove(key)
+ },
+
+ MakeUnique(T) {
+ return new T()
+ }
+}
+
+module.exports = {
+ Storage,
+ Factory
};
diff --git a/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/uni-cloud-cache.js b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/uni-cloud-cache.js
index f17044fd654d6d3655e1ca311c9678d308c59057..075093273414e8b8da1c3250b491a7896f7a1ae2 100644
--- a/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/uni-cloud-cache.js
+++ b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/uni-cloud-cache.js
@@ -1,324 +1,324 @@
-const db = uniCloud.database()
-
-function getType(value) {
- return Object.prototype.toString.call(value).slice(8, -1).toLowerCase()
-}
-
-const validator = {
- key: function(value) {
- const err = new Error('Invalid key')
- if (typeof value !== 'string') {
- throw err
- }
- const valueTrim = value.trim()
- if (!valueTrim || valueTrim !== value) {
- throw err
- }
- },
- value: function(value) {
- // 仅作简单校验
- const type = getType(value)
- const validValueType = ['null', 'number', 'string', 'array', 'object']
- if (validValueType.indexOf(type) === -1) {
- throw new Error('Invalid value type')
- }
- },
- duration: function(value) {
- const err = new Error('Invalid duration')
- if (value === undefined) {
- return
- }
- if (typeof value !== 'number' || value === 0) {
- throw err
- }
- }
-}
-
-/**
- * 入库时 expired 为过期时间对应的时间戳,永不过期用-1表示
- * 返回结果时 与redis对齐,-1表示永不过期,-2表示已过期或不存在
- */
-class DatabaseCache {
- constructor({
- collection = 'opendb-open-data'
- } = {}) {
- this.type = 'db'
- this.collection = db.collection(collection)
- }
-
- _serializeValue(value) {
- return value === undefined ? null : JSON.stringify(value)
- }
-
- _deserializeValue(value) {
- return value ? JSON.parse(value) : value
- }
-
- async set(key, value, duration) {
- validator.key(key)
- validator.value(value)
- validator.duration(duration)
- value = this._serializeValue(value)
- await this.collection.doc(key).set({
- value,
- expired: duration && duration !== -1 ? Date.now() + duration : -1
- })
- }
-
- async _getWithDuration(key) {
- const getKeyRes = await this.collection.doc(key).get()
- const record = getKeyRes.data[0]
- if (!record) {
- return {
- value: null,
- duration: -2
- }
- }
- const value = this._deserializeValue(record.value)
- const expired = record.expired
- if (expired === -1) {
- return {
- value,
- duration: -1
- }
- }
- const duration = expired - Date.now()
- if (duration <= 0) {
- await this.remove(key)
- return {
- value: null,
- duration: -2
- }
- }
- return {
- value,
- duration: Math.floor(duration / 1000)
- }
- }
-
- async get(key, {
- withDuration = true
- } = {}) {
- const result = await this._getWithDuration(key)
- if (!withDuration) {
- delete result.duration
- }
- return result
- }
-
- async remove(key) {
- await this.collection.doc(key).remove()
- }
-}
-
-class RedisCache {
- constructor() {
- this.type = 'redis'
- this.redis = uniCloud.redis()
- }
-
- _serializeValue(value) {
- return value === undefined ? null : JSON.stringify(value)
- }
-
- _deserializeValue(value) {
- return value ? JSON.parse(value) : value
- }
-
- async set(key, value, duration) {
- validator.key(key)
- validator.value(value)
- validator.duration(duration)
- value = this._serializeValue(value)
- if (!duration || duration === -1) {
- await this.redis.set(key, value)
- } else {
- await this.redis.set(key, value, 'EX', duration)
- }
- }
-
- async get(key, {
- withDuration = false
- } = {}) {
- let value = await this.redis.get(key)
- value = this._deserializeValue(value)
- if (!withDuration) {
- return {
- value
- }
- }
- const durationSecond = await this.redis.ttl(key)
- let duration
- switch (durationSecond) {
- case -1:
- duration = -1
- break
- case -2:
- duration = -2
- break
- default:
- duration = durationSecond
- break
- }
- return {
- value,
- duration
- }
- }
-
- async remove(key) {
- await this.redis.del(key)
- }
-}
-
-class Cache {
- constructor({
- type,
- collection
- } = {}) {
- if (type === 'database') {
- return new DatabaseCache({
- collection
- })
- } else if (type === 'redis') {
- return new RedisCache()
- } else {
- throw new Error('Invalid cache type')
- }
- }
-}
-
-class CacheKey {
- constructor({
- type,
- collection,
- cache,
- key,
- fallback
- } = {}) {
- this.cache = cache || new Cache({
- type,
- collection
- })
- this.key = key
- this.fallback = fallback
- }
-
- async set(value, duration) {
- await this.cache.set(this.key, value, duration)
- }
-
- async setWithSync(value, duration, syncMethod) {
- await Promise.all([
- this.set(this.key, value, duration),
- syncMethod(value, duration)
- ])
- }
-
- async get() {
- let {
- value,
- duration
- } = await this.cache.get(this.key)
- if (value !== null && value !== undefined) {
- return {
- value,
- duration
- }
- }
- if (!this.fallback) {
- return {
- value: null,
- duration: -2
- }
- }
- const fallbackResult = await this.fallback()
- value = fallbackResult.value
- duration = fallbackResult.duration
- if (value !== null && duration !== undefined) {
- await this.cache.set(this.key, value, duration)
- }
- return {
- value,
- duration
- }
- }
-
- async remove() {
- await this.cache.remove(this.key)
- }
-}
-
-class CacheKeyCascade {
- constructor({
- layers, // [{cache, type, collection, key}] 从低级到高级排序,[DbCacheKey, RedisCacheKey]
- fallback
- } = {}) {
- this.layers = layers
- this.cacheLayers = []
- let lastCacheKey
- for (let i = 0; i < layers.length; i++) {
- const {
- type,
- cache,
- collection,
- key
- } = layers[i]
- const lastCacheKeyTemp = lastCacheKey
- try {
- const currentCacheKey = new CacheKey({
- type,
- collection,
- cache,
- key,
- fallback: i === 0 ? fallback : function() {
- return lastCacheKeyTemp.get()
- }
- })
- this.cacheLayers.push(currentCacheKey)
- lastCacheKey = currentCacheKey
- } catch (e) {}
- }
- this.highLevelCache = lastCacheKey
- }
-
- async set(value, duration) {
- return Promise.all(
- this.cacheLayers.map(item => {
- return item.set(value, duration)
- })
- )
- }
-
- async setWithSync(value, duration, syncMethod) {
- const setPromise = this.cacheLayers.map(item => {
- return item.set(value, duration)
- })
- return Promise.all(
- [
- ...setPromise,
- syncMethod(value, duration)
- ]
- )
- }
-
- async get() {
- return this.highLevelCache.get()
- }
-
- async remove() {
- await Promise.all(
- this.cacheLayers.map(cacheKeyItem => {
- return cacheKeyItem.remove()
- })
- )
- }
-}
-
-module.exports = {
- Cache,
- DatabaseCache,
- RedisCache,
- CacheKey,
- CacheKeyCascade
+const db = uniCloud.database()
+
+function getType(value) {
+ return Object.prototype.toString.call(value).slice(8, -1).toLowerCase()
+}
+
+const validator = {
+ key: function(value) {
+ const err = new Error('Invalid key')
+ if (typeof value !== 'string') {
+ throw err
+ }
+ const valueTrim = value.trim()
+ if (!valueTrim || valueTrim !== value) {
+ throw err
+ }
+ },
+ value: function(value) {
+ // 仅作简单校验
+ const type = getType(value)
+ const validValueType = ['null', 'number', 'string', 'array', 'object']
+ if (validValueType.indexOf(type) === -1) {
+ throw new Error('Invalid value type')
+ }
+ },
+ duration: function(value) {
+ const err = new Error('Invalid duration')
+ if (value === undefined) {
+ return
+ }
+ if (typeof value !== 'number' || value === 0) {
+ throw err
+ }
+ }
+}
+
+/**
+ * 入库时 expired 为过期时间对应的时间戳,永不过期用-1表示
+ * 返回结果时 与redis对齐,-1表示永不过期,-2表示已过期或不存在
+ */
+class DatabaseCache {
+ constructor({
+ collection = 'opendb-open-data'
+ } = {}) {
+ this.type = 'db'
+ this.collection = db.collection(collection)
+ }
+
+ _serializeValue(value) {
+ return value === undefined ? null : JSON.stringify(value)
+ }
+
+ _deserializeValue(value) {
+ return value ? JSON.parse(value) : value
+ }
+
+ async set(key, value, duration) {
+ validator.key(key)
+ validator.value(value)
+ validator.duration(duration)
+ value = this._serializeValue(value)
+ await this.collection.doc(key).set({
+ value,
+ expired: duration && duration !== -1 ? Date.now() + duration : -1
+ })
+ }
+
+ async _getWithDuration(key) {
+ const getKeyRes = await this.collection.doc(key).get()
+ const record = getKeyRes.data[0]
+ if (!record) {
+ return {
+ value: null,
+ duration: -2
+ }
+ }
+ const value = this._deserializeValue(record.value)
+ const expired = record.expired
+ if (expired === -1) {
+ return {
+ value,
+ duration: -1
+ }
+ }
+ const duration = expired - Date.now()
+ if (duration <= 0) {
+ await this.remove(key)
+ return {
+ value: null,
+ duration: -2
+ }
+ }
+ return {
+ value,
+ duration: Math.floor(duration / 1000)
+ }
+ }
+
+ async get(key, {
+ withDuration = true
+ } = {}) {
+ const result = await this._getWithDuration(key)
+ if (!withDuration) {
+ delete result.duration
+ }
+ return result
+ }
+
+ async remove(key) {
+ await this.collection.doc(key).remove()
+ }
+}
+
+class RedisCache {
+ constructor() {
+ this.type = 'redis'
+ this.redis = uniCloud.redis()
+ }
+
+ _serializeValue(value) {
+ return value === undefined ? null : JSON.stringify(value)
+ }
+
+ _deserializeValue(value) {
+ return value ? JSON.parse(value) : value
+ }
+
+ async set(key, value, duration) {
+ validator.key(key)
+ validator.value(value)
+ validator.duration(duration)
+ value = this._serializeValue(value)
+ if (!duration || duration === -1) {
+ await this.redis.set(key, value)
+ } else {
+ await this.redis.set(key, value, 'EX', duration)
+ }
+ }
+
+ async get(key, {
+ withDuration = false
+ } = {}) {
+ let value = await this.redis.get(key)
+ value = this._deserializeValue(value)
+ if (!withDuration) {
+ return {
+ value
+ }
+ }
+ const durationSecond = await this.redis.ttl(key)
+ let duration
+ switch (durationSecond) {
+ case -1:
+ duration = -1
+ break
+ case -2:
+ duration = -2
+ break
+ default:
+ duration = durationSecond
+ break
+ }
+ return {
+ value,
+ duration
+ }
+ }
+
+ async remove(key) {
+ await this.redis.del(key)
+ }
+}
+
+class Cache {
+ constructor({
+ type,
+ collection
+ } = {}) {
+ if (type === 'database') {
+ return new DatabaseCache({
+ collection
+ })
+ } else if (type === 'redis') {
+ return new RedisCache()
+ } else {
+ throw new Error('Invalid cache type')
+ }
+ }
+}
+
+class CacheKey {
+ constructor({
+ type,
+ collection,
+ cache,
+ key,
+ fallback
+ } = {}) {
+ this.cache = cache || new Cache({
+ type,
+ collection
+ })
+ this.key = key
+ this.fallback = fallback
+ }
+
+ async set(value, duration) {
+ await this.cache.set(this.key, value, duration)
+ }
+
+ async setWithSync(value, duration, syncMethod) {
+ await Promise.all([
+ this.set(this.key, value, duration),
+ syncMethod(value, duration)
+ ])
+ }
+
+ async get() {
+ let {
+ value,
+ duration
+ } = await this.cache.get(this.key)
+ if (value !== null && value !== undefined) {
+ return {
+ value,
+ duration
+ }
+ }
+ if (!this.fallback) {
+ return {
+ value: null,
+ duration: -2
+ }
+ }
+ const fallbackResult = await this.fallback()
+ value = fallbackResult.value
+ duration = fallbackResult.duration
+ if (value !== null && duration !== undefined) {
+ await this.cache.set(this.key, value, duration)
+ }
+ return {
+ value,
+ duration
+ }
+ }
+
+ async remove() {
+ await this.cache.remove(this.key)
+ }
+}
+
+class CacheKeyCascade {
+ constructor({
+ layers, // [{cache, type, collection, key}] 从低级到高级排序,[DbCacheKey, RedisCacheKey]
+ fallback
+ } = {}) {
+ this.layers = layers
+ this.cacheLayers = []
+ let lastCacheKey
+ for (let i = 0; i < layers.length; i++) {
+ const {
+ type,
+ cache,
+ collection,
+ key
+ } = layers[i]
+ const lastCacheKeyTemp = lastCacheKey
+ try {
+ const currentCacheKey = new CacheKey({
+ type,
+ collection,
+ cache,
+ key,
+ fallback: i === 0 ? fallback : function() {
+ return lastCacheKeyTemp.get()
+ }
+ })
+ this.cacheLayers.push(currentCacheKey)
+ lastCacheKey = currentCacheKey
+ } catch (e) {}
+ }
+ this.highLevelCache = lastCacheKey
+ }
+
+ async set(value, duration) {
+ return Promise.all(
+ this.cacheLayers.map(item => {
+ return item.set(value, duration)
+ })
+ )
+ }
+
+ async setWithSync(value, duration, syncMethod) {
+ const setPromise = this.cacheLayers.map(item => {
+ return item.set(value, duration)
+ })
+ return Promise.all(
+ [
+ ...setPromise,
+ syncMethod(value, duration)
+ ]
+ )
+ }
+
+ async get() {
+ return this.highLevelCache.get()
+ }
+
+ async remove() {
+ await Promise.all(
+ this.cacheLayers.map(cacheKeyItem => {
+ return cacheKeyItem.remove()
+ })
+ )
+ }
+}
+
+module.exports = {
+ Cache,
+ DatabaseCache,
+ RedisCache,
+ CacheKey,
+ CacheKeyCascade
}
diff --git a/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/validator.js b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/validator.js
index 231dc8b14e84201e4a16a7de2366c4d137eb781f..47a455b15a479ce608838731287f5776985e191c 100644
--- a/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/validator.js
+++ b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/validator.js
@@ -1,31 +1,31 @@
-const Validator = {
-
- Key(keyArray, parameters) {
- for (let i = 0; i < keyArray.length; i++) {
- const keyName = keyArray[i]
- if (typeof parameters[keyName] !== 'string') {
- Validator.ThrowNewError(`Invalid ${keyName}`)
- }
- if (parameters[keyName].length < 1) {
- Validator.ThrowNewError(`Invalid ${keyName}`)
- }
- }
- },
-
- Value(value) {
- if (value === undefined) {
- Validator.ThrowNewError('Invalid Value')
- }
- if (typeof value !== 'object') {
- Validator.ThrowNewError('Invalid Value Type')
- }
- },
-
- ThrowNewError(message) {
- throw new Error(message)
- }
-}
-
-module.exports = {
- Validator
+const Validator = {
+
+ Key(keyArray, parameters) {
+ for (let i = 0; i < keyArray.length; i++) {
+ const keyName = keyArray[i]
+ if (typeof parameters[keyName] !== 'string') {
+ Validator.ThrowNewError(`Invalid ${keyName}`)
+ }
+ if (parameters[keyName].length < 1) {
+ Validator.ThrowNewError(`Invalid ${keyName}`)
+ }
+ }
+ },
+
+ Value(value) {
+ if (value === undefined) {
+ Validator.ThrowNewError('Invalid Value')
+ }
+ if (typeof value !== 'object') {
+ Validator.ThrowNewError('Invalid Value Type')
+ }
+ },
+
+ ThrowNewError(message) {
+ throw new Error(message)
+ }
+}
+
+module.exports = {
+ Validator
}
diff --git a/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/weixin-server.js b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/weixin-server.js
index 28d695d74794fbc48095d962abb44ec9f0e1cc78..f405bc2c21d631cc9a27cb6b5ebf0f2f53f2d509 100644
--- a/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/weixin-server.js
+++ b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/weixin-server.js
@@ -1,161 +1,161 @@
-'use strict';
-
-const crypto = require('crypto')
-
-const {
- HTTP_STATUS
-} = require('./consts.js')
-
-const {
- BridgeError
-} = require('./bridge-error.js')
-
-class WeixinServer {
-
- constructor(options = {}) {
- this._appid = options.appid
- this._secret = options.secret
- }
-
- getAccessToken() {
- return uniCloud.httpclient.request(WeixinServer.AccessToken_Url, {
- dataType: 'json',
- method: 'POST',
- data: {
- appid: this._appid,
- secret: this._secret,
- grant_type: "client_credential"
- }
- })
- }
-
- // 使用客户端获取的 code 从微信服务器换取 openid,code 仅可使用一次
- codeToSession(code) {
- return uniCloud.httpclient.request(WeixinServer.Code2Session_Url, {
- dataType: 'json',
- data: {
- appid: this._appid,
- secret: this._secret,
- js_code: code,
- grant_type: 'authorization_code'
- }
- })
- }
-
- getUserEncryptKey({
- access_token,
- openid,
- session_key
- }) {
- console.log(access_token, openid, session_key);
- const signature = crypto.createHmac('sha256', session_key).update('').digest('hex')
- return uniCloud.httpclient.request(WeixinServer.User_Encrypt_Key_Url, {
- dataType: 'json',
- method: 'POST',
- dataAsQueryString: true,
- data: {
- access_token,
- openid: openid,
- signature: signature,
- sig_method: 'hmac_sha256'
- }
- })
- }
-
- getAccessTokenH5() {
- return uniCloud.httpclient.request(WeixinServer.AccessToken_H5_Url, {
- dataType: 'json',
- method: 'GET',
- data: {
- appid: this._appid,
- secret: this._secret,
- grant_type: "client_credential"
- }
- })
- }
-
- getTicket(access_token) {
- return uniCloud.httpclient.request(WeixinServer.Ticket_Url, {
- dataType: 'json',
- dataAsQueryString: true,
- method: 'POST',
- data: {
- access_token
- }
- })
- }
-}
-
-WeixinServer.AccessToken_Url = 'https://api.weixin.qq.com/cgi-bin/token'
-WeixinServer.Code2Session_Url = 'https://api.weixin.qq.com/sns/jscode2session'
-WeixinServer.User_Encrypt_Key_Url = 'https://api.weixin.qq.com/wxa/business/getuserencryptkey'
-WeixinServer.AccessToken_H5_Url = 'https://api.weixin.qq.com/cgi-bin/token'
-WeixinServer.Ticket_Url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi'
-
-WeixinServer.GetMPAccessToken = function(options) {
- return new WeixinServer(options).getAccessToken()
-}
-
-WeixinServer.GetCodeToSession = function(options) {
- return new WeixinServer(options).codeToSession(options.code)
-}
-
-WeixinServer.GetUserEncryptKey = function(options) {
- return new WeixinServer(options).getUserEncryptKey(options)
-}
-
-WeixinServer.GetH5AccessToken = function(options) {
- return new WeixinServer(options).getAccessTokenH5()
-}
-
-WeixinServer.GetH5Ticket = function(options) {
- return new WeixinServer(options).getTicket(options.access_token)
-}
-
-////////////////////////////////////////////////////////////////
-
-WeixinServer.GetResponseData = function(response) {
- console.log("WeixinServer::response", response)
-
- if (response.status !== HTTP_STATUS.SUCCESS) {
- throw new BridgeError(response.status, response.status)
- }
-
- const responseData = response.data
-
- if (responseData.errcode !== undefined && responseData.errcode !== 0) {
- throw new BridgeError(responseData.errcode, responseData.errmsg)
- }
-
- return responseData
-}
-
-WeixinServer.GetMPAccessTokenData = async function(options) {
- const response = await new WeixinServer(options).getAccessToken()
- return WeixinServer.GetResponseData(response)
-}
-
-WeixinServer.GetCodeToSessionData = async function(options) {
- const response = await new WeixinServer(options).codeToSession(options.code)
- return WeixinServer.GetResponseData(response)
-}
-
-WeixinServer.GetUserEncryptKeyData = async function(options) {
- const response = await new WeixinServer(options).getUserEncryptKey(options)
- return WeixinServer.GetResponseData(response)
-}
-
-WeixinServer.GetH5AccessTokenData = async function(options) {
- const response = await new WeixinServer(options).getAccessTokenH5()
- return WeixinServer.GetResponseData(response)
-}
-
-WeixinServer.GetH5TicketData = async function(options) {
- const response = await new WeixinServer(options).getTicket(options.access_token)
- return WeixinServer.GetResponseData(response)
-}
-
-
-module.exports = {
- WeixinServer
+'use strict';
+
+const crypto = require('crypto')
+
+const {
+ HTTP_STATUS
+} = require('./consts.js')
+
+const {
+ BridgeError
+} = require('./bridge-error.js')
+
+class WeixinServer {
+
+ constructor(options = {}) {
+ this._appid = options.appid
+ this._secret = options.secret
+ }
+
+ getAccessToken() {
+ return uniCloud.httpclient.request(WeixinServer.AccessToken_Url, {
+ dataType: 'json',
+ method: 'POST',
+ data: {
+ appid: this._appid,
+ secret: this._secret,
+ grant_type: "client_credential"
+ }
+ })
+ }
+
+ // 使用客户端获取的 code 从微信服务器换取 openid,code 仅可使用一次
+ codeToSession(code) {
+ return uniCloud.httpclient.request(WeixinServer.Code2Session_Url, {
+ dataType: 'json',
+ data: {
+ appid: this._appid,
+ secret: this._secret,
+ js_code: code,
+ grant_type: 'authorization_code'
+ }
+ })
+ }
+
+ getUserEncryptKey({
+ access_token,
+ openid,
+ session_key
+ }) {
+ console.log(access_token, openid, session_key);
+ const signature = crypto.createHmac('sha256', session_key).update('').digest('hex')
+ return uniCloud.httpclient.request(WeixinServer.User_Encrypt_Key_Url, {
+ dataType: 'json',
+ method: 'POST',
+ dataAsQueryString: true,
+ data: {
+ access_token,
+ openid: openid,
+ signature: signature,
+ sig_method: 'hmac_sha256'
+ }
+ })
+ }
+
+ getAccessTokenH5() {
+ return uniCloud.httpclient.request(WeixinServer.AccessToken_H5_Url, {
+ dataType: 'json',
+ method: 'GET',
+ data: {
+ appid: this._appid,
+ secret: this._secret,
+ grant_type: "client_credential"
+ }
+ })
+ }
+
+ getTicket(access_token) {
+ return uniCloud.httpclient.request(WeixinServer.Ticket_Url, {
+ dataType: 'json',
+ dataAsQueryString: true,
+ method: 'POST',
+ data: {
+ access_token
+ }
+ })
+ }
+}
+
+WeixinServer.AccessToken_Url = 'https://api.weixin.qq.com/cgi-bin/token'
+WeixinServer.Code2Session_Url = 'https://api.weixin.qq.com/sns/jscode2session'
+WeixinServer.User_Encrypt_Key_Url = 'https://api.weixin.qq.com/wxa/business/getuserencryptkey'
+WeixinServer.AccessToken_H5_Url = 'https://api.weixin.qq.com/cgi-bin/token'
+WeixinServer.Ticket_Url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi'
+
+WeixinServer.GetMPAccessToken = function(options) {
+ return new WeixinServer(options).getAccessToken()
+}
+
+WeixinServer.GetCodeToSession = function(options) {
+ return new WeixinServer(options).codeToSession(options.code)
+}
+
+WeixinServer.GetUserEncryptKey = function(options) {
+ return new WeixinServer(options).getUserEncryptKey(options)
+}
+
+WeixinServer.GetH5AccessToken = function(options) {
+ return new WeixinServer(options).getAccessTokenH5()
+}
+
+WeixinServer.GetH5Ticket = function(options) {
+ return new WeixinServer(options).getTicket(options.access_token)
+}
+
+////////////////////////////////////////////////////////////////
+
+WeixinServer.GetResponseData = function(response) {
+ console.log("WeixinServer::response", response)
+
+ if (response.status !== HTTP_STATUS.SUCCESS) {
+ throw new BridgeError(response.status, response.status)
+ }
+
+ const responseData = response.data
+
+ if (responseData.errcode !== undefined && responseData.errcode !== 0) {
+ throw new BridgeError(responseData.errcode, responseData.errmsg)
+ }
+
+ return responseData
+}
+
+WeixinServer.GetMPAccessTokenData = async function(options) {
+ const response = await new WeixinServer(options).getAccessToken()
+ return WeixinServer.GetResponseData(response)
+}
+
+WeixinServer.GetCodeToSessionData = async function(options) {
+ const response = await new WeixinServer(options).codeToSession(options.code)
+ return WeixinServer.GetResponseData(response)
+}
+
+WeixinServer.GetUserEncryptKeyData = async function(options) {
+ const response = await new WeixinServer(options).getUserEncryptKey(options)
+ return WeixinServer.GetResponseData(response)
+}
+
+WeixinServer.GetH5AccessTokenData = async function(options) {
+ const response = await new WeixinServer(options).getAccessTokenH5()
+ return WeixinServer.GetResponseData(response)
+}
+
+WeixinServer.GetH5TicketData = async function(options) {
+ const response = await new WeixinServer(options).getTicket(options.access_token)
+ return WeixinServer.GetResponseData(response)
+}
+
+
+module.exports = {
+ WeixinServer
}