Browse Source

function getUserToken ready

master
master 8 months ago
parent
commit
5a7d2b2396
  1. 27
      common.mjs
  2. 7
      conf/config.json
  3. 24
      heroUnion.mjs
  4. 9
      test/common.test.mjs

27
common.mjs

@ -4,10 +4,16 @@
import fs from 'node:fs'; import fs from 'node:fs';
import { readdir, readFile } from 'node:fs/promises'; import { readdir, readFile } from 'node:fs/promises';
import { resolve } from 'node:path';
import md5 from 'md5'; import md5 from 'md5';
class Common { class Common {
//构造函数,设置默认配置
constructor() {
this.configDir = resolve('conf/');
}
sortDict(obj) { //dict按key排序 sortDict(obj) { //dict按key排序
return Object.keys(obj).sort().reduce(function (result, key) { return Object.keys(obj).sort().reduce(function (result, key) {
result[key] = obj[key]; result[key] = obj[key];
@ -41,6 +47,27 @@ class Common {
return md5( JSON.stringify(this.sortDict(params)) + token ); return md5( JSON.stringify(this.sortDict(params)) + token );
} }
//从conf/目录读取配置文件内容
async getConfigFromJsonFile(filename) {
let data = null;
let filePath = this.configDir + `/${filename}`;
if (fs.existsSync(filePath)) {
try {
const contents = await readFile(filePath, { encoding: 'utf8' });
if (contents) {
data = JSON.parse(contents);
}
} catch (err) {
console.error(`[FAILED] get config content from %s failed, error: %s`, filePath, err.message);
}
}else {
console.error("[ERROR] file %s not exist.", filePath);
}
return data;
}
} }
let commonFuns = new Common(); let commonFuns = new Common();

7
conf/config.json

@ -0,0 +1,7 @@
{
"name": "Hero Union",
"version": "0.0.1",
"tokens": {
"demo": "hello#world!"
}
}

24
heroUnion.mjs

@ -28,6 +28,8 @@ class HeroUnion {
//构造函数,设置默认配置 //构造函数,设置默认配置
constructor() { constructor() {
this.config = null;
//this.task_data_dir = path.resolve('./tmp/data/'); //任务数据保存目录 //this.task_data_dir = path.resolve('./tmp/data/'); //任务数据保存目录
this.task_cache_time = 86400; //任务数据最长缓存时间,单位:秒 this.task_cache_time = 86400; //任务数据最长缓存时间,单位:秒
this.task_data_max_size = 1024; //任务数据最大字节数,单位:KB this.task_data_max_size = 1024; //任务数据最大字节数,单位:KB
@ -73,6 +75,14 @@ class HeroUnion {
return JSON.stringify(data).length > this.task_data_max_size * 1024; return JSON.stringify(data).length > this.task_data_max_size * 1024;
} }
async getConfig(forceReload) {
if ( !this.config || (typeof(forceReload) != 'undefined' && forceReload) ) {
this.config = await common.getConfigFromJsonFile('config.json');
}
return this.config;
}
//--任务相关功能-- //--任务相关功能--
//根据任务提交者ID和时间戳生成任务ID编号 //根据任务提交者ID和时间戳生成任务ID编号
@ -213,9 +223,10 @@ class HeroUnion {
return this.tasks.find((item) => item.id == id); return this.tasks.find((item) => item.id == id);
} }
//TODO: 根据uuid获取用户的签名密钥 //根据uuid获取用户的签名密钥
getUserToken(uuid) { async getUserToken(uuid) {
return 'token'; let config = await this.getConfig();
return config && typeof(config.tokens[uuid]) != 'undefined' ? config.tokens[uuid] : '';
} }
//任务完成触发回调通知 //任务完成触发回调通知
@ -232,17 +243,18 @@ class HeroUnion {
"task_result": task.results, "task_result": task.results,
"timestamp": this.getTimestamp(), "timestamp": this.getTimestamp(),
}; };
params.sign = common.sign(params, this.getUserToken(task.uuid)); let token = await this.getUserToken(task.uuid);
params.sign = common.sign(params, token);
const response = await axios.post(notify_url, params, {timeout: this.notify_timeout*1000}); const response = await axios.post(notify_url, params, {timeout: this.notify_timeout*1000});
if (response.status == 200) { if (response.status == 200) {
notified = true; notified = true;
}else { }else {
console.error('Notify to %s failed, response status: %s, status text: %s, result: %s', console.error('[FAILED] Notify to %s failed, response status: %s, status text: %s, result: %s',
notify_url, response.status, response.statusText, response.daa); notify_url, response.status, response.statusText, response.daa);
} }
} }
}catch(err) { }catch(err) {
console.error('Notify to %s failed: %s', notify_url, err); console.error('[ERROR] Notify to %s failed: %s', notify_url, err);
} }
return notified; return notified;

9
test/common.test.mjs

@ -32,3 +32,12 @@ test('Common function joinDict test', (t) => {
assert.strictEqual(common.joinDict(common.sortDict(params)), expectRes); assert.strictEqual(common.joinDict(common.sortDict(params)), expectRes);
}); });
test('Common function getConfigFromJsonFile test', async (t) => {
let filename = 'config.json';
let config = await common.getConfigFromJsonFile(filename);
assert.ok(config);
const expectName = 'Hero Union';
assert.strictEqual(config.name, expectName);
});

Loading…
Cancel
Save