import cloud from '@lafjs/cloud'
import moment from 'moment'
const db = cloud.database()
const _ = db.command
const $ = _.aggregate
export async function main(ctx: FunctionContext) {
const { headers, query, body, params, user, requestId, method, request } = ctx
// 获取请求的实际IP
const ip = headers['x-real-ip'] ? headers['x-real-ip'] : headers['x-forwarded-for']
if (ip == "null") return false
// 判断是否在黑名单表,如果在的话直接拒绝请求
const sys_banIp = db.collection("sys_banIp");
let banRes = await sys_banIp.where({
ip: _.eq(ip)
}).getOne()
if (banRes.data !== null) {
ctx.response.status(401)
ctx.response.json({ "success": false, "message": "黑名单用户,禁止登陆!!!如有问题,请联系管理员!!!", "data": { "error": "Forbidden", "requestId": requestId } })
return false
}
// 获取请求信息
const user_agent = headers['user-agent']
const host = headers['host']
const referer = headers['referer']
const func = request.params.name
const sys_requestIp = db.collection("sys_requestIp");
// 添加请求IP到数据库,并自动添加 add_time
let requestIp = await sys_requestIp.add({
req_id: requestId,
ip: ip,
host: host,
user_agent: user_agent,
referer: referer,
func: func,
query: query,
body: body,
params: params,
user: user,
method: method,
req_time: moment(new Date()).utcOffset(8).format('YYYY/MM/DD HH:mm:ss')
})
// console.log(requestIp)
//获取当前IP的时间段的访问次数
const Interval = 1 // 间隔分钟
const times = 60 // 间隔Interval分钟内限制最大访问次数
let timesRes = await sys_requestIp.where({
// 主表where条件
req_time: _.and(_.gte(Date.now() - Interval * 60 * 1000), _.lte(Date.now()))
}).count()
// console.log(timesRes)
if (timesRes.total <= times) {
// 返回 true 则会去继续请求实际的云函数
return true
} else {
// 返回 false 则不会去继续请求实际的云函数
return false
}
}
更新一下