108 lines
2.9 KiB
JavaScript
108 lines
2.9 KiB
JavaScript
const sessionWeCom = require("./weCom/index");
|
|
const common = require("../../common");
|
|
let db = null;
|
|
let collection = null;
|
|
exports.main = async (event, mongodb) => {
|
|
db = mongodb;
|
|
collection = db.collection("corp-session-archive");
|
|
switch (event.type) {
|
|
case "createSessionArchiveAuth":
|
|
return await exports.createSessionArchiveAuth(event);
|
|
case "getCorpSessionArchive":
|
|
return await exports.getCorpSessionArchive(event);
|
|
case "updateCorpSessionArchive":
|
|
return await exports.updateCorpSessionArchive(event);
|
|
}
|
|
};
|
|
|
|
exports.createSessionArchiveAuth = async ({ corpId }) => {
|
|
const res = await collection.find({ corpId }).toArray();
|
|
if (res.length === 0) {
|
|
await collection.insertOne({
|
|
corpId,
|
|
_id: common.generateRandomString(24),
|
|
});
|
|
}
|
|
};
|
|
|
|
exports.getCorpSessionArchive = async ({ corpId }) => {
|
|
try {
|
|
// 使用 MongoDB 的原生查询语法
|
|
let res = await db
|
|
.collection("corp-session-archive")
|
|
.find({ corpId })
|
|
.toArray();
|
|
if (res.length === 0) {
|
|
// 如果没有数据,插入新的记录
|
|
await db
|
|
.collection("corp-session-archive")
|
|
.insertOne({ corpId, _id: common.generateRandomString(24) });
|
|
// 设置PublicKey
|
|
await sessionWeCom.main({ type: "setCorpPublicKey", corpId }, db);
|
|
// 再次查询
|
|
res = await db
|
|
.collection("corp-session-archive")
|
|
.find({ corpId })
|
|
.toArray();
|
|
}
|
|
return {
|
|
success: true,
|
|
data: res[0],
|
|
message: "获取成功",
|
|
};
|
|
} catch (error) {
|
|
console.error("获取失败:", error);
|
|
return {
|
|
success: false,
|
|
message: "获取失败",
|
|
};
|
|
}
|
|
};
|
|
|
|
exports.updateCorpSessionArchive = async (context) => {
|
|
const { publicKey, privateKey, corpId } = context;
|
|
try {
|
|
const res = await collection.find({ corpId }).toArray();
|
|
let item = res[0];
|
|
if (!item) {
|
|
return {
|
|
success: false,
|
|
message: "机构未授权会话存档",
|
|
};
|
|
} else {
|
|
let publicKeys = item.publicKeys || [];
|
|
let publicKeyVersion = 1;
|
|
if (publicKeys.length === 0) {
|
|
publicKeys = [
|
|
{
|
|
publicKey,
|
|
privateKey,
|
|
publicKeyVersion,
|
|
},
|
|
];
|
|
} else {
|
|
// 获取最新的公钥
|
|
let latestPublicKey = publicKeys[publicKeys.length - 1];
|
|
publicKeyVersion = latestPublicKey.publicKeyVersion + 1;
|
|
// 如果最新的公钥版本号大于当前的公钥版本号,则更新
|
|
publicKeys.push({
|
|
publicKey,
|
|
privateKey,
|
|
publicKeyVersion,
|
|
});
|
|
}
|
|
await collection.updateOne({ corpId }, { $set: { publicKeys } });
|
|
return {
|
|
success: true,
|
|
publicKeyVersion,
|
|
message: "更新成功",
|
|
};
|
|
}
|
|
} catch (e) {
|
|
return {
|
|
success: false,
|
|
message: "更新失败",
|
|
};
|
|
}
|
|
};
|