Skip to content

Commit

Permalink
迁移laf官方资源,同步云函数 (#34)
Browse files Browse the repository at this point in the history
* 对称签名等修复

* Laf对称加密支持一下

* 1

* 测试数据切换

* 1

* v1.11.0

* 更新云函数
  • Loading branch information
Zing22 authored Jul 3, 2023
1 parent 2bb75f9 commit 401b56f
Show file tree
Hide file tree
Showing 11 changed files with 177 additions and 60 deletions.
52 changes: 37 additions & 15 deletions functions/__interceptor__.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ import CryptoJS from 'crypto-js';

// 检查签名是否有效
function verifySign(signKey: string, data: string, signature: string) {
if (!signKey || !data || !signature) {
return false;
}

// 使用HMAC-SHA256算法进行验证
const isValid = CryptoJS.HmacSHA256(data, signKey).toString() === signature;
Expand All @@ -20,27 +23,46 @@ function compareDateStrings(dateString1: string, dateString2: string, n: number)


export async function main(ctx: FunctionContext) {
let signKey = cloud.env.SIGN_KEY;
if (!signKey) {
// 没有开启
// 请求的实际IP
const ip = ctx.headers['x-real-ip']
const { host } = ctx.headers;
const { APPID, DEV_IPS } = cloud.env;

if (ip === undefined && host === `${APPID}.${APPID}:8000`) {
// 触发器触发
return true;
}
const { signdata, signstr } = ctx.headers;
const isValid = verifySign(signKey, signdata, signstr);

if (!isValid) {
console.log("invalid sign");
return false;
// 白名单ip,用于开发
if (DEV_IPS && DEV_IPS.split(",").includes(ip)) {
return true;
}

// 检查时间
const now = new Date().toDateString();
const threshold = 30; // 秒
const timeCheck = compareDateStrings(now, signdata, threshold);

if (!timeCheck) {
console.log("time check failed");
return false;
let signKey = cloud.env.SIGN_KEY;
if (signKey) {
// 开启了签名检查
const { signdata, signstr } = ctx.headers;
const isValid = verifySign(signKey, signdata, signstr);

if (!isValid) {
console.log("invalid sign");
console.log(ctx.headers);
console.log(cloud.env);
return false;
}

// 检查时间
const now = new Date().toISOString();
const threshold = 60; // 秒
const timeCheck = compareDateStrings(now, signdata, threshold);

if (!timeCheck) {
console.log("time check failed", now, signdata);
console.log(ctx.headers);
console.log(cloud.env);
return false;
}
}

return true;
Expand Down
2 changes: 1 addition & 1 deletion functions/__interceptor__.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
name: __interceptor__
methods:
- GET
- POST
- GET
tags: []
31 changes: 31 additions & 0 deletions functions/addRecords.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// addRecords 数据库操作云函数
import cloud from '@lafjs/cloud'
import { EJSON } from 'bson'

const db = cloud.database();
const _ = db.command;

exports.main = async function (ctx: FunctionContext) {
// body, query 为请求参数, auth 是授权对象
const { auth, body, query } = ctx;

const collection = body.collection;
var data = body.data;
data = Buffer.from(data, "base64").toString('utf-8');
data = JSON.parse(data);
console.log("curdOp param:", body);

for (var idx in data) {
var record = EJSON.parse(data[idx]);
console.log("mdate type:", typeof (record.mdate));
var id = record._id;
console.log(id);
delete record._id;
await db.collection(collection).doc(id).set(record);
}
return "success";
}

async function deleteAll(collection) {
return await db.collection(collection).remove({ multi: true });
}
4 changes: 4 additions & 0 deletions functions/addRecords.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
name: addRecords
methods:
- POST
tags: []
11 changes: 9 additions & 2 deletions functions/curdOp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,9 @@ const permissionAuthor = {
"update": {
"feedback": true
},
"remove": {},
"remove": {
"comment": true
},
"set": {},
"inc": {},
}
Expand All @@ -104,6 +106,11 @@ exports.main = async function (ctx: FunctionContext) {
const permissionLevel = permissionNeed[operation][collection]; // 操作要求的最低权限
console.log("permissionLevel:", permissionLevel)

if (permissionLevel === undefined) {
console.log("unk req.")
return;
}

console.log("curdOp param:", body);
// TODO, 不要login了
if (!openid) {
Expand All @@ -117,6 +124,7 @@ exports.main = async function (ctx: FunctionContext) {
const item_id = body.item_id;
var data = body.data;


// 检查权限
if (permissionLevel) {
const allowAuthor = permissionAuthor[operation][collection];
Expand All @@ -126,7 +134,6 @@ exports.main = async function (ctx: FunctionContext) {
}
}


if (operation == "add") { // 添加记录
// Laf云不会主动存储 _openid ,但是微信云(在前端直接往数据库增加记录时)会
// 前端可能需要跟据 _openid 字段进行数据库搜索,故手动保存
Expand Down
25 changes: 25 additions & 0 deletions functions/dropdb.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import cloud from '@lafjs/cloud'

const colls = []

export default async function (ctx: FunctionContext) {
//查询全部集合名
const allColls = await cloud.mongo.db.listCollections().toArray();
let names = [];
for (const x of allColls) {
if (x.name.startsWith("__")) {
continue;
}
names.push(x.name);
}
console.log(names);

// 删除coll
const db = cloud.database();
for (const coll of colls) {
const count = (await db.collection(coll).count()).total;
console.log(`dropping ${coll} with ${count} items...`);
cloud.mongo.db.dropCollection(coll);
console.log(`dropping ${coll} done.`);
}
}
3 changes: 3 additions & 0 deletions functions/dropdb.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
name: dropdb
methods: []
tags: []
23 changes: 21 additions & 2 deletions functions/getPhotoRank.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ exports.main = async function (ctx: FunctionContext) {
const today = new Date(), y = today.getFullYear(), m = today.getMonth();
const firstDay = new Date(y, m, 1);
const qf = { mdate: _.gt(firstDay), verified: true };

// 先取出集合记录总数
const countResult = await db.collection('photo').where(qf).count();
const total = countResult.total;
Expand Down Expand Up @@ -46,6 +46,10 @@ exports.main = async function (ctx: FunctionContext) {

const stat = getStat(all_photos.data);
await db.collection('photo_rank').add({ stat, mdate: today })

// 删除旧的
await removeOld();

return { all_photos: all_photos, stat: stat };
}

Expand All @@ -64,8 +68,23 @@ function getStat(all_photos) {
count: 1
}
} else {
stat[key].count ++;
stat[key].count++;
}
}
return stat;
}


// 删除旧的
async function removeOld() {
const db = cloud.database();
const _ = db.command;

var weekAgo = new Date();
weekAgo.setDate(weekAgo.getDate() - 7);

const res = await db.collection('photo_rank')
.where({ mdate: _.lt(weekAgo) })
.remove({ multi: true });
console.log("remove old", res);
}
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
"@kubernetes/client-node": "^0.18.0",
"@lafjs/cloud": "1.0.0-beta.7",
"chatgpt": "^5.2.5",
"alipay-sdk": "^3.2.0",
"axios": "^1.4.0",
"database-proxy": "^0.8.2",
"dayjs": "^1.11.7",
Expand Down
7 changes: 7 additions & 0 deletions policies/catface.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
- collectionName: photo
rules:
read: true
count: true
update: false
remove: false
add: false
78 changes: 39 additions & 39 deletions policies/miniprogram.yaml
Original file line number Diff line number Diff line change
@@ -1,77 +1,77 @@
- collectionName: setting
- collectionName: cat
rules:
read: true
count: true
read: openid
count: openid
update: false
remove: false
add: false
- collectionName: science
- collectionName: comment
rules:
read: true
count: true
read: openid
count: openid
update: false
remove: false
add: false
- collectionName: comment
add: openid
- collectionName: feedback
rules:
read: true
count: true
read: openid
count: openid
update: false
remove: false
add: true
- collectionName: news
add: openid
- collectionName: inter
rules:
read: true
count: true
read: openid
count: openid
update: false
remove: false
add: false
- collectionName: reward
add: openid
- collectionName: news
rules:
read: true
count: true
read: openid
count: openid
update: false
remove: false
add: false
- collectionName: user
- collectionName: photo
rules:
read: true
count: true
read: openid
count: openid
update: false
remove: false
add: false
add: openid
- collectionName: photo_rank
rules:
read: true
count: true
read: openid
count: openid
update: false
remove: false
add: false
- collectionName: inter
- collectionName: reward
rules:
read: true
count: true
read: openid
count: openid
update: false
remove: false
add: true
- collectionName: cat
add: false
- collectionName: science
rules:
read: true
count: true
read: openid
count: openid
update: false
remove: false
add: false
- collectionName: photo
- collectionName: setting
rules:
read: true
count: true
read: openid
count: openid
update: false
remove: false
add: true
- collectionName: feedback
add: false
- collectionName: user
rules:
read: true
count: true
read: openid
count: openid
update: false
remove: false
add: true
add: false

0 comments on commit 401b56f

Please sign in to comment.