flexbiz-server
Version:
Flexible Server
24 lines (23 loc) • 10.3 kB
JavaScript
const fs=require("fs"),async=require("async"),logger=require("./libs/logger.js");global.Logger=logger;const prototypes=require("./libs/prototypes.js"),TransactionPool=require("./libs/BlockchainTransactionPool"),leanID=require("./libs/mongooseLeanId"),mongooseSecurityPlugin=require("./libs/mongooseSecurityPlugin"),deletePost=require("./libs/mongooseDeletePost");
function globalListinfoCodePlugin($schema$$){$schema$$.path("listinfo_code")||$schema$$.add({listinfo_code:{type:String,default:null}});$schema$$.path("id_client")||$schema$$.add({id_client:{type:String,default:null}})}global.blockchainTransactionPool=new TransactionPool;global.new_schedules=[];global.rootDir=__dirname;global.ctrlVouchers={};global.controllers={};global.report_controllers={};global.postingVouchers={};global.cacheDatas={};
global.socketContainer={loadConnectionId:async()=>new Promise($res$$=>{global.clientRedis.get("client-io",function($err$$,$reply$$){if($err$$)return console.error($err$$),$res$$({});if($reply$$)try{let $ios$$=JSON.parse($reply$$);return $res$$($ios$$||{})}catch($e$$){return console.error($e$$),$res$$({})}else return $res$$({})})}),saveConnectionId:async($clientIO$$={})=>new Promise(($res$$,$rej$$)=>{global.clientRedis.set("client-io",JSON.stringify($clientIO$$),$e$$=>{if($e$$)return console.error($e$$),
$rej$$($e$$);$res$$($clientIO$$)})})};global.clientIO={};global.model_books="socai socaitmp socainpp vsocai sokho sokhott sokhonpp sokhokhongton sosanxuat vatvao vatra phucap".split(" ");global.secu_models="asskey assproduct assperiod assinvestment asssell assbuy assneedtobuy asswithdraw asscashwithdraw wallet assfindhash assbank asstransaction assissue token tokens user app listinfo right otp payload smsaccount emailaccount".split(" ");global.webPush=require("web-push");global.mongoose=require("mongoose");
global.mongoose.plugin(mongooseSecurityPlugin);require("./libs/mongoosePatch.js");global.mongoose.plugin(leanID);global.mongoose.plugin(deletePost);global.mongoose.plugin(globalListinfoCodePlugin);global.mongoose.plugin(function($schema$$){$schema$$.set("versionKey",!1)});global.Schema=global.mongoose.Schema;
global.getModel=$model_name_name$$=>{$model_name_name$$=$model_name_name$$.split(".js")[0];var $_requireFields_manualMap_model_model_path_mySchema$$={kbmpttct:"kbmPttct",kbmtkgtgt:"kbmTkgtgt",token:"tokens",bn1:"pc1",bc1:"pt1"};$_requireFields_manualMap_model_model_path_mySchema$$[$model_name_name$$]&&($model_name_name$$=$_requireFields_manualMap_model_model_path_mySchema$$[$model_name_name$$]);if($_requireFields_manualMap_model_model_path_mySchema$$=mongoose.models[$model_name_name$$])return $_requireFields_manualMap_model_model_path_mySchema$$;
if(((global.configs||{}).paths||{}).models&&($_requireFields_manualMap_model_model_path_mySchema$$=((global.configs||{}).paths||{}).models+"/"+$model_name_name$$+".js",fs.existsSync($_requireFields_manualMap_model_model_path_mySchema$$)))return require($_requireFields_manualMap_model_model_path_mySchema$$);$_requireFields_manualMap_model_model_path_mySchema$$=__dirname+"/models/"+$model_name_name$$+".js";if(fs.existsSync($_requireFields_manualMap_model_model_path_mySchema$$))return require($_requireFields_manualMap_model_model_path_mySchema$$);
console.error("model",$model_name_name$$,"is not exists. create new model");$_requireFields_manualMap_model_model_path_mySchema$$={...require("./models/listinfo").requireFields};$_requireFields_manualMap_model_model_path_mySchema$$=new global.Schema($_requireFields_manualMap_model_model_path_mySchema$$,{strict:!1});return global.mongoose.model($model_name_name$$,$_requireFields_manualMap_model_model_path_mySchema$$)};global.getLib=$lib_name$$=>require("./libs/"+$lib_name$$);
const pointSchema=new global.mongoose.Schema({type:{type:String,enum:["Point"],required:!0,default:"Point"},coordinates:{type:[Number],required:!0}}),polygonSchema=new global.mongoose.Schema({type:{type:String,enum:["Polygon"],required:!0,default:"Polygon"},coordinates:{type:[[[Number]]],required:!0}});global.customTypes={Point:pointSchema,Polygon:polygonSchema};const EventEmitter=require("events");class GlobalEmitter extends EventEmitter{}global.globalEvents=new GlobalEmitter;
global.getSysConfig=async $cf_code$$=>{if($cf_code$$=await global.getModel("sysconfig").findOne({code:$cf_code$$}))return $cf_code$$.value};global.asyncCountUnRead=async $email$$=>{const $Message$$=global.getModel("message");return new Promise($resolve$$=>{setImmediate(()=>{$Message$$.countDocuments({email:$email$$,read:!1},($e$$,$rs$$)=>{$resolve$$($rs$$||0)})})})};
global.alertMessage=function($email$$,$id_app$$){onAfterCommit(()=>{const $Message$$=global.getModel("message"),$User$$=global.getModel("user");let $query$$={email_owner:$email$$,read:!1};$id_app$$&&($query$$["exfields.id_app"]=$id_app$$);$Message$$.countDocuments($query$$,function($error$$,$count$$){$error$$?console.log($error$$):$User$$.emitEvent($email$$,"message:count",$count$$,!1)})})};
global.createNotification=function($email_sender$$,$email_receiver$$,$title$$,$content$$,$fn$$,$exfields$$,$emitEvent$$,$c_token$$,$send_email$$){global.getModel("notification").createNotification($email_sender$$,$email_receiver$$,$title$$,$content$$,$fn$$,$exfields$$,$emitEvent$$,$c_token$$,$send_email$$)};
global.getNotifies=function($email$$,$fn$$,$id_app$$){if(!$id_app$$)return $fn$$(null,{notifications:[],colls:[],apps:[]});const $Notification$$=global.getModel("notification");async.parallel({colls:function($callback$$){$callback$$(null,[])},notifications:function($callback$$){let $query$$={email_owner:$email$$,read:!1};$id_app$$&&($query$$["exfields.id_app"]=$id_app$$);$Notification$$.find($query$$,function($error$$,$colls_raw$$){setImmediate(()=>{if($error$$)$callback$$($error$$);else{const $colls$$=
$colls_raw$$.map(function($c$$){return $c$$.toObject()});$callback$$(null,$colls$$)}})})},apps:function($callback$$){$callback$$(null,[])}},function($error$$,$rs$$){setImmediate(()=>{$fn$$($error$$,$rs$$)})})};
global.sendNotification=function($email$$,$_id$$,$notify$$,$push_to_mobile_and_web$$=!0){const $User$$=global.getModel("user");setImmediate(()=>{$notify$$||={email_sender:"H\u1ec7 th\u1ed1ng"};const $obj_notify$$={_id:$_id$$,code:"notification",action:"view"};$obj_notify$$.body=$notify$$.content||$notify$$.title||"";$obj_notify$$.sender=$notify$$.email_sender;$obj_notify$$.title=$notify$$.title||"";$obj_notify$$.content=$notify$$.content||"";$User$$.emitEvent($email$$,"notify:new",$obj_notify$$,$push_to_mobile_and_web$$)})};
global.alertNotification=function($email$$,$id_app$$){const $Notification$$=global.getModel("notification"),$User$$=global.getModel("user");setImmediate(()=>{let $condition$$={email_owner:$email$$,read:!1};$id_app$$&&($condition$$["exfields.id_app"]=$id_app$$);$Notification$$.countDocuments($condition$$,function($error$$,$count$$){$error$$?Logger.error("[alertNotification]",$error$$):(Logger.warn("[global][alertNotification]",{email:$email$$,id_app:$id_app$$,count:$count$$}),$User$$.emitEvent($email$$,
"notify:count",$count$$,!1))})})};global.asyncCountNotifications=async function($email$$,$id_app$$){const $Notification$$=global.getModel("notification");return new Promise($resolve$$=>{setImmediate(()=>{let $condition$$={email_owner:$email$$,read:!1};$id_app$$&&($condition$$["exfields.id_app"]=$id_app$$);$Notification$$.countDocuments($condition$$,function($error$$,$count$$){setImmediate(()=>{$error$$?(Logger.error("[global][countNotification]",$error$$),$resolve$$(0)):$resolve$$($count$$)})})})})};
const {RateLimiterRedis,RateLimiterQueue,RateLimiterMemory}=require("rate-limiter-flexible"),{onAfterCommit}=require("./libs/sessionContext.js");
global.createRateLimiterMiddleware=async($config$$,$keyPrefix$$)=>{const $total_points$$=$config$$.points||1E3;var $duration_limiterFlexible$$=$config$$.duration||1;const $insuranceLimiter$$=new RateLimiterMemory({points:$total_points$$,duration:$duration_limiterFlexible$$});$duration_limiterFlexible$$=new RateLimiterRedis({keyPrefix:$keyPrefix$$,storeClient:global.clientRedis,points:$total_points$$,duration:$duration_limiterFlexible$$,blockDuration:$config$$.blockDuration||0,inmemoryBlockOnConsumed:$total_points$$+
1,inmemoryBlockDuration:10,insuranceLimiter:$insuranceLimiter$$});const $rateLimiter$$=new RateLimiterQueue($duration_limiterFlexible$$,{maxQueueSize:$config$$.maxQueueSize||1E4});return async($req$$,$res$$,$next$$)=>{let $key$$=($req$$.ip||$req$$.headers["x-forwarded-for"]||$req$$.connection.remoteAddress).replace("::ffff:","");const $origin$$=($req$$.headers.origin||$req$$.headers.referer||"").toString().toLowerCase().replace("https://","").replace("http://","").replace("www.","").split("/").join("").trim();
let $trust_domains$$=((global.configs||{}).trust_domains||"").toString().toLowerCase().split(","),$points$$;if($origin$$&&$trust_domains$$.indexOf($origin$$)<0){var $check_query$$={domain:$origin$$};if($check_query$$=await global.getModel("domain").findOne($check_query$$).lean()){if($check_query$$.not_allow)return $res$$.status(400).send({error:"Access is not allowed"});$points$$=$check_query$$.points;$trust_domains$$.push($origin$$)}}$check_query$$=$req$$.headers["x-trust-key"]||$req$$.query.trustkey||
$req$$.query.trust_key||"";const $trust_keys$$=(global.configs||{}).trust_keys||[];$req$$.user&&($key$$=`${$key$$}-${$req$$.user.email}`);$key$$=`${$key$$}-${$origin$$||"unknow"}-${$check_query$$||"untrustkey"}`;$points$$||(!$origin$$||$trust_domains$$.length==0&&$trust_keys$$.length==0||$origin$$&&$trust_domains$$.length>0&&$trust_domains$$.indexOf($origin$$)>=0||$trust_keys$$.length>0&&$trust_keys$$.indexOf($check_query$$)>=0?$points$$=1:($points$$=Math.roundBy($total_points$$/2),Logger.warn("This request is limit rate at",
$points$$,"/",$total_points$$,{origin:$origin$$,originalUrl:$req$$.originalUrl,trust_keys:$trust_keys$$,trust_Key:$check_query$$,key:$key$$})));setImmediate(async()=>{try{await $rateLimiter$$.removeTokens($points$$,$key$$),$next$$()}catch($err$$){console.error("Error rate limiter",$keyPrefix$$,$err$$),$err$$ instanceof Error?$res$$.status(400).send({error:$err$$.message||"Error rate limiter"}):$res$$.status(429).send({error:"Too Many Requests. Please try again later"})}})}};