提交 812b079d 编写于 作者: DCloud_JSON's avatar DCloud_JSON

Update index.js

上级 d827251d
'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))
/* /*
...@@ -17,7 +17,7 @@ exports.main = async (event, context) => { ...@@ -17,7 +17,7 @@ exports.main = async (event, context) => {
params:业务数据内容 params:业务数据内容
uniIdToken:系统自动传递的token,数据来源客户端的 uni.getStorageSync('uni_id_token') uniIdToken:系统自动传递的token,数据来源客户端的 uni.getStorageSync('uni_id_token')
*/ */
const {action,uniIdToken,params} = event; const {action,uniIdToken} = event;
let params = event.params || {}; let params = event.params || {};
/* /*
2.在某些操作之前我们要对用户对身份进行校验(也就是要检查用户的token)再将得到的uid写入params.uid 2.在某些操作之前我们要对用户对身份进行校验(也就是要检查用户的token)再将得到的uid写入params.uid
...@@ -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
}; };
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册