Commit 069a460d authored by 方雄韬's avatar 方雄韬

Initial commit

parents
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
#Mac
.DS_Store
server/.DS_Store
server/static/dist
web/.DS_Store
web/dist
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# nyc test coverage
.nyc_output
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
server/node_modules/
web/node_modules/
server/upload_store/
# Typescript v1 declaration files
typings/
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
.eslintrc.json
# vscode configuration
jsconfig.json
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
This diff is collapsed.
{
"name": "duiba-minipgm",
"version": "1.0.0",
"description": "wechat minigrogram duiba credits mall demo",
"main": "app.js",
"scripts": {
"start": "node ./server/app.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"duiba",
"wechat",
"miniprogram",
"credits",
"malll",
"demo"
],
"author": "tonyfxt",
"license": "ISC",
"dependencies": {
"koa": "^2.4.1",
"koa-bodyparser": "^4.2.0",
"koa-router": "^7.4.0",
"mime": "^2.2.0",
"mz": "^2.7.0",
"nunjucks": "^3.0.1"
}
}
const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
// 导入controller middleware:
const controller = require('./utils/controller');
const templating = require('./utils/templating');
const isProduction = process.env.NODE_ENV === 'production';
const app = new Koa();
// log request URL:
app.use(async(ctx, next) => {
console.log(`Process ${ctx.request.method} ${ctx.request.url}...`);
var
start = new Date().getTime(),
execTime;
await next();
execTime = new Date().getTime() - start;
ctx.response.set('X-Response-Time', `${execTime}ms`);
});
// 使用middleware:
if (!isProduction) {
let staticFiles = require('./utils/static-files');
app.use(staticFiles('/static/', __dirname + '/static'));
}
//解析body
app.use(bodyParser());
//使用模板
app.use(templating('views', {
noCache: !isProduction,
watch: !isProduction
}));
//控制器
app.use(controller());
app.listen(3000);
console.log('app started at port 3000...');
\ No newline at end of file
const md5 = require('../utils/signTools/md5');
const prefix = 'http://home.m.duiba.com.cn/autoLogin/autologin?';
const appKey = '4EjQPjaceMUWMdSsAqPukuiN7LmD';
const appSecret = '2kF4RsKiCfHF9cN3ccqLWWyo2K7q';
// const testurl = 'http://localhost:3000/duiba/inner4me?uid=fxt&credits=1000&dbredirect=http%3a%2f%2ftrade.m.duiba.com.cn%2fcrecord%2frecord';
let autoLogin = async(ctx, next) => {
let uid = ctx.request.query['uid'] || 'duiba';
let credits = ctx.request.query['credits'] || '100';
let redirect = ctx.request.query['dbredirect'];
let timestamp = new Date().getTime();
let params = new Map();
params.set('uid', uid);
params.set('credits', credits);
params.set('appKey', appKey);
params.set('timestamp', timestamp);
if (!!redirect) {
params.set('redirect', redirect);
}
params.set('appSecret', appSecret);
let sign = md5.sign(params);
let autoLoginUrl = '';
if (!!redirect) {
autoLoginUrl = prefix + 'uid=' + uid + '&credits=' + credits + '&appKey=' + appKey + '&timestamp=' + timestamp + '&sign=' + sign +'&redirect='+ encodeURIComponent(redirect);
} else {
autoLoginUrl = prefix + 'uid=' + uid + '&credits=' + credits + '&appKey=' + appKey + '&timestamp=' + timestamp + '&sign=' + sign;
}
ctx.redirect(autoLoginUrl);
}
module.exports = {
'GET /duiba/autoLogin': autoLogin
};
/**
* 自动扫描加载路由
*/
const fs = require('fs');
// process.cwd() 是当前执行node命令时候的文件夹地址
// __dirname 是被执行的js 文件的地址
const cwd = process.cwd();
function addMapping(router, mapping) {
for (var url in mapping) {
if (url.startsWith('GET ')) {
var path = url.substring(4);
router.get(path, mapping[url]);
console.log(`register URL mapping: GET ${path}`);
} else if (url.startsWith('POST ')) {
var path = url.substring(5);
router.post(path, mapping[url]);
console.log(`register URL mapping: POST ${path}`);
} else {
console.log(`invalid URL: ${url}`);
}
}
}
function addControllers(router) {
var files = fs.readdirSync(cwd + '/server/controllers');
var js_files = files.filter((f) => {
return f.endsWith('.js');
});
for (var f of js_files) {
console.log(`process controller: ${f}...`);
let mapping = require(cwd + '/server/controllers/' + f);
addMapping(router, mapping);
}
}
module.exports = function (dir) {
let
controllers_dir = dir || 'controllers', // 如果不传参数,扫描目录默认为'controllers'
router = require('koa-router')();
addControllers(router, controllers_dir);
return router.routes();
};
\ No newline at end of file
var Encryption = require('./utils/encryption');
var e = new Encryption();
var key = "Ziy66Kf";
var text = "2dvVjNPS7KNFRfjRZXrTvvvsUak7nJDwgh4QhaA";
var encrypted = e.encrypt(text, key);
console.log("Encrypted text: "+encrypted);
var decrypted = e.decrypt(encrypted, key);
console.log("Decrypted text: "+decrypted);
\ No newline at end of file
var crypto = require('crypto');
var algorithm = "bf-ecb";
function pad(text) {
pad_bytes = 8 - (text.length % 8)
for (var x=1; x<=pad_bytes;x++)
text = text + String.fromCharCode(0)
return text;
}
function Encryption() {
self = this;
self.encrypt = function(data, key) {
var cipher = crypto.createCipheriv(algorithm, new Buffer(key), '');
cipher.setAutoPadding(false);
try {
return new Buffer(cipher.update(pad(data), 'utf8', 'binary') + cipher.final('binary'), 'binary').toString('base64');
} catch (e) {
return null;
}
}
self.decrypt = function(data, key) {
var decipher = crypto.createDecipheriv(algorithm, new Buffer(key), '');
decipher.setAutoPadding(false);
try {
return (decipher.update(new Buffer(data, 'base64').toString('binary'), 'binary', 'utf8')+ decipher.final('utf8')).replace(/\x00+$/g, '');
} catch (e) {
return null;
}
}
}
module.exports = Encryption;
\ No newline at end of file
const crypto = require('crypto');
let sign = (params) => {
const hash = crypto.createHash('md5');
let array = [];
let signStr = '';
for (let param of params) {
array.push(param);
}
let sortParams = new Map(array.sort());
for (let value of sortParams.values()) {
signStr += value;
}
hash.update(signStr);
return hash.digest('hex');
}
module.exports = {
sign: sign
}
const path = require('path');
const mime = require('mime');
const fs = require('mz/fs');
// url: 类似 '/static/'
// dir: 类似 __dirname + '/static'
function staticFiles(url, dir) {
return async (ctx, next) => {
let rpath = ctx.request.path;
// 判断是否以指定的url开头:
if (rpath.startsWith(url)) {
// 获取文件完整路径:
let fp = path.join(dir, rpath.substring(url.length));
// 判断文件是否存在:
if (await fs.exists(fp)) {
// 查找文件的mime:
ctx.response.type = mime.lookup(rpath);
// 读取文件内容并赋值给response.body:
ctx.response.body = await fs.readFile(fp);
} else {
// 文件不存在:
ctx.response.status = 404;
}
} else {
// 不是指定前缀的URL,继续处理下一个middleware:
await next();
}
};
}
module.exports = staticFiles;
\ No newline at end of file
const nunjucks = require('nunjucks');
function createEnv(path, opts) {
var
autoescape = opts.autoescape === undefined ? true : opts.autoescape,
noCache = opts.noCache || false,
watch = opts.watch || false,
throwOnUndefined = opts.throwOnUndefined || false,
env = new nunjucks.Environment(
new nunjucks.FileSystemLoader(path, {
noCache: noCache,
watch: watch,
}), {
autoescape: autoescape,
throwOnUndefined: throwOnUndefined
});
if (opts.filters) {
for (var f in opts.filters) {
env.addFilter(f, opts.filters[f]);
}
}
return env;
}
function templating(path, opts) {
var env = createEnv(path, opts);
return async (ctx, next) => {
ctx.render = function (view, model) {
ctx.response.body = env.render(view, Object.assign({}, ctx.state || {}, model || {}));
ctx.response.type = 'text/html';
};
await next();
};
}
module.exports = templating;
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment