提交 2f4c9be8 编写于 作者: DCloud_JSON's avatar DCloud_JSON

新增callfunction的拦截器废除this.request的写法。为callFunction添加:请求失败是否断网判断并提示、恢复网络自动重新执行、自...

新增callfunction的拦截器废除this.request的写法。为callFunction添加:请求失败是否断网判断并提示、恢复网络自动重新执行、自动处理响应体,目前处理了403为token过期自动跳转到登陆页面,今后会添加更多的自动行为、自动延续token过期时间
上级 812b079d
...@@ -13,7 +13,7 @@ ...@@ -13,7 +13,7 @@
// #ifdef APP-PLUS // #ifdef APP-PLUS
//checkIsAgree(); 暂时先用默认生成的,自定义的等待原生支持后实现。因为启动vue界面时已经,请求了部分权限这并不符合国家的法规 //checkIsAgree(); 暂时先用默认生成的,自定义的等待原生支持后实现。因为启动vue界面时已经,请求了部分权限这并不符合国家的法规
// #endif // #endif
// #ifdef APP-PLUS // #ifdef APP-PLUS
//一键登录 功能预登录 //一键登录 功能预登录
plus.oauth.getServices(oauthServices => { plus.oauth.getServices(oauthServices => {
...@@ -37,31 +37,6 @@ ...@@ -37,31 +37,6 @@
console.error('获取服务供应商失败:' + JSON.stringify(err)); console.error('获取服务供应商失败:' + JSON.stringify(err));
}) })
// #endif // #endif
//clientDB的错误提示
const db = uniCloud.database()
function onDBError({
code, // 错误码详见https://uniapp.dcloud.net.cn/uniCloud/clientdb?id=returnvalue
message
}) {
// 处理错误
console.log(code,message);
if([
'TOKEN_INVALID_INVALID_CLIENTID',
'TOKEN_INVALID',
'TOKEN_INVALID_TOKEN_EXPIRED',
'TOKEN_INVALID_WRONG_TOKEN',
'TOKEN_INVALID_ANONYMOUS_USER',
].includes(code)){
uni.navigateTo({
url:'/pages/ucenter/login-page/index/index'
})
}
}
// 绑定clientDB错误事件
db.on('error', onDBError)
// 解绑clientDB错误事件
//db.off('error', onDBError)
}, },
onShow: function() { onShow: function() {
console.log('App Show') console.log('App Show')
......
...@@ -177,6 +177,22 @@ uni-starter + uniCloud admin,应用开发从未如此简单快捷! ...@@ -177,6 +177,22 @@ uni-starter + uniCloud admin,应用开发从未如此简单快捷!
1. 最新的华为应用市场要求,隐私政策提示框上接受按钮的文本,必须为“同意”而不能是其他有歧义的文字。 1. 最新的华为应用市场要求,隐私政策提示框上接受按钮的文本,必须为“同意”而不能是其他有歧义的文字。
2. 配置后提交云端打包后生效。理论上绝大部分和`manifest.json`生效相关的配置均需要提交云打包后生效 2. 配置后提交云端打包后生效。理论上绝大部分和`manifest.json`生效相关的配置均需要提交云打包后生效
#### 10.拦截器改造后的uniCloud
1. Debug,调试期间开启Debug。接口一旦file就会弹出真实错误信息。否则将弹出,系统错误请稍后再试!
```
if(Debug){
console.log(e);
uni.showModal({
content: JSON.stringify(e),
showCancel: false
});
}
```
2. 断网自动重试,当callFunction为fail时检测是否因断网引起。如果是会提醒用户并且会在恢复网络之后自动重新发起请求
3. 常规的errCoder自动执行对应程序,如token无效/过期自动跳转到登陆页面。
4. token自动续期。
### 应用启动时序介绍 ### 应用启动时序介绍
文件路径: App.vue 文件路径: App.vue
``` ```
......
## 1.0.9(2021-05-23)
修复变量被重复定义的问题
## 1.0.8(2021-05-22) ## 1.0.8(2021-05-22)
宫格页(/pages/grid/grid),新增根据当前用户是否登陆、是否为管理员的角色来决定是否显示的示范 宫格页(/pages/grid/grid),新增根据当前用户是否登陆、是否为管理员的角色来决定是否显示的示范
## 1.0.7(2021-05-22) ## 1.0.7(2021-05-22)
......
import uniStarterConfig from '@/uni-starter.config.js'; import uniStarterConfig from '@/uni-starter.config.js';
import store from '@/store'
//应用初始化页 //应用初始化页
// #ifdef APP-PLUS // #ifdef APP-PLUS
import checkUpdate from '@/uni_modules/uni-upgrade-center-app/utils/check-update'; import checkUpdate from '@/uni_modules/uni-upgrade-center-app/utils/check-update';
import callCheckVersion from '@/uni_modules/uni-upgrade-center-app/utils/call-check-version'; import callCheckVersion from '@/uni_modules/uni-upgrade-center-app/utils/call-check-version';
import interceptorChooseImage from '@/uni_modules/json-interceptor-chooseImage/js_sdk/main.js'; import interceptorChooseImage from '@/uni_modules/json-interceptor-chooseImage/js_sdk/main.js';
// #endif // #endif
const db = uniCloud.database()
export default function() { export default function() {
setTimeout(()=>{ setTimeout(()=>{
...@@ -21,7 +23,132 @@ export default function() { ...@@ -21,7 +23,132 @@ export default function() {
interceptorChooseImage() interceptorChooseImage()
// #endif // #endif
//clientDB的错误提示
function onDBError({
code, // 错误码详见https://uniapp.dcloud.net.cn/uniCloud/clientdb?id=returnvalue
message
}) {
// 处理错误
console.log(code,message);
if([
'TOKEN_INVALID_INVALID_CLIENTID',
'TOKEN_INVALID',
'TOKEN_INVALID_TOKEN_EXPIRED',
'TOKEN_INVALID_WRONG_TOKEN',
'TOKEN_INVALID_ANONYMOUS_USER',
].includes(code)){
uni.navigateTo({
url:'/pages/ucenter/login-page/index/index'
})
}
}
// 绑定clientDB错误事件
db.on('error', onDBError)
// 解绑clientDB错误事件
//db.off('error', onDBError)
db.on('refreshToken', function({
token,
tokenExpired
}) {
console.log('监听到clientDB的refreshToken',{token,tokenExpired});
store.commit('user/login', {
token,
tokenExpired
})
})
const Debug = true;
//拦截器封装callFunction
let callFunctionOption;
uniCloud.addInterceptor('callFunction',{
invoke(e){
console.log(JSON.stringify(e));
callFunctionOption = e
},
complete(e){
// console.log(JSON.stringify(e));
},
fail(e) { // 失败回调拦截
if(Debug){
console.log(e);
uni.showModal({
content: JSON.stringify(e),
showCancel: false
});
}else{
uni.showModal({
content: "系统错误请稍后再试!",
showCancel: false,
confirmText:"知道了"
});
}
//如果执行错误,检查是否断网
uni.getNetworkType({
complete:res => {
console.log(res);
if (res.networkType == 'none') {
uni.showToast({
title: '手机网络异常',
icon: 'none'
});
console.log('手机网络异常');
let callBack = res=>{
console.log(res);
if (res.isConnected) {
uni.showToast({
title: '恢复联网自动重新执行',
icon: 'none'
});
console.log(res.networkType,"恢复联网自动重新执行");
uni.offNetworkStatusChange(e=>{
console.log("移除监听成功",e);
})
//恢复联网自动重新执行
uniCloud.callFunction(callFunctionOption)
uni.offNetworkStatusChange(callBack);
}
}
uni.onNetworkStatusChange(callBack);
}
}
});
},
success:(e)=>{
console.log(e);
const {token,tokenExpired} = e.result
if (token && tokenExpired) {
store.commit('user/login', {
token,
tokenExpired
})
}
console.log(e.result.code);
switch (e.result.code){
case 403:
uni.showModal({
content: '未登陆,跳登陆',
showCancel: false
});
break;
case 50101:
uni.showToast({
title: e.result.msg,
icon: 'none',
duration:2000
});
break;
default:
console.log('code的值是:'+e.result.code,'可以在这里插入,自动处理响应体');
break;
}
}
})
//自定义路由拦截 //自定义路由拦截
const {"router": {needLogin,login} } = uniStarterConfig //需要登录的页面 const {"router": {needLogin,login} } = uniStarterConfig //需要登录的页面
let list = ["navigateTo", "redirectTo", "reLaunch", "switchTab"]; let list = ["navigateTo", "redirectTo", "reLaunch", "switchTab"];
......
...@@ -93,8 +93,8 @@ ...@@ -93,8 +93,8 @@
}, },
}, },
created() { created() {
console.log('loginConfig', this.loginConfig); // console.log('loginConfig', this.loginConfig);
console.log('this.getRoute(1)', this.getRoute(1)); // console.log('this.getRoute(1)', this.getRoute(1));
let servicesList = this.servicesList let servicesList = this.servicesList
//去掉当前页面对应的登录选项 //去掉当前页面对应的登录选项
for (var i = 0; i < servicesList.length; i++) { for (var i = 0; i < servicesList.length; i++) {
...@@ -109,7 +109,7 @@ ...@@ -109,7 +109,7 @@
servicesList.splice(i, 1) servicesList.splice(i, 1)
} }
} }
console.log('servicesList', servicesList); // console.log('servicesList', servicesList);
}, },
mounted() { mounted() {
//获取当前环境能用的快捷登录方式 //获取当前环境能用的快捷登录方式
...@@ -265,17 +265,27 @@ ...@@ -265,17 +265,27 @@
params, params,
type type
}); });
this.request('uni-id-cf/login_by_' + type, params, result => { uniCloud.callFunction({
console.log(result); name:'uni-id-cf',
if (result.code === 0) { data:{
if (type == 'univerify') { action:'login_by_'+type,
uni.closeAuthView() params
} },
uni.hideLoading() success: ({result}) => {
loginSuccess(result) console.log(result);
delete result.userInfo.token if (result.code === 0) {
this.setUserInfo(result.userInfo) if (type == 'univerify') {
} uni.closeAuthView()
}
uni.hideLoading()
loginSuccess(result)
delete result.userInfo.token
this.setUserInfo(result.userInfo)
}
},
complete: () => {
uni.hideLoading()
}
}) })
}, },
async getUserInfo(e) { async getUserInfo(e) {
......
...@@ -74,22 +74,26 @@ ...@@ -74,22 +74,26 @@
title: '手机号格式错误', title: '手机号格式错误',
icon: 'none' icon: 'none'
}); });
uniCloud.callFunction({
this.request('uni-id-cf/sendSmsCode', name:'uni-id-cf',
{ data:{
"mobile": this.phone, action:'sendSmsCode',
"type": this.codeType params:{
},result=>{ "mobile": this.phone,
console.log(result); "type": this.codeType
uni.showToast({ },
title: "短信验证码发送成功", },
icon: 'none' success: ({result}) => {
}); console.log(result);
this.reverseNumber = Number(this.count); uni.showToast({
this.getCode(); title: "短信验证码发送成功",
this.$emit('getCode'); icon: 'none'
} });
) this.reverseNumber = Number(this.count);
this.getCode();
this.$emit('getCode');
}
})
}, },
getCode() { getCode() {
if (this.reverseNumber == 0) { if (this.reverseNumber == 0) {
......
/*
1.优雅访问指定路由地址
2.load自动显示与关闭
3.统一路由拦截
3.1 读取云端接口权限配置,先验证本地token再访问
3.2 处理因token过期等问题自动更新本地token,或token无效跳转至登录页面
*/
const debug = true;//开启后,会alert错误信息
export default function request(name,params,callback=false,{showLoading=false,loadText='',fail=()=>{}}={}){
// console.log('request');
showLoading||loadText? uni.showLoading({title:loadText,mask:true}):'';
let routers = name.split('/');
var action = false
if (routers.length>1){
name = routers[0]
action = routers[1]
}
console.log({name,data:{action,params}})
return new Promise((resolve,reject)=>{
uniCloud.callFunction({name,data:{action,params},
success(e){
console.log(e);
const {result:{data,code}} = e
console.log(data,code);
resolve(e)
return callback(e.result,e)
},
fail(err){
reject(err)
console.log(err);
fail(err)
},
complete() {
if(showLoading || loadText) uni.hideLoading()
}
})
})
}
\ No newline at end of file
...@@ -2,10 +2,8 @@ import Vue from 'vue' ...@@ -2,10 +2,8 @@ import Vue from 'vue'
import App from './App' import App from './App'
import store from './store/index.js'; import store from './store/index.js';
import openApp from './common/openApp.js'; import openApp from './common/openApp.js';
import request from './js_sdk/request.js';
Vue.config.productionTip = false Vue.config.productionTip = false
Vue.prototype.request = request
openApp(); openApp();
App.mpType = 'app' App.mpType = 'app'
......
{ {
"id": "uni-starter", "id": "uni-starter",
"displayName": "uni-starter", "displayName": "uni-starter",
"version": "1.0.7", "version": "1.0.9",
"description": "云端一体应用快速开发模版", "description": "云端一体应用快速开发模版",
"keywords": [ "keywords": [
"uni-starter", "uni-starter",
......
...@@ -58,7 +58,7 @@ ...@@ -58,7 +58,7 @@
} }
} }
}, },
onReady() { onReady() {
// #ifdef APP-NVUE // #ifdef APP-NVUE
this.listHight = uni.getSystemInfoSync().windowHeight - 96 + 'px' this.listHight = uni.getSystemInfoSync().windowHeight - 96 + 'px'
// #endif // #endif
......
...@@ -13,7 +13,7 @@ ...@@ -13,7 +13,7 @@
</view> </view>
</template> </template>
<script> <script>
var univerify_first,currentWebview;//是否一键登录优先 var univerify_first,currentWebview;//是否一键登录优先
export default { export default {
data() { data() {
......
...@@ -42,16 +42,31 @@ ...@@ -42,16 +42,31 @@
}, },
methods: { methods: {
submit(){ //完成并提交 submit(){ //完成并提交
this.request('uni-id-cf/loginBySms', // this.-request('uni-id-cf/loginBySms',
{ // {
"mobile":this.phone, // "mobile":this.phone,
"code":this.code // "code":this.code
}, // },
e=>{ // e=>{
console.log(e); // console.log(e);
this.loginSuccess(e) // this.loginSuccess(e)
}, // },
{showLoading:true}) // {showLoading:true})
uniCloud.callFunction({
name:'uni-id-cf',
data:{
action:'loginBySms',
params:{
"mobile":this.phone,
"code":this.code
},
},
success: ({result}) => {
this.loginSuccess(result)
}
})
} }
} }
} }
......
...@@ -62,42 +62,90 @@ ...@@ -62,42 +62,90 @@
icon: 'none' icon: 'none'
}); });
} }
// 下边是可以登录 // 下边是可以登录
this.request('uni-id-cf/login', { uniCloud.callFunction({
"username": this.username, name:'uni-id-cf',
"password": this.password, data:{
"captcha":this.captcha action:'login',
}, result => { params:{
console.log(result); "username": this.username,
if (result.code === 0) { "password": this.password,
this.loginSuccess(result) "captcha":this.captcha
} else { },
if (result.needCaptcha) { },
uni.showToast({ success: ({result}) => {
title: result.msg, console.log(result);
icon: 'none' if (result.code === 0) {
}); this.loginSuccess(result)
this.createCaptcha() } else {
}else{ if (result.needCaptcha) {
uni.showModal({ uni.showToast({
title: '错误', title: result.msg,
content: result.msg, icon: 'none'
showCancel: false, });
confirmText: '知道了' this.createCaptcha()
}); }else{
} uni.showModal({
} title: '错误',
}) content: result.msg,
showCancel: false,
confirmText: '知道了'
});
}
}
}
})
// this.-request('uni-id-cf/login', {
// "username": this.username,
// "password": this.password,
// "captcha":this.captcha
// }, result => {
// console.log(result);
// if (result.code === 0) {
// this.loginSuccess(result)
// } else {
// if (result.needCaptcha) {
// uni.showToast({
// title: result.msg,
// icon: 'none'
// });
// this.createCaptcha()
// }else{
// uni.showModal({
// title: '错误',
// content: result.msg,
// showCancel: false,
// confirmText: '知道了'
// });
// }
// }
// })
}, },
createCaptcha(){ createCaptcha(){
this.request( // this.-request(
'uni-id-cf/createCaptcha', { // 'uni-id-cf/createCaptcha', {
scene: "login" // scene: "login"
}, // },
result => { // result => {
if (result.code === 0) { // if (result.code === 0) {
this.captchaBase64 = result.captchaBase64 // this.captchaBase64 = result.captchaBase64
} // }
// })
uniCloud.callFunction({
name:'uni-id-cf',
data:{
action:'createCaptcha',
params:{
scene: "login"
},
},
success: ({result}) => {
if (result.code === 0) {
this.captchaBase64 = result.captchaBase64
}
}
}) })
}, },
/* 前往注册 */ /* 前往注册 */
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
<uni-forms ref="form" :value="formData" :rules="rules"> <uni-forms ref="form" :value="formData" :rules="rules">
<uni-forms-item name="phone"> <uni-forms-item name="phone">
<!-- focus规则如果上一页携带来“手机号码”数据就focus验证码输入框,否则focus手机号码输入框 --> <!-- focus规则如果上一页携带来“手机号码”数据就focus验证码输入框,否则focus手机号码输入框 -->
<uni-easyinput :focus="formData.phone.length!=11" type="number" class="easyinput" :inputBorder="false" <uni-easyinput :disabled="lock" :focus="formData.phone.length!=11" type="number" class="easyinput" :inputBorder="false"
v-model="formData.phone" maxlength="11" placeholder="请输入手机号"></uni-easyinput> v-model="formData.phone" maxlength="11" placeholder="请输入手机号"></uni-easyinput>
</uni-forms-item> </uni-forms-item>
<uni-forms-item name="code"> <uni-forms-item name="code">
...@@ -35,7 +35,8 @@ ...@@ -35,7 +35,8 @@
export default { export default {
mixins: [mixin], mixins: [mixin],
data() { data() {
return { return {
lock:false,
formData: { formData: {
"phone": "", "phone": "",
'pwd': '', 'pwd': '',
...@@ -120,7 +121,8 @@ ...@@ -120,7 +121,8 @@
}, },
onLoad(event) { onLoad(event) {
if (event && event.phoneNumber) { if (event && event.phoneNumber) {
this.formData.phone = event.phoneNumber; this.formData.phone = event.phoneNumber;
this.lock = true
} }
}, },
onReady() { onReady() {
...@@ -135,21 +137,42 @@ ...@@ -135,21 +137,42 @@
submit() { submit() {
this.$refs.form.submit() this.$refs.form.submit()
.then(res => { .then(res => {
this.request('uni-id-cf/resetPwdBySmsCode', { // this.-request('uni-id-cf/resetPwdBySmsCode', {
"mobile": this.formData.phone, // "mobile": this.formData.phone,
"code": this.formData.code, // "code": this.formData.code,
"password": this.formData.pwd // "password": this.formData.pwd
}, result => { // }, result => {
console.log(result); // console.log(result);
uni.showToast({ // uni.showToast({
title: result.msg, // title: result.msg,
icon: 'none' // icon: 'none'
}); // });
if (result.code === 0) { // if (result.code === 0) {
uni.navigateBack() // uni.navigateBack()
} // }
// })
uniCloud.callFunction({
name:'uni-id-cf',
data:{
action:'resetPwdBySmsCode',
params:{
"mobile": this.formData.phone,
"code": this.formData.code,
"password": this.formData.pwd
},
},
success: ({result}) => {
console.log(result);
uni.showToast({
title: result.msg,
icon: 'none'
});
if (result.code === 0) {
uni.navigateBack()
}
}
}) })
}) })
} }
} }
} }
......
...@@ -62,12 +62,25 @@ import mixin from '../common/login-page.mixin.js'; ...@@ -62,12 +62,25 @@ import mixin from '../common/login-page.mixin.js';
uni.hideLoading() uni.hideLoading()
}) })
}, },
submitForm(value) { submitForm(params) {
this.request('uni-id-cf/register',value,result=>{ // this.-request('uni-id-cf/register',params,result=>{
console.log(result); // console.log(result);
if(result.code === 0){ // if(result.code === 0){
this.loginSuccess(result) // this.loginSuccess(result)
} // }
// })
uniCloud.callFunction({
name:'uni-id-cf',
data:{
action:'register',
params,
},
success: ({result}) => {
console.log(result);
if(result.code === 0){
this.loginSuccess(result)
}
}
}) })
} }
} }
......
...@@ -48,19 +48,40 @@ ...@@ -48,19 +48,40 @@
*/ */
submit() { submit() {
console.log(this.formData); console.log(this.formData);
this.request('uni-id-cf/bind_mobile_by_sms', { // this.-request('uni-id-cf/bind_mobile_by_sms', {
"mobile": this.formData.phone, // "mobile": this.formData.phone,
"code": this.formData.code // "code": this.formData.code
}, result=> { // }, result=> {
console.log(result); // console.log(result);
this.setUserInfo({"mobile":result.mobile}) // this.setUserInfo({"mobile":result.mobile})
uni.showToast({ // uni.showToast({
title: result.msg, // title: result.msg,
icon: 'none' // icon: 'none'
}); // });
if (result.code === 0) { // if (result.code === 0) {
uni.navigateBack() // uni.navigateBack()
} // }
// })
uniCloud.callFunction({
name:'uni-id-cf',
data:{
action:'bind_mobile_by_sms',
params:{
"mobile": this.formData.phone,
"code": this.formData.code
},
},
success: ({result}) => {
console.log(result);
this.setUserInfo({"mobile":result.mobile})
uni.showToast({
title: result.msg,
icon: 'none'
});
if (result.code === 0) {
uni.navigateBack()
}
}
}) })
} }
} }
......
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
<image class="avatarUrl" :src="userInfo.avatar||nullAvatarUrl" mode="widthFix"></image> <image class="avatarUrl" :src="userInfo.avatar||nullAvatarUrl" mode="widthFix"></image>
</view> </view>
</uni-list-item> </uni-list-item>
<uni-list-item class="item" @click="setNickname()" title="昵称" :rightText="userInfo.nickname||'未设置'" link></uni-list-item> <uni-list-item class="item" @click="setNickname('')" title="昵称" :rightText="userInfo.nickname||'未设置'" link></uni-list-item>
<uni-list-item class="item" @click="bindMobile" title="手机号" :rightText="userInfo.mobile||'未绑定'" link></uni-list-item> <uni-list-item class="item" @click="bindMobile" title="手机号" :rightText="userInfo.mobile||'未绑定'" link></uni-list-item>
</uni-list> </uni-list>
<uni-popup ref="dialog" type="dialog"> <uni-popup ref="dialog" type="dialog">
...@@ -70,10 +70,32 @@ ...@@ -70,10 +70,32 @@
"univerifyStyle": this.univerifyStyle, "univerifyStyle": this.univerifyStyle,
success: async e => { success: async e => {
console.log(e.authResult); console.log(e.authResult);
this.request('uni-id-cf/bind_mobile_by_univerify', // this.-request('uni-id-cf/bind_mobile_by_univerify',
e.authResult, // e.authResult,
result=> // result=>
{ // {
// console.log(result);
// if(result.code===0){
// this.setUserInfo({"mobile":result.mobile})
// uni.closeAuthView()
// }else{
// uni.showModal({
// content: JSON.stringify(result.msg),
// showCancel: false,
// complete() {
// uni.closeAuthView()
// }
// });
// }
// }
// )
uniCloud.callFunction({
name:'uni-id-cf',
data:{
action:'bind_mobile_by_univerify',
params:e.authResult,
},
success: ({result}) => {
console.log(result); console.log(result);
if(result.code===0){ if(result.code===0){
this.setUserInfo({"mobile":result.mobile}) this.setUserInfo({"mobile":result.mobile})
...@@ -86,9 +108,9 @@ ...@@ -86,9 +108,9 @@
uni.closeAuthView() uni.closeAuthView()
} }
}); });
} }
} }
) })
}, },
fail: (err) => { fail: (err) => {
console.log(err); console.log(err);
...@@ -104,7 +126,7 @@ ...@@ -104,7 +126,7 @@
}) })
}, },
setNickname(nickname) { setNickname(nickname) {
console.log(nickname); console.log(9527,nickname);
if (nickname) { if (nickname) {
usersTable.where('_id==$env.uid').update({ usersTable.where('_id==$env.uid').update({
nickname nickname
......
'use strict'; 'use strict';
let uniID = require('uni-id') let uniID = require('uni-id')
const uniCaptcha = require('uni-captcha') const uniCaptcha = require('uni-captcha')
const createConfig = require('uni-config-center') const createConfig = require('uni-config-center')
const uniIdConfig = createConfig({ const uniIdConfig = createConfig({
pluginId: 'uni-id' pluginId: 'uni-id'
})._config })._config
const db = uniCloud.database() const db = uniCloud.database()
const dbCmd = db.command const dbCmd = db.command
exports.main = async (event, context) => { exports.main = async (event, context) => {
//UNI_WYQ:这里的uniID换成新的,保证多人访问不会冲突 //UNI_WYQ:这里的uniID换成新的,保证多人访问不会冲突
uniID = uniID.createInstance({context}) uniID = uniID.createInstance({context})
console.log('event : ' + JSON.stringify(event)) console.log('event : ' + JSON.stringify(event))
/* /*
...@@ -36,117 +36,117 @@ exports.main = async (event, context) => { ...@@ -36,117 +36,117 @@ exports.main = async (event, context) => {
用户就这样轻易地伪造了他人的uid传递给服务端,有一句话叫:前端从来的数据是不可信任的 用户就这样轻易地伪造了他人的uid传递给服务端,有一句话叫:前端从来的数据是不可信任的
所以这里我们需要将uniID.checkToken返回的uid写入到params.uid 所以这里我们需要将uniID.checkToken返回的uid写入到params.uid
*/ */
let noCheckAction = ['register','checkToken','login','logout','sendSmsCode','createCaptcha','verifyCaptcha','refreshCaptcha','inviteLogin','login_by_weixin','login_by_univerify','login_by_apple','loginBySms','resetPwdBySmsCode'] let noCheckAction = ['register','checkToken','login','logout','sendSmsCode','createCaptcha','verifyCaptcha','refreshCaptcha','inviteLogin','login_by_weixin','login_by_univerify','login_by_apple','loginBySms','resetPwdBySmsCode']
if (!noCheckAction.includes(action)) { if (!noCheckAction.includes(action)) {
if (!uniIdToken) { if (!uniIdToken) {
return { return {
code: 403, code: 403,
msg: '缺少token' msg: '缺少token'
} }
} }
let payload = await uniID.checkToken(uniIdToken) let payload = await uniID.checkToken(uniIdToken)
if (payload.code && payload.code > 0) { if (payload.code && payload.code > 0) {
return payload return payload
} }
params.uid = payload.uid params.uid = payload.uid
} }
//3.注册成功后创建新用户的积分表方法 //3.注册成功后创建新用户的积分表方法
async function registerSuccess(uid) { async function registerSuccess(uid) {
await db.collection('uni-id-scores').add({ await db.collection('uni-id-scores').add({
user_id: uid, user_id: uid,
score: 1, score: 1,
type: 1, type: 1,
balance: 1, balance: 1,
comment: "", comment: "",
create_date: Date.now() create_date: Date.now()
}) })
} }
//4.记录成功登录的日志方法 //4.记录成功登录的日志方法
const loginLog = async (res = {}, type = 'login') => { const loginLog = async (res = {}, type = 'login') => {
const now = Date.now() const now = Date.now()
const uniIdLogCollection = db.collection('uni-id-log') const uniIdLogCollection = db.collection('uni-id-log')
let logData = { let logData = {
deviceId: params.deviceId || context.DEVICEID, deviceId: params.deviceId || context.DEVICEID,
ip: params.ip || context.CLIENTIP, ip: params.ip || context.CLIENTIP,
type, type,
ua: context.CLIENTUA, ua: context.CLIENTUA,
create_date: now create_date: now
}; };
Object.assign(logData, Object.assign(logData,
res.code === 0 ? { res.code === 0 ? {
user_id: res.uid, user_id: res.uid,
state: 1 state: 1
} : { } : {
state: 0 state: 0
}) })
if (res.type == 'register') { if (res.type == 'register') {
await registerSuccess(res.uid) await registerSuccess(res.uid)
} }
return await uniIdLogCollection.add(logData) return await uniIdLogCollection.add(logData)
} }
let res = {} let res = {}
switch (action) { //根据action的值执行对应的操作 switch (action) { //根据action的值执行对应的操作
case 'bind_mobile_by_univerify': case 'bind_mobile_by_univerify':
let { let {
appid, apiKey, apiSecret appid, apiKey, apiSecret
} = uniIdConfig.service.univerify } = uniIdConfig.service.univerify
let univerifyRes = await uniCloud.getPhoneNumber({ let univerifyRes = await uniCloud.getPhoneNumber({
provider: 'univerify', provider: 'univerify',
appid, appid,
apiKey, apiKey,
apiSecret, apiSecret,
access_token: params.access_token, access_token: params.access_token,
openid: params.openid openid: params.openid
}) })
if (univerifyRes.code === 0) { if (univerifyRes.code === 0) {
res = await uniID.bindMobile({ res = await uniID.bindMobile({
uid: params.uid, uid: params.uid,
mobile: univerifyRes.phoneNumber mobile: univerifyRes.phoneNumber
}) })
res.mobile = univerifyRes.phoneNumber res.mobile = univerifyRes.phoneNumber
} }
break; break;
case 'bind_mobile_by_sms': case 'bind_mobile_by_sms':
console.log({ console.log({
uid: params.uid, uid: params.uid,
mobile: params.mobile, mobile: params.mobile,
code: params.code code: params.code
}); });
res = await uniID.bindMobile({ res = await uniID.bindMobile({
uid: params.uid, uid: params.uid,
mobile: params.mobile, mobile: params.mobile,
code: params.code code: params.code
}) })
console.log(res); console.log(res);
break; break;
case 'register': case 'register':
var { var {
username, password, nickname username, password, nickname
} = params } = params
if (/^1\d{10}$/.test(username)) { if (/^1\d{10}$/.test(username)) {
return { return {
code: 401, code: 401,
msg: '用户名不能是手机号' msg: '用户名不能是手机号'
} }
}; };
if (/^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/.test(username)) { if (/^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/.test(username)) {
return { return {
code: 401, code: 401,
msg: '用户名不能是邮箱' msg: '用户名不能是邮箱'
} }
} }
res = await uniID.register({ res = await uniID.register({
username, username,
password, password,
nickname nickname
}); });
if (res.code === 0) { if (res.code === 0) {
await registerSuccess(res.uid) await registerSuccess(res.uid)
} }
break; break;
case 'login': case 'login':
//防止黑客恶意破解登录,连续登录失败一定次数后,需要用户提供验证码 //防止黑客恶意破解登录,连续登录失败一定次数后,需要用户提供验证码
const getNeedCaptcha = async () => { const getNeedCaptcha = async () => {
...@@ -165,192 +165,192 @@ exports.main = async (event, context) => { ...@@ -165,192 +165,192 @@ exports.main = async (event, context) => {
.get(); .get();
return recentRecord.data.filter(item => item.state === 0).length === recordSize; return recentRecord.data.filter(item => item.state === 0).length === recordSize;
} }
let passed = false; let passed = false;
let needCaptcha = await getNeedCaptcha(); let needCaptcha = await getNeedCaptcha();
console.log('needCaptcha', needCaptcha); console.log('needCaptcha', needCaptcha);
if (needCaptcha) { if (needCaptcha) {
res = await uniCaptcha.verify({ res = await uniCaptcha.verify({
...params, ...params,
scene: 'login' scene: 'login'
}) })
if (res.code === 0) passed = true; if (res.code === 0) passed = true;
} }
if (!needCaptcha || passed) { if (!needCaptcha || passed) {
res = await uniID.login({ res = await uniID.login({
...params, ...params,
queryField: ['username', 'email', 'mobile'] queryField: ['username', 'email', 'mobile']
}); });
await loginLog(res); await loginLog(res);
needCaptcha = await getNeedCaptcha(); needCaptcha = await getNeedCaptcha();
} }
res.needCaptcha = needCaptcha; res.needCaptcha = needCaptcha;
break; break;
case 'login_by_weixin': case 'login_by_weixin':
res = await uniID.loginByWeixin(params); res = await uniID.loginByWeixin({...params});
await uniID.updateUser({ await uniID.updateUser({
uid: res.uid, uid: res.uid,
username: "微信用户" username: "微信用户"
}); });
res.userInfo.username = "微信用户" res.userInfo.username = "微信用户"
await loginLog(res) await loginLog(res)
break; break;
case 'login_by_univerify': case 'login_by_univerify':
res = await uniID.loginByuniverify(params) res = await uniID.loginByuniverify(params)
await loginLog(res) await loginLog(res)
break; break;
case 'login_by_apple': case 'login_by_apple':
res = await uniID.loginByApple(params) res = await uniID.loginByApple(params)
await loginLog(res) await loginLog(res)
break; break;
case 'checkToken': case 'checkToken':
res = await uniID.checkToken(uniIdToken); res = await uniID.checkToken(uniIdToken);
break; break;
case 'logout': case 'logout':
res = await uniID.logout(uniIdToken) res = await uniID.logout(uniIdToken)
break; break;
case 'sendSmsCode': case 'sendSmsCode':
// 测试期间短信统一用 123456 正式项目删除即可 // 测试期间短信统一用 123456 正式项目删除即可
return uniID.setVerifyCode({ return uniID.setVerifyCode({
mobile: params.mobile, mobile: params.mobile,
code: '123456', code: '123456',
type: params.type type: params.type
}) })
// 简单限制一下客户端调用频率 // 简单限制一下客户端调用频率
const ipLimit = await db.collection('uni-verify').where({ const ipLimit = await db.collection('uni-verify').where({
ip: context.CLIENTIP, ip: context.CLIENTIP,
created_at: dbCmd.gt(Date.now() - 60000) created_at: dbCmd.gt(Date.now() - 60000)
}).get() }).get()
if (ipLimit.data.length > 0) { if (ipLimit.data.length > 0) {
return { return {
code: 429, code: 429,
msg: '请求过于频繁' msg: '请求过于频繁'
} }
} }
const templateId = '11753' // 替换为自己申请的模板id const templateId = '11753' // 替换为自己申请的模板id
if (!templateId) { if (!templateId) {
return { return {
code: 500, code: 500,
msg: 'sendSmsCode需要传入自己的templateId,参考https://uniapp.dcloud.net.cn/uniCloud/uni-id?id=sendsmscode' msg: 'sendSmsCode需要传入自己的templateId,参考https://uniapp.dcloud.net.cn/uniCloud/uni-id?id=sendsmscode'
} }
} }
const randomStr = '00000' + Math.floor(Math.random() * 1000000) const randomStr = '00000' + Math.floor(Math.random() * 1000000)
const code = randomStr.substring(randomStr.length - 6) const code = randomStr.substring(randomStr.length - 6)
res = await uniID.sendSmsCode({ res = await uniID.sendSmsCode({
mobile: params.mobile, mobile: params.mobile,
code, code,
type: params.type, type: params.type,
templateId templateId
}) })
await loginLog(res) await loginLog(res)
break; break;
case 'loginBySms': case 'loginBySms':
if (!params.code) { if (!params.code) {
return { return {
code: 500, code: 500,
msg: '请填写验证码' msg: '请填写验证码'
} }
} }
if (!/^1\d{10}$/.test(params.mobile)) { if (!/^1\d{10}$/.test(params.mobile)) {
return { return {
code: 500, code: 500,
msg: '手机号码填写错误' msg: '手机号码填写错误'
} }
} }
res = await uniID.loginBySms(params) res = await uniID.loginBySms(params)
await loginLog(res) await loginLog(res)
break; break;
case 'inviteLogin': case 'inviteLogin':
if (!params.code) { if (!params.code) {
return { return {
code: 500, code: 500,
msg: '请填写验证码' msg: '请填写验证码'
} }
} }
res = await uniID.loginBySms({ res = await uniID.loginBySms({
...params, ...params,
type: 'register' type: 'register'
}) })
break; break;
case 'resetPwdBySmsCode': case 'resetPwdBySmsCode':
if (!params.code) { if (!params.code) {
return { return {
code: 500, code: 500,
msg: '请填写验证码' msg: '请填写验证码'
} }
} }
if (!/^1\d{10}$/.test(params.mobile)) { if (!/^1\d{10}$/.test(params.mobile)) {
return { return {
code: 500, code: 500,
msg: '手机号码填写错误' msg: '手机号码填写错误'
} }
} }
let loginBySmsRes = await uniID.loginBySms(params) let loginBySmsRes = await uniID.loginBySms(params)
console.log(loginBySmsRes); console.log(loginBySmsRes);
if (loginBySmsRes.code === 0) { if (loginBySmsRes.code === 0) {
res = await uniID.resetPwd({ res = await uniID.resetPwd({
password: params.password, password: params.password,
"uid": loginBySmsRes.uid "uid": loginBySmsRes.uid
}) })
} else { } else {
return loginBySmsRes return loginBySmsRes
} }
break; break;
case 'getInviteCode': case 'getInviteCode':
res = await uniID.getUserInfo({ res = await uniID.getUserInfo({
uid: params.uid, uid: params.uid,
field: ['my_invite_code'] field: ['my_invite_code']
}) })
if (res.code === 0) { if (res.code === 0) {
res.myInviteCode = res.userInfo.my_invite_code res.myInviteCode = res.userInfo.my_invite_code
delete res.userInfo delete res.userInfo
} }
break; break;
case 'getInvitedUser': case 'getInvitedUser':
res = await uniID.getInvitedUser(params) res = await uniID.getInvitedUser(params)
break; break;
case 'updatePwd': case 'updatePwd':
res = await uniID.updatePwd({ res = await uniID.updatePwd({
uid: params.uid, uid: params.uid,
...params ...params
}) })
break; break;
case 'createCaptcha': case 'createCaptcha':
res = await uniCaptcha.create(params) res = await uniCaptcha.create(params)
break; break;
case 'refreshCaptcha': case 'refreshCaptcha':
res = await uniCaptcha.refresh(params) res = await uniCaptcha.refresh(params)
break; break;
case 'registerAdmin': case 'registerAdmin':
var { var {
username, password username, password
} = params } = params
let { let {
total total
} = await db.collection('uni-id-users').where({ } = await db.collection('uni-id-users').where({
role: 'admin' role: 'admin'
}).count() }).count()
if (total) { if (total) {
return { return {
code: 10001, code: 10001,
message: '超级管理员已存在,请登录...' message: '超级管理员已存在,请登录...'
} }
} }
return this.ctx.uniID.register({ return this.ctx.uniID.register({
username, username,
password, password,
role: ["admin"] role: ["admin"]
}) })
break; break;
default: default:
res = { res = {
code: 403, code: 403,
msg: '非法访问' msg: '非法访问'
} }
break; break;
} }
//返回数据给客户端 //返回数据给客户端
return res return res
}; };
// 本文件中的json内容将在云函数【运行】时作为参数传给云函数。
// 配置教程参考:https://uniapp.dcloud.net.cn/uniCloud/quickstart?id=runparam
{
"action": "login_by_weixin",
"params": {
"code": "093tK5Ga1X1D6B0MSAHa13uRH04tK5Gs"
}
}
// 本文件用于,使用JQL语法操作项目关联的uniCloud空间的数据库,方便开发调试和远程数据库管理
// 编写clientDB的js API(也支持常规js语法,比如var),可以对云数据库进行增删改查操作。不支持uniCloud-db组件写法
// 可以全部运行,也可以选中部分代码运行。点击工具栏上的运行按钮或者按下【F5】键运行代码
// 如果文档中存在多条JQL语句,只有最后一条语句生效
// 如果混写了普通js,最后一条语句需是数据库操作语句
// 此处代码运行不受DB Schema的权限控制,移植代码到实际业务中注意在schema中配好permission
// 不支持clientDB的action
// 数据库查询有最大返回条数限制,详见:https://uniapp.dcloud.net.cn/uniCloud/cf-database?id=limit
// 详细JQL语法,请参考 https://uniapp.dcloud.net.cn/uniCloud/clientdb?id=jsquery
// 下面示例查询uni-id-users表的所有数据
db.collection('uni-id-users').get();
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册