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

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

新增callfunction的拦截器废除this.request的写法。为callFunction添加:请求失败是否断网判断并提示、恢复网络自动重新执行、自动处理响应体,目前处理了403为token过期自动跳转到登陆页面,今后会添加更多的自动行为、自动延续token过期时间
上级 812b079d
......@@ -13,7 +13,7 @@
// #ifdef APP-PLUS
//checkIsAgree(); 暂时先用默认生成的,自定义的等待原生支持后实现。因为启动vue界面时已经,请求了部分权限这并不符合国家的法规
// #endif
// #ifdef APP-PLUS
//一键登录 功能预登录
plus.oauth.getServices(oauthServices => {
......@@ -37,31 +37,6 @@
console.error('获取服务供应商失败:' + JSON.stringify(err));
})
// #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() {
console.log('App Show')
......
......@@ -177,6 +177,22 @@ uni-starter + uniCloud admin,应用开发从未如此简单快捷!
1. 最新的华为应用市场要求,隐私政策提示框上接受按钮的文本,必须为“同意”而不能是其他有歧义的文字。
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
```
......
## 1.0.9(2021-05-23)
修复变量被重复定义的问题
## 1.0.8(2021-05-22)
宫格页(/pages/grid/grid),新增根据当前用户是否登陆、是否为管理员的角色来决定是否显示的示范
## 1.0.7(2021-05-22)
......
import uniStarterConfig from '@/uni-starter.config.js';
import store from '@/store'
//应用初始化页
// #ifdef APP-PLUS
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 interceptorChooseImage from '@/uni_modules/json-interceptor-chooseImage/js_sdk/main.js';
// #endif
const db = uniCloud.database()
export default function() {
setTimeout(()=>{
......@@ -21,7 +23,132 @@ export default function() {
interceptorChooseImage()
// #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 //需要登录的页面
let list = ["navigateTo", "redirectTo", "reLaunch", "switchTab"];
......
......@@ -93,8 +93,8 @@
},
},
created() {
console.log('loginConfig', this.loginConfig);
console.log('this.getRoute(1)', this.getRoute(1));
// console.log('loginConfig', this.loginConfig);
// console.log('this.getRoute(1)', this.getRoute(1));
let servicesList = this.servicesList
//去掉当前页面对应的登录选项
for (var i = 0; i < servicesList.length; i++) {
......@@ -109,7 +109,7 @@
servicesList.splice(i, 1)
}
}
console.log('servicesList', servicesList);
// console.log('servicesList', servicesList);
},
mounted() {
//获取当前环境能用的快捷登录方式
......@@ -265,17 +265,27 @@
params,
type
});
this.request('uni-id-cf/login_by_' + type, params, result => {
console.log(result);
if (result.code === 0) {
if (type == 'univerify') {
uni.closeAuthView()
}
uni.hideLoading()
loginSuccess(result)
delete result.userInfo.token
this.setUserInfo(result.userInfo)
}
uniCloud.callFunction({
name:'uni-id-cf',
data:{
action:'login_by_'+type,
params
},
success: ({result}) => {
console.log(result);
if (result.code === 0) {
if (type == 'univerify') {
uni.closeAuthView()
}
uni.hideLoading()
loginSuccess(result)
delete result.userInfo.token
this.setUserInfo(result.userInfo)
}
},
complete: () => {
uni.hideLoading()
}
})
},
async getUserInfo(e) {
......
......@@ -74,22 +74,26 @@
title: '手机号格式错误',
icon: 'none'
});
this.request('uni-id-cf/sendSmsCode',
{
"mobile": this.phone,
"type": this.codeType
},result=>{
console.log(result);
uni.showToast({
title: "短信验证码发送成功",
icon: 'none'
});
this.reverseNumber = Number(this.count);
this.getCode();
this.$emit('getCode');
}
)
uniCloud.callFunction({
name:'uni-id-cf',
data:{
action:'sendSmsCode',
params:{
"mobile": this.phone,
"type": this.codeType
},
},
success: ({result}) => {
console.log(result);
uni.showToast({
title: "短信验证码发送成功",
icon: 'none'
});
this.reverseNumber = Number(this.count);
this.getCode();
this.$emit('getCode');
}
})
},
getCode() {
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'
import App from './App'
import store from './store/index.js';
import openApp from './common/openApp.js';
import request from './js_sdk/request.js';
Vue.config.productionTip = false
Vue.prototype.request = request
openApp();
App.mpType = 'app'
......
{
"id": "uni-starter",
"displayName": "uni-starter",
"version": "1.0.7",
"version": "1.0.9",
"description": "云端一体应用快速开发模版",
"keywords": [
"uni-starter",
......
......@@ -58,7 +58,7 @@
}
}
},
onReady() {
onReady() {
// #ifdef APP-NVUE
this.listHight = uni.getSystemInfoSync().windowHeight - 96 + 'px'
// #endif
......
......@@ -13,7 +13,7 @@
</view>
</template>
<script>
<script>
var univerify_first,currentWebview;//是否一键登录优先
export default {
data() {
......
......@@ -42,16 +42,31 @@
},
methods: {
submit(){ //完成并提交
this.request('uni-id-cf/loginBySms',
{
"mobile":this.phone,
"code":this.code
},
e=>{
console.log(e);
this.loginSuccess(e)
},
{showLoading:true})
// this.-request('uni-id-cf/loginBySms',
// {
// "mobile":this.phone,
// "code":this.code
// },
// e=>{
// console.log(e);
// this.loginSuccess(e)
// },
// {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 @@
icon: 'none'
});
}
// 下边是可以登录
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: '知道了'
});
}
}
})
// 下边是可以登录
uniCloud.callFunction({
name:'uni-id-cf',
data:{
action:'login',
params:{
"username": this.username,
"password": this.password,
"captcha":this.captcha
},
},
success: ({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: '知道了'
});
}
}
}
})
// 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(){
this.request(
'uni-id-cf/createCaptcha', {
scene: "login"
},
result => {
if (result.code === 0) {
this.captchaBase64 = result.captchaBase64
}
// this.-request(
// 'uni-id-cf/createCaptcha', {
// scene: "login"
// },
// result => {
// if (result.code === 0) {
// 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 @@
<uni-forms ref="form" :value="formData" :rules="rules">
<uni-forms-item name="phone">
<!-- 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>
</uni-forms-item>
<uni-forms-item name="code">
......@@ -35,7 +35,8 @@
export default {
mixins: [mixin],
data() {
return {
return {
lock:false,
formData: {
"phone": "",
'pwd': '',
......@@ -120,7 +121,8 @@
},
onLoad(event) {
if (event && event.phoneNumber) {
this.formData.phone = event.phoneNumber;
this.formData.phone = event.phoneNumber;
this.lock = true
}
},
onReady() {
......@@ -135,21 +137,42 @@
submit() {
this.$refs.form.submit()
.then(res => {
this.request('uni-id-cf/resetPwdBySmsCode', {
"mobile": this.formData.phone,
"code": this.formData.code,
"password": this.formData.pwd
}, result => {
console.log(result);
uni.showToast({
title: result.msg,
icon: 'none'
});
if (result.code === 0) {
uni.navigateBack()
}
// this.-request('uni-id-cf/resetPwdBySmsCode', {
// "mobile": this.formData.phone,
// "code": this.formData.code,
// "password": this.formData.pwd
// }, result => {
// console.log(result);
// uni.showToast({
// title: result.msg,
// icon: 'none'
// });
// if (result.code === 0) {
// 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';
uni.hideLoading()
})
},
submitForm(value) {
this.request('uni-id-cf/register',value,result=>{
console.log(result);
if(result.code === 0){
this.loginSuccess(result)
}
submitForm(params) {
// this.-request('uni-id-cf/register',params,result=>{
// console.log(result);
// if(result.code === 0){
// 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 @@
*/
submit() {
console.log(this.formData);
this.request('uni-id-cf/bind_mobile_by_sms', {
"mobile": this.formData.phone,
"code": this.formData.code
}, result=> {
console.log(result);
this.setUserInfo({"mobile":result.mobile})
uni.showToast({
title: result.msg,
icon: 'none'
});
if (result.code === 0) {
uni.navigateBack()
}
// this.-request('uni-id-cf/bind_mobile_by_sms', {
// "mobile": this.formData.phone,
// "code": this.formData.code
// }, result=> {
// console.log(result);
// this.setUserInfo({"mobile":result.mobile})
// uni.showToast({
// title: result.msg,
// icon: 'none'
// });
// if (result.code === 0) {
// 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 @@
<image class="avatarUrl" :src="userInfo.avatar||nullAvatarUrl" mode="widthFix"></image>
</view>
</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>
<uni-popup ref="dialog" type="dialog">
......@@ -70,10 +70,32 @@
"univerifyStyle": this.univerifyStyle,
success: async e => {
console.log(e.authResult);
this.request('uni-id-cf/bind_mobile_by_univerify',
e.authResult,
result=>
{
// this.-request('uni-id-cf/bind_mobile_by_univerify',
// e.authResult,
// 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);
if(result.code===0){
this.setUserInfo({"mobile":result.mobile})
......@@ -86,9 +108,9 @@
uni.closeAuthView()
}
});
}
}
)
}
}
})
},
fail: (err) => {
console.log(err);
......@@ -104,7 +126,7 @@
})
},
setNickname(nickname) {
console.log(nickname);
console.log(9527,nickname);
if (nickname) {
usersTable.where('_id==$env.uid').update({
nickname
......
'use strict';
let uniID = require('uni-id')
const uniCaptcha = require('uni-captcha')
const createConfig = require('uni-config-center')
const uniIdConfig = createConfig({
pluginId: 'uni-id'
})._config
const db = uniCloud.database()
const dbCmd = db.command
'use strict';
let uniID = require('uni-id')
const uniCaptcha = require('uni-captcha')
const createConfig = require('uni-config-center')
const uniIdConfig = createConfig({
pluginId: 'uni-id'
})._config
const db = uniCloud.database()
const dbCmd = db.command
exports.main = async (event, context) => {
//UNI_WYQ:这里的uniID换成新的,保证多人访问不会冲突
//UNI_WYQ:这里的uniID换成新的,保证多人访问不会冲突
uniID = uniID.createInstance({context})
console.log('event : ' + JSON.stringify(event))
/*
......@@ -36,117 +36,117 @@ exports.main = async (event, context) => {
用户就这样轻易地伪造了他人的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']
if (!noCheckAction.includes(action)) {
if (!uniIdToken) {
return {
code: 403,
msg: '缺少token'
}
}
let payload = await uniID.checkToken(uniIdToken)
if (payload.code && payload.code > 0) {
return payload
}
params.uid = payload.uid
}
//3.注册成功后创建新用户的积分表方法
async function registerSuccess(uid) {
await db.collection('uni-id-scores').add({
user_id: uid,
score: 1,
type: 1,
balance: 1,
comment: "",
create_date: Date.now()
})
}
//4.记录成功登录的日志方法
const loginLog = async (res = {}, type = 'login') => {
const now = Date.now()
const uniIdLogCollection = db.collection('uni-id-log')
let logData = {
deviceId: params.deviceId || context.DEVICEID,
ip: params.ip || context.CLIENTIP,
type,
ua: context.CLIENTUA,
create_date: now
};
Object.assign(logData,
res.code === 0 ? {
user_id: res.uid,
state: 1
} : {
state: 0
})
if (res.type == 'register') {
await registerSuccess(res.uid)
}
return await uniIdLogCollection.add(logData)
}
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 (!uniIdToken) {
return {
code: 403,
msg: '缺少token'
}
}
let payload = await uniID.checkToken(uniIdToken)
if (payload.code && payload.code > 0) {
return payload
}
params.uid = payload.uid
}
//3.注册成功后创建新用户的积分表方法
async function registerSuccess(uid) {
await db.collection('uni-id-scores').add({
user_id: uid,
score: 1,
type: 1,
balance: 1,
comment: "",
create_date: Date.now()
})
}
//4.记录成功登录的日志方法
const loginLog = async (res = {}, type = 'login') => {
const now = Date.now()
const uniIdLogCollection = db.collection('uni-id-log')
let logData = {
deviceId: params.deviceId || context.DEVICEID,
ip: params.ip || context.CLIENTIP,
type,
ua: context.CLIENTUA,
create_date: now
};
Object.assign(logData,
res.code === 0 ? {
user_id: res.uid,
state: 1
} : {
state: 0
})
if (res.type == 'register') {
await registerSuccess(res.uid)
}
return await uniIdLogCollection.add(logData)
}
let res = {}
switch (action) { //根据action的值执行对应的操作
case 'bind_mobile_by_univerify':
let {
appid, apiKey, apiSecret
} = uniIdConfig.service.univerify
let univerifyRes = await uniCloud.getPhoneNumber({
provider: 'univerify',
appid,
apiKey,
apiSecret,
access_token: params.access_token,
openid: params.openid
})
if (univerifyRes.code === 0) {
res = await uniID.bindMobile({
uid: params.uid,
mobile: univerifyRes.phoneNumber
})
res.mobile = univerifyRes.phoneNumber
}
break;
case 'bind_mobile_by_sms':
console.log({
uid: params.uid,
mobile: params.mobile,
code: params.code
});
res = await uniID.bindMobile({
uid: params.uid,
mobile: params.mobile,
code: params.code
})
console.log(res);
break;
case 'register':
var {
username, password, nickname
} = params
if (/^1\d{10}$/.test(username)) {
return {
code: 401,
msg: '用户名不能是手机号'
}
};
if (/^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/.test(username)) {
return {
code: 401,
msg: '用户名不能是邮箱'
}
}
res = await uniID.register({
username,
password,
nickname
});
if (res.code === 0) {
await registerSuccess(res.uid)
}
break;
switch (action) { //根据action的值执行对应的操作
case 'bind_mobile_by_univerify':
let {
appid, apiKey, apiSecret
} = uniIdConfig.service.univerify
let univerifyRes = await uniCloud.getPhoneNumber({
provider: 'univerify',
appid,
apiKey,
apiSecret,
access_token: params.access_token,
openid: params.openid
})
if (univerifyRes.code === 0) {
res = await uniID.bindMobile({
uid: params.uid,
mobile: univerifyRes.phoneNumber
})
res.mobile = univerifyRes.phoneNumber
}
break;
case 'bind_mobile_by_sms':
console.log({
uid: params.uid,
mobile: params.mobile,
code: params.code
});
res = await uniID.bindMobile({
uid: params.uid,
mobile: params.mobile,
code: params.code
})
console.log(res);
break;
case 'register':
var {
username, password, nickname
} = params
if (/^1\d{10}$/.test(username)) {
return {
code: 401,
msg: '用户名不能是手机号'
}
};
if (/^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/.test(username)) {
return {
code: 401,
msg: '用户名不能是邮箱'
}
}
res = await uniID.register({
username,
password,
nickname
});
if (res.code === 0) {
await registerSuccess(res.uid)
}
break;
case 'login':
//防止黑客恶意破解登录,连续登录失败一定次数后,需要用户提供验证码
const getNeedCaptcha = async () => {
......@@ -165,192 +165,192 @@ exports.main = async (event, context) => {
.get();
return recentRecord.data.filter(item => item.state === 0).length === recordSize;
}
let passed = false;
let needCaptcha = await getNeedCaptcha();
console.log('needCaptcha', needCaptcha);
if (needCaptcha) {
res = await uniCaptcha.verify({
...params,
scene: 'login'
})
if (res.code === 0) passed = true;
}
if (!needCaptcha || passed) {
res = await uniID.login({
...params,
queryField: ['username', 'email', 'mobile']
});
await loginLog(res);
needCaptcha = await getNeedCaptcha();
}
res.needCaptcha = needCaptcha;
break;
let passed = false;
let needCaptcha = await getNeedCaptcha();
console.log('needCaptcha', needCaptcha);
if (needCaptcha) {
res = await uniCaptcha.verify({
...params,
scene: 'login'
})
if (res.code === 0) passed = true;
}
if (!needCaptcha || passed) {
res = await uniID.login({
...params,
queryField: ['username', 'email', 'mobile']
});
await loginLog(res);
needCaptcha = await getNeedCaptcha();
}
res.needCaptcha = needCaptcha;
break;
case 'login_by_weixin':
res = await uniID.loginByWeixin(params);
await uniID.updateUser({
uid: res.uid,
username: "微信用户"
});
res.userInfo.username = "微信用户"
await loginLog(res)
break;
case 'login_by_univerify':
res = await uniID.loginByuniverify(params)
await loginLog(res)
break;
case 'login_by_apple':
res = await uniID.loginByApple(params)
await loginLog(res)
break;
case 'checkToken':
res = await uniID.checkToken(uniIdToken);
break;
case 'logout':
res = await uniID.logout(uniIdToken)
break;
case 'sendSmsCode':
// 测试期间短信统一用 123456 正式项目删除即可
return uniID.setVerifyCode({
mobile: params.mobile,
code: '123456',
type: params.type
})
// 简单限制一下客户端调用频率
const ipLimit = await db.collection('uni-verify').where({
ip: context.CLIENTIP,
created_at: dbCmd.gt(Date.now() - 60000)
}).get()
if (ipLimit.data.length > 0) {
return {
code: 429,
msg: '请求过于频繁'
}
}
const templateId = '11753' // 替换为自己申请的模板id
if (!templateId) {
return {
code: 500,
msg: 'sendSmsCode需要传入自己的templateId,参考https://uniapp.dcloud.net.cn/uniCloud/uni-id?id=sendsmscode'
}
}
const randomStr = '00000' + Math.floor(Math.random() * 1000000)
const code = randomStr.substring(randomStr.length - 6)
res = await uniID.sendSmsCode({
mobile: params.mobile,
code,
type: params.type,
templateId
})
await loginLog(res)
break;
case 'loginBySms':
if (!params.code) {
return {
code: 500,
msg: '请填写验证码'
}
}
if (!/^1\d{10}$/.test(params.mobile)) {
return {
code: 500,
msg: '手机号码填写错误'
}
}
res = await uniID.loginBySms(params)
await loginLog(res)
break;
case 'inviteLogin':
if (!params.code) {
return {
code: 500,
msg: '请填写验证码'
}
}
res = await uniID.loginBySms({
...params,
type: 'register'
})
break;
case 'resetPwdBySmsCode':
if (!params.code) {
return {
code: 500,
msg: '请填写验证码'
}
}
if (!/^1\d{10}$/.test(params.mobile)) {
return {
code: 500,
msg: '手机号码填写错误'
}
}
let loginBySmsRes = await uniID.loginBySms(params)
console.log(loginBySmsRes);
if (loginBySmsRes.code === 0) {
res = await uniID.resetPwd({
password: params.password,
"uid": loginBySmsRes.uid
})
} else {
return loginBySmsRes
}
break;
case 'getInviteCode':
res = await uniID.getUserInfo({
uid: params.uid,
field: ['my_invite_code']
})
if (res.code === 0) {
res.myInviteCode = res.userInfo.my_invite_code
delete res.userInfo
}
break;
case 'getInvitedUser':
res = await uniID.getInvitedUser(params)
break;
case 'updatePwd':
res = await uniID.updatePwd({
uid: params.uid,
...params
})
break;
case 'createCaptcha':
res = await uniCaptcha.create(params)
break;
case 'refreshCaptcha':
res = await uniCaptcha.refresh(params)
break;
case 'registerAdmin':
var {
username, password
} = params
let {
total
} = await db.collection('uni-id-users').where({
role: 'admin'
}).count()
if (total) {
return {
code: 10001,
message: '超级管理员已存在,请登录...'
}
}
return this.ctx.uniID.register({
username,
password,
role: ["admin"]
})
break;
default:
res = {
code: 403,
msg: '非法访问'
}
break;
}
//返回数据给客户端
return res
res = await uniID.loginByWeixin({...params});
await uniID.updateUser({
uid: res.uid,
username: "微信用户"
});
res.userInfo.username = "微信用户"
await loginLog(res)
break;
case 'login_by_univerify':
res = await uniID.loginByuniverify(params)
await loginLog(res)
break;
case 'login_by_apple':
res = await uniID.loginByApple(params)
await loginLog(res)
break;
case 'checkToken':
res = await uniID.checkToken(uniIdToken);
break;
case 'logout':
res = await uniID.logout(uniIdToken)
break;
case 'sendSmsCode':
// 测试期间短信统一用 123456 正式项目删除即可
return uniID.setVerifyCode({
mobile: params.mobile,
code: '123456',
type: params.type
})
// 简单限制一下客户端调用频率
const ipLimit = await db.collection('uni-verify').where({
ip: context.CLIENTIP,
created_at: dbCmd.gt(Date.now() - 60000)
}).get()
if (ipLimit.data.length > 0) {
return {
code: 429,
msg: '请求过于频繁'
}
}
const templateId = '11753' // 替换为自己申请的模板id
if (!templateId) {
return {
code: 500,
msg: 'sendSmsCode需要传入自己的templateId,参考https://uniapp.dcloud.net.cn/uniCloud/uni-id?id=sendsmscode'
}
}
const randomStr = '00000' + Math.floor(Math.random() * 1000000)
const code = randomStr.substring(randomStr.length - 6)
res = await uniID.sendSmsCode({
mobile: params.mobile,
code,
type: params.type,
templateId
})
await loginLog(res)
break;
case 'loginBySms':
if (!params.code) {
return {
code: 500,
msg: '请填写验证码'
}
}
if (!/^1\d{10}$/.test(params.mobile)) {
return {
code: 500,
msg: '手机号码填写错误'
}
}
res = await uniID.loginBySms(params)
await loginLog(res)
break;
case 'inviteLogin':
if (!params.code) {
return {
code: 500,
msg: '请填写验证码'
}
}
res = await uniID.loginBySms({
...params,
type: 'register'
})
break;
case 'resetPwdBySmsCode':
if (!params.code) {
return {
code: 500,
msg: '请填写验证码'
}
}
if (!/^1\d{10}$/.test(params.mobile)) {
return {
code: 500,
msg: '手机号码填写错误'
}
}
let loginBySmsRes = await uniID.loginBySms(params)
console.log(loginBySmsRes);
if (loginBySmsRes.code === 0) {
res = await uniID.resetPwd({
password: params.password,
"uid": loginBySmsRes.uid
})
} else {
return loginBySmsRes
}
break;
case 'getInviteCode':
res = await uniID.getUserInfo({
uid: params.uid,
field: ['my_invite_code']
})
if (res.code === 0) {
res.myInviteCode = res.userInfo.my_invite_code
delete res.userInfo
}
break;
case 'getInvitedUser':
res = await uniID.getInvitedUser(params)
break;
case 'updatePwd':
res = await uniID.updatePwd({
uid: params.uid,
...params
})
break;
case 'createCaptcha':
res = await uniCaptcha.create(params)
break;
case 'refreshCaptcha':
res = await uniCaptcha.refresh(params)
break;
case 'registerAdmin':
var {
username, password
} = params
let {
total
} = await db.collection('uni-id-users').where({
role: 'admin'
}).count()
if (total) {
return {
code: 10001,
message: '超级管理员已存在,请登录...'
}
}
return this.ctx.uniID.register({
username,
password,
role: ["admin"]
})
break;
default:
res = {
code: 403,
msg: '非法访问'
}
break;
}
//返回数据给客户端
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.
先完成此消息的编辑!
想要评论请 注册