feat: 支持aes传输 (#10)

This commit is contained in:
ZhangYuan 2023-11-29 15:23:28 +08:00 committed by GitHub
parent 630fe0541c
commit 435431feff
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 73 additions and 4 deletions

View File

@ -16,13 +16,15 @@
"dev": "npm run copy && nodemon -e js,mjs,json,ts --exec 'npm run launch:dev' --watch ./src"
},
"devDependencies": {
"@types/crypto-js": "^4.2.1",
"@types/koa": "^2.13.8",
"@types/koa-bodyparser": "^4.3.10",
"@types/koa-router": "^7.4.4",
"nodemon": "^2.0.20",
"typescript": "^4.8.4"
},
"dependencies": {
"@types/koa": "^2.13.8",
"@types/koa-bodyparser": "^4.3.10",
"@types/koa-router": "^7.4.4",
"crypto-js": "^4.2.0",
"joi": "^17.9.2",
"jsonwebtoken": "^9.0.1",
"koa": "^2.14.2",

View File

@ -2,6 +2,13 @@ const config = {
mongo:{
url: process.env.xiaojuSurveyMongoUrl ||'mongodb://localhost:27017',
dbName:'xiaojuSurvey',
},
session:{
expireTime: parseInt(process.env.xiaojuSurveySessionExpireTime) || 8*3600*1000
},
encrypt:{
type: process.env.xiaojuSurveyEncryptType ||'aes',
aesCodelength: parseInt(process.env.xiaojuSurveyAesCodelength) || 10 //aes密钥长度
}
}

View File

@ -33,6 +33,15 @@ export default class SurveyPublish {
data: data,
}
}
@SurveyServer({ type: 'http', method: 'get', routerName: '/getEncryptInfo' })
async getEncryptInfo({ req, res }: { req: Request, res: Response }) {
const data = await surveySubmitService.getEncryptInfo()
return {
code: 200,
data: data,
}
}
// 提交问卷
@SurveyServer({ type: 'http', method: 'post', routerName: '/submit' })
async submit({ req, res }: { req: Request, res: Response }) {
@ -43,6 +52,7 @@ export default class SurveyPublish {
surveyPath: Joi.string().required(),
data: Joi.string().required(),
encryptType: Joi.string(),
sessionId: Joi.string(),
}).validate(req.body, { allowUnknown: true }));
await surveySubmitService.submit({ surveySubmitData })
return {

View File

@ -1,10 +1,49 @@
import { mongo } from '../db/mongo'
import { getStatusObject, getMapByKey } from '../utils/index'
import { getStatusObject, getMapByKey, randomCode } from '../utils/index'
import { SURVEY_STATUS, CommonError } from '../../../types/index'
import { surveyKeyStoreService } from './surveyKeyStoreService'
import { getConfig } from '../config/index'
import * as CryptoJS from 'crypto-js'
import * as aes from 'crypto-js/aes';
import * as moment from 'moment'
const config = getConfig()
class SurveySubmitService {
async addSessionData(data) {
const surveySession = await mongo.getCollection({ collectionName: 'surveySession' });
const surveySessionRes = await surveySession.insertOne({
data,
expireDate: Date.now() + config.session.expireTime
})
return {
sessionId: surveySessionRes.insertedId.toString(),
...data
}
}
async getSessionData(sessionId) {
const surveySession = await mongo.getCollection({ collectionName: 'surveySession' });
const sessionObjectId = mongo.getObjectIdByStr(sessionId)
const surveySessionRes = await surveySession.findOne({ _id: sessionObjectId })
await surveySession.deleteMany({ expireDate: { $lt: Date.now() } })
return { sessionId, data: surveySessionRes.data }
}
async getEncryptInfo() {
const encryptType = config.encrypt.type
let data = {}
if (encryptType === 'aes') {
data = await this.addSessionData({
code: randomCode(config.encrypt.aesCodelength)
})
}
return {
encryptType,
data
}
}
async submit({ surveySubmitData }: { surveySubmitData: any }) {
const surveyMeta = await mongo.getCollection({ collectionName: 'surveyMeta' });
const surveyMetaRes = mongo.convertId2StringByDoc(
@ -19,6 +58,9 @@ class SurveySubmitService {
const surveySubmit = await mongo.getCollection({ collectionName: 'surveySubmit' });
if (surveySubmitData.encryptType === 'base64') {
surveySubmitData.data = JSON.parse(decodeURIComponent(Buffer.from(surveySubmitData.data, "base64").toString()))
} else if (surveySubmitData.encryptType === 'aes') {
const sessionData = await this.getSessionData(surveySubmitData.sessionId)
surveySubmitData.data = JSON.parse(decodeURIComponent(aes.decrypt(surveySubmitData.data, sessionData.data.code).toString(CryptoJS.enc.Utf8)))
} else {
surveySubmitData.data = JSON.parse(surveySubmitData.data)
}

View File

@ -21,4 +21,12 @@ export function getValidateValue<T=any>(validationResult:Joi.ValidationResult<T>
throw new CommonError(validationResult.error.details.map(e=>e.message).join())
}
return validationResult.value;
}
export function randomCode(length) {
let charList:Array<string> = []
for(let i=0;i<length;i++) {
charList.push(Math.floor(Math.random()*16).toString(16))
}
return charList.join('')
}