add javascript standard check

This commit is contained in:
Jay 2017-06-06 20:40:51 +08:00
parent 298bf45585
commit b390643a70
13 changed files with 1674 additions and 597 deletions

View File

@ -1,57 +1,56 @@
const koa = require('koa');
const path = require('path');
const fs = require('fs');
const mongoose = require('mongoose');
const Koa = require('koa')
const path = require('path')
const mongoose = require('mongoose')
// Load config
const config = require('./config.json');
const config = require('./config.json')
// custom modules
const mysql = require('./libs/mysql_pool');
const so = require('./libs/storeObject');
const mem = require('./libs/memcache_lib');
const sendmail = require('./libs/sendmail');
const mysql = require('./libs/mysql_pool')
// const so = require('./libs/storeObject')
const mem = require('./libs/memcache_lib')
// const sendmail = require('./libs/sendmail')
// init memcached connection
mem.host = 'dyn.trj.tw';
mem.port = 24002;
mem.connect();
mem.host = 'dyn.trj.tw'
mem.port = 24002
mem.connect()
// init mysql connection pool
mysql.database = config.db.mysql.dbname;
mysql.host = config.db.mysql.host;
mysql.user = config.db.mysql.user;
mysql.password = config.db.mysql.pass;
mysql.port = config.db.mysql.port;
mysql.createPool();
mysql.database = config.db.mysql.dbname
mysql.host = config.db.mysql.host
mysql.user = config.db.mysql.user
mysql.password = config.db.mysql.pass
mysql.port = config.db.mysql.port
mysql.createPool()
// init mongodb connection
let mongoAuth = `${config.db.mongo.user.length > 0 && config.db.mongo.pass.length > 0 ? `${config.db.mongo.user}:${config.db.mongo.pass}@` : ''}`;
let mongoUrl = `mongodb://${mongoAuth}${config.db.mongo.host}:${config.db.mongo.port}/${config.db.mongo.dbname}${mongoAuth.length > 0 ? '?authSource=admin': ''}`;
mongoose.connect(mongoUrl);
let mongoAuth = `${config.db.mongo.user.length > 0 && config.db.mongo.pass.length > 0 ? `${config.db.mongo.user}:${config.db.mongo.pass}@` : ''}`
let mongoUrl = `mongodb://${mongoAuth}${config.db.mongo.host}:${config.db.mongo.port}/${config.db.mongo.dbname}${mongoAuth.length > 0 ? '?authSource=admin' : ''}`
mongoose.connect(mongoUrl)
// Koa Middleware
const session = require('koa-session');
const Router = require('koa-router');
const koaBody = require('koa-body');
const koaStatic = require('koa-static');
const cors = require('kcors');
const logger = require('koa-morgan');
const session = require('koa-session')
const Router = require('koa-router')
// const koaBody = require('koa-body')
const koaStatic = require('koa-static')
const cors = require('kcors')
const logger = require('koa-morgan')
// Koa Main Application
const app = new koa();
const app = new Koa()
const server = app.listen(config.port, () => {
console.log(`Server start on port ${server.address().port}`);
});
console.log(`Server start on port ${server.address().port}`)
})
// Root Router
const router = new Router();
const router = new Router()
// set app keys
app.keys = ['44b4fa5cb8a394294361'];
app.keys = ['44b4fa5cb8a394294361']
// enable logger
app.use(logger('dev'));
app.use(logger('dev'))
// enable body parser
// app.use(koaBody({
// multipart: true,
@ -59,7 +58,7 @@ app.use(logger('dev'));
// maxFieldSize: 10 * 1024 * 1024
// }));
// enable cors
app.use(cors());
app.use(cors())
// enable session
app.use(session({
key: 'koa:sess',
@ -67,19 +66,19 @@ app.use(session({
overwrite: true,
httpOnly: true,
signed: true
}, app));
}, app))
// enable static file
app.use(koaStatic(path.resolve(__dirname, 'public')));
app.use(koaStatic(path.resolve(__dirname, 'public')))
// enable router
app.use(router.routes());
app.use(router.allowedMethods());
app.use(router.routes())
app.use(router.allowedMethods())
// load other route
const api_route = require('./route/api');
const apiRoute = require('./route/api')
// set other route
router.use("/api", api_route.routes());
router.use('/api', apiRoute.routes())
router.get('/', async(c, n) => {
c.body = 'Get root';
});
c.body = 'Get root'
})

View File

@ -1,12 +1,12 @@
var crypto = require('crypto');
var crypto = require('crypto')
/**
*
* @param {number} len
*/
var random = (len = 32) => {
var buf = crypto.randomBytes(len);
return buf.toString("hex");
var buf = crypto.randomBytes(len)
return buf.toString('hex')
}
/**
@ -14,7 +14,7 @@ var random = (len = 32) => {
* @param {string} str
*/
var sha256 = (str) => {
return crypto.createHash("sha256").update(str).digest('base64');
return crypto.createHash('sha256').update(str).digest('base64')
}
/**
@ -22,9 +22,9 @@ var sha256 = (str) => {
* @param {string} str
*/
var genPassHash = (str) => {
var hash = random(16);
var pass = sha256(str + hash);
return `$${hash}$${pass}`;
var hash = random(16)
var pass = sha256(str + hash)
return `$${hash}$${pass}`
}
/**
@ -33,11 +33,11 @@ var genPassHash = (str) => {
* @param {string} hash
*/
var comparePass = (plain, hash) => {
var match = hash.match(/^\$(.+?)\$(.+)$/);
if (match == null || match.length < 3 || !match[1] || !match[2]) return false;
var pass = sha256(plain + match[1]);
if (pass == match[2]) return true;
return false;
var match = hash.match(/^\$(.+?)\$(.+)$/)
if (match == null || match.length < 3 || !match[1] || !match[2]) return false
var pass = sha256(plain + match[1])
if (pass === match[2]) return true
return false
}
module.exports = {

View File

@ -1,14 +1,14 @@
const Memcached = require('memcached');
const Memcached = require('memcached')
class memcachedLib {
constructor() {
class MemcachedLib {
constructor () {
this._host = ''
this._port = ''
this._expire = 86400
this._conn = null;
this._conn = null
}
connect() {
connect () {
this._conn = new Memcached(`${this._host}:${this._port}`)
}
@ -18,11 +18,11 @@ class memcachedLib {
* @param {string} val
* @param {number} expire
*/
async setVal(key, val, expire = this._expire) {
async setVal (key, val, expire = this._expire) {
return new Promise((resolve, reject) => {
this._conn.set(key, val, expire, err => {
if (err) return reject(err);
return resolve(null);
if (err) return reject(err)
return resolve(null)
})
})
}
@ -31,18 +31,18 @@ class memcachedLib {
* get object from memcached
* @param {string} key
*/
async getVal(key) {
async getVal (key) {
return new Promise((resolve, reject) => {
this._conn.get(key, (err, data) => {
if (err) return reject(err);
return resolve(data);
if (err) return reject(err)
return resolve(data)
})
})
}
set host(str) { this._host = str }
set port(str) { this._port = str }
set expire(str) { this._expire = str }
set host (str) { this._host = str }
set port (str) { this._port = str }
set expire (str) { this._expire = str }
}
module.exports = new memcachedLib();
module.exports = new MemcachedLib()

View File

@ -1,4 +1,4 @@
const mongoose = require('mongoose');
const mongoose = require('mongoose')
const tokenSchema = mongoose.Schema({
object: Object,
@ -6,35 +6,35 @@ const tokenSchema = mongoose.Schema({
type: Number,
default: Date.now
}
});
})
tokenSchema.statics.clearExpire = function (cb) {
console.log(Date.now())
return this.remove({ expire: { $lte: Date.now() } }, cb);
return this.remove({ expire: { $lte: Date.now() } }, cb)
}
tokenSchema.statics.renewToken = function (id, expire, cb) {
return this.update({ _id: mongoose.Schema.Types.ObjectId(id) }, { $set: { expire: Date.now() + 86400000 } }, cb);
return this.update({ _id: mongoose.Schema.Types.ObjectId(id) }, { $set: { expire: Date.now() + 86400000 } }, cb)
}
tokenSchema.statics.checkToken = async function (str) {
let self = this;
let self = this
return new Promise((resolve, reject) => {
self.findOne({ _id: str, expire: { $gte: Date.now() } }, (err, row) => {
if (err || !row) return resolve(false);
return resolve(true);
});
if (err || !row) return resolve(false)
return resolve(true)
})
})
}
tokenSchema.statics.getToken = async function (str) {
let self = this;
let self = this
return new Promise((resolve, reject) => {
self.findOne({ _id: str, expire: { $gte: Date.now() } }, (err, row) => {
if (err) return reject(err);
return resolve(row);
if (err) return reject(err)
return resolve(row)
})
})
}
const token = mongoose.model('token', tokenSchema, 'token');
const Token = mongoose.model('token', tokenSchema, 'token')
module.exports = {
token
Token
}

View File

@ -1,19 +1,19 @@
const mysql = require('mysql');
const mysql = require('mysql')
class MySQLPool {
constructor() {
this._user = '';
this._password = '';
this._host = '';
this._port = 3306;
this._database = '';
constructor () {
this._user = ''
this._password = ''
this._host = ''
this._port = 3306
this._database = ''
this._socketPath = ''
this._pool = null;
this.autoclose = false;
this._useSocket = false;
this._pool = null
this.autoclose = false
this._useSocket = false
}
createPool() {
createPool () {
let json = {
connectionLimit: 30,
user: this._user,
@ -21,68 +21,67 @@ class MySQLPool {
host: this._host,
port: this._port,
socketPath: this._socketPath
};
if (this._useSocket) {
delete json.host;
delete json.port;
} else {
delete json.socketPath;
}
this._pool = mysql.createPool(json);
if (this._useSocket) {
delete json.host
delete json.port
} else {
delete json.socketPath
}
this._pool = mysql.createPool(json)
}
async getConn() {
async getConn () {
return new Promise((resolve, reject) => {
this._pool.getConnection((err, conn) => {
if (err) return reject(err);
if (err) return reject(err)
return resolve(conn)
})
})
}
formatQuery(query, arg) {
return mysql.format(query, arg);
formatQuery (query, arg) {
return mysql.format(query, arg)
}
escape(val) {
return mysql.escape(val);
escape (val) {
return mysql.escape(val)
}
recordPage(rows, page, maxPage) {
if (!page || !isFinite(page) || page < 1) page = 1;
recordPage (rows, page, maxPage) {
if (!page || !isFinite(page) || page < 1) page = 1
let totalpage = Math.ceil(rows / maxPage);
let totalPage = Math.ceil(rows / maxPage)
let prevpage = page - 1;
let nextpage = page + 1;
let prevPage = page - 1
let nextPage = page + 1
if (prevpage < 1) prevpage = 1;
if (nextpage > totalpage) nextpage = totalpage;
if (prevPage < 1) prevPage = 1
if (nextPage > totalPage) nextPage = totalPage
let rec_start = (page - 1) * maxPage + 1
let rec_end = (rec_start + maxPage - 1);
if (rec_end > rows) rec_end = rows;
let recStart = (page - 1) * maxPage + 1
let recEnd = (recStart + maxPage - 1)
if (recEnd > rows) recEnd = rows
let json = {
rec_start,
rec_end,
recStart,
recEnd,
total: rows,
prevpage,
nextpage,
totalpage,
prevPage,
nextPage,
totalPage,
page
};
return json;
}
set user(str) { this._user = str; }
set host(str) { this._host = str; }
set password(str) { this._password = str; }
set port(str) { this._port = str; }
set database(str) { this._database = str; }
}
return json
}
set user (str) { this._user = str }
set host (str) { this._host = str }
set password (str) { this._password = str }
set port (str) { this._port = str }
set database (str) { this._database = str }
}
// let Pool = ((opts) => {
// let defOpts = {
@ -116,4 +115,4 @@ class MySQLPool {
// return pool
// })()
module.exports = new MySQLPool();
module.exports = new MySQLPool()

View File

@ -1,6 +1,6 @@
const nodemailer = require('nodemailer');
const config = require('../config.json');
const util = require('util');
const nodemailer = require('nodemailer')
const config = require('../config.json')
const util = require('util')
module.exports = async(toMail, template = {}, data = []) => {
let transporter = nodemailer.createTransport({
@ -11,7 +11,7 @@ module.exports = async(toMail, template = {}, data = []) => {
user: config.smtp.user,
pass: config.smtp.pass
}
});
})
// setup email data with unicode symbols
let mailOptions = {
@ -20,16 +20,16 @@ module.exports = async(toMail, template = {}, data = []) => {
subject: template.title || '', // Subject line
text: template.text ? util.format(template.text, ...data) : '', // plain text body
html: template.html ? util.format(template.html, ...data) : '' // html body
};
}
return new Promise((resolve, reject) => {
// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return reject(error);
return reject(error)
}
// console.log('Mepassage %s sent: %s', info.messageId, info.response);
return resolve(info);
});
});
return resolve(info)
})
})
}

View File

@ -1,7 +1,6 @@
const StoreObj = (() => {
let memStore = {};
let maxAge = 86400000;
let memStore = {}
let maxAge = 86400000
/**
* @param {string} uuid
@ -19,37 +18,37 @@ const StoreObj = (() => {
*/
const get = (uuid) => {
if (uuid in memStore) {
let s = memStore[uuid];
let s = memStore[uuid]
if (Date.now() < s.age) {
s.age = Date.now() + maxAge;
return s.obj;
s.age = Date.now() + maxAge
return s.obj
} else {
delete memStore[uuid];
delete memStore[uuid]
}
}
return null;
return null
}
/**
* @param {string} uuid
*/
const chkKey = (uuid) => {
if (uuid in memStore) return true;
return false;
if (uuid in memStore) return true
return false
}
/**
* @param {string} uuid
*/
const del = (uuid) => {
if (uuid in memStore) delete memStore[uuid];
if (uuid in memStore) delete memStore[uuid]
}
const clear = () => {
let t = Date.now();
let t = Date.now()
for (var i in memStore) {
let s = memStore[i];
if (s.age < t) delete memStore[i];
let s = memStore[i]
if (s.age < t) delete memStore[i]
}
}
@ -57,12 +56,19 @@ const StoreObj = (() => {
* @param {string} uuid if not input return all
*/
const show = (uuid) => {
if (uuid && uuid in memStore) return memStore[uuid];
if (uuid && uuid in memStore) return memStore[uuid]
return memStore;
return memStore
}
return {set, get, chkKey, clear, del, show };
return {
set,
get,
chkKey,
clear,
del,
show
}
})()
module.exports = StoreObj;
module.exports = StoreObj

View File

@ -4,6 +4,9 @@
"main": "app.js",
"author": "UrWind",
"license": "MIT",
"scripts": {
"check": "standard --fix --verbose"
},
"dependencies": {
"kcors": "2",
"koa": "^2.2.0",
@ -16,5 +19,8 @@
"mongoose": "^4.10.4",
"mysql": "^2.13.0",
"nodemailer": "^4.0.1"
},
"devDependencies": {
"standard": "^10.0.2"
}
}

View File

@ -1,45 +1,48 @@
const Router = require('koa-router');
const router = new Router();
/* eslint-disable no-throw-literal */
/* eslint-env es6 */
/* eslint-disable no-multi-str */
const Router = require('koa-router')
const router = new Router()
// import tools
const crypto = require('../../libs/crypto.js');
const so = require('../../libs/storeObject');
const mongo = require('../../libs/mongo_model.js');
const mem = require('../../libs/memcache_lib');
const msgMng = require('./msgManager');
const sendmail = require('../../libs/sendmail');
const crypto = require('../../libs/crypto.js')
// const so = require('../../libs/storeObject')
const mongo = require('../../libs/mongo_model.js')
const mem = require('../../libs/memcache_lib')
const msgMng = require('./msgManager')
const sendmail = require('../../libs/sendmail')
router
.post('/user', async(c, n) => {
let arr = c.request.body;
if (!arr.data) throw 'CE0000';
if (!arr.data.account) throw 'CE0001';
if (!arr.data.password) throw 'CE00002';
if (!arr.data.name) throw 'CE0004';
if (!arr.data.email) throw 'CE0005';
let arr = c.request.body
if (!arr.data) throw 'CE0000'
if (!arr.data.account) throw 'CE0001'
if (!arr.data.password) throw 'CE00002'
if (!arr.data.name) throw 'CE0004'
if (!arr.data.email) throw 'CE0005'
try {
let query = "select count(*) as c from ??.?? where `account` = ?";
let param = ['lora', 'user', arr.data.account];
let count = await c.syncQuery(query, param);
if (count.length == 0) throw 'SE0000';
if (count[0].c > 0) throw 'CE0006';
let query = 'select count(*) as c from ??.?? where `account` = ?'
let param = ['lora', 'user', arr.data.account]
let count = await c.syncQuery(query, param)
if (count.length === 0) throw 'SE0000'
if (count[0].c > 0) throw 'CE0006'
} catch (err) {
if (typeof err == 'string') throw err;
c.serr = err;
throw 'SE0000';
if (typeof err === 'string') throw err
c.serr = err
throw 'SE0000'
}
let uid = 0;
let uid = 0
try {
let query = "insert into ??.?? (`account`, `password`, `name`, `email`) values (?, ?, ?, ?)";
let param = ['lora', 'user', arr.data.account, arr.data.password, arr.data.name, arr.data.email];
let indata = await c.syncQuery(query, param);
uid = indata.insertId;
let query = 'insert into ??.?? (`account`, `password`, `name`, `email`) values (?, ?, ?, ?)'
let param = ['lora', 'user', arr.data.account, arr.data.password, arr.data.name, arr.data.email]
let indata = await c.syncQuery(query, param)
uid = indata.insertId
} catch (err) {
if (typeof err == 'string') throw err;
c.serr = err;
throw 'SE0001';
if (typeof err === 'string') throw err
c.serr = err
throw 'SE0001'
}
c.body = {
@ -47,89 +50,89 @@ router
}
})
.get('/user/:uid', async(c, n) => {
if (!await mongo.token.checkToken(c.token)) throw 'CE1000';
if (!await mongo.Token.checkToken(c.token)) throw 'CE1000'
try {
let t = await mongo.token.getToken(c.token);
if (t.object.uid != c.params.uid) throw 'CE2000';
let t = await mongo.Token.getToken(c.token)
if (t.object.uid !== c.params.uid) throw 'CE2000'
} catch (err) {
if (typeof err == 'string') throw err;
c.serr = err;
throw 'SE0000';
if (typeof err === 'string') throw err
c.serr = err
throw 'SE0000'
}
try {
let user = await c.syncQuery('select `uid`,`account`,`name`,`email` from ??.?? where `uid` = ?', ['lora', 'user', c.params.uid]);
let user = await c.syncQuery('select `uid`,`account`,`name`,`email` from ??.?? where `uid` = ?', ['lora', 'user', c.params.uid])
c.body = {
record: user
}
} catch (err) {
if (typeof err == 'string') throw err;
c.serr = err;
throw 'SE0000';
if (typeof err === 'string') throw err
c.serr = err
throw 'SE0000'
}
})
.put('/user/:uid', async(c, n) => {
if (!await mongo.token.checkToken(c.token)) throw 'CE1000';
let arr = c.request.body;
if (!arr.data) throw 'CE0000';
if (!arr.data.name) throw 'CE0004';
if (!arr.data.email) throw 'CE0005';
if (!await mongo.Token.checkToken(c.token)) throw 'CE1000'
let arr = c.request.body
if (!arr.data) throw 'CE0000'
if (!arr.data.name) throw 'CE0004'
if (!arr.data.email) throw 'CE0005'
try {
let t = await mongo.token.getToken(c.token);
if (t.object.uid != c.params.uid) throw 'CE2000';
let t = await mongo.Token.getToken(c.token)
if (t.object.uid !== c.params.uid) throw 'CE2000'
} catch (err) {
if (typeof err == 'string') throw err;
c.serr = err;
throw 'SE0000';
if (typeof err === 'string') throw err
c.serr = err
throw 'SE0000'
}
try {
let query = "update ??.?? set \
let query = 'update ??.?? set \
`name` = ?, \
`email` = ?" + (arr.data.password ? ',' : '') + " \
" + (arr.data.password ? "`password` = ?, " : '') + " \
`email` = ?' + (arr.data.password ? ',' : '') + ' \
' + (arr.data.password ? '`password` = ?, ' : '') + ' \
where \
`uid` = ?";
let param = ['lora', 'user', arr.data.name, arr.data.email];
if (arr.data.password) param.push(crypto.genPassHash(arr.data.password));
param.push(c.params.uid);
`uid` = ?'
let param = ['lora', 'user', arr.data.name, arr.data.email]
if (arr.data.password) param.push(crypto.genPassHash(arr.data.password))
param.push(c.params.uid)
let updata = await c.syncQuery(query, param);
await c.syncQuery(query, param)
} catch (err) {
if (typeof err == 'string') throw err;
c.serr = err;
throw 'SE0002';
if (typeof err === 'string') throw err
c.serr = err
throw 'SE0002'
}
c.body = { record: [] };
c.body = { record: [] }
})
.post('/login', async(c, n) => {
let arr = c.request.body;
if (!arr.data) throw 'CE0000';
if (!arr.data.account) throw 'CE0001';
if (!arr.data.password) throw 'CE0002';
let arr = c.request.body
if (!arr.data) throw 'CE0000'
if (!arr.data.account) throw 'CE0001'
if (!arr.data.password) throw 'CE0002'
try {
let user = await c.syncQuery('select `uid`,`account`,`password`,`name`,`email` from ??.?? where `account` = ?', ['lora', 'user', arr.data.account])
if (user.length == 0) throw 'CE0003';
if (user.length === 0) throw 'CE0003'
if (!crypto.comparePass(arr.data.password, user[0].password)) throw 'CE0003';
if (!crypto.comparePass(arr.data.password, user[0].password)) throw 'CE0003'
delete user[0].password;
delete user[0].password
c.body = {
record: user
}
} catch (err) {
if (typeof err == 'string') throw err;
c.serr = err;
throw 'SE0000';
if (typeof err === 'string') throw err
c.serr = err
throw 'SE0000'
}
let u = c.body.record[0];
let token = new mongo.token({ object: u, expire: Date.now() + 86400000 });
token.save();
let u = c.body.record[0]
let token = new mongo.Token({ object: u, expire: Date.now() + 86400000 })
token.save()
c.body.rt = {
token: {
id: token._id
@ -137,37 +140,37 @@ router
}
})
.post('/user/forgotpass', async(c, n) => {
let arr = c.request.body;
if (!arr.data) throw 'CE0000';
if (!arr.data.account) throw 'CE0001';
if (!arr.data.email) throw 'CE0005';
let arr = c.request.body
if (!arr.data) throw 'CE0000'
if (!arr.data.account) throw 'CE0001'
if (!arr.data.email) throw 'CE0005'
let user = [];
let user = []
try {
let query = "select * from ??.?? where `account` = ? and `email` = ?";
let param = ['lora', 'user', arr.data.account, arr.data.email];
user = await c.syncQuery(query, param);
let query = 'select * from ??.?? where `account` = ? and `email` = ?'
let param = ['lora', 'user', arr.data.account, arr.data.email]
user = await c.syncQuery(query, param)
} catch (err) {
if (typeof err == 'string') throw err;
c.serr = err;
throw 'SE0001';
if (typeof err === 'string') throw err
c.serr = err
throw 'SE0001'
}
if (user.length == 0) throw 'CE0007';
if (user.length === 0) throw 'CE0007'
let randomToken = crypto.random(10);
let randomToken = crypto.random(10)
try {
await mem.setVal(randomToken, JSON.stringify(user[0]), 7200);
await mem.setVal(randomToken, JSON.stringify(user[0]), 7200)
} catch (err) {
c.serr = err;
throw 'SE0005';
c.serr = err
throw 'SE0005'
}
try {
await sendmail(user[0].email, msgMng.getMailTemplate('forgotpass', c.headers['accept-language']), [randomToken])
} catch (err) {
if (typeof err == 'string') throw err;
c.serr = err;
throw 'SE0006';
if (typeof err === 'string') throw err
c.serr = err
throw 'SE0006'
}
c.body = {
@ -175,20 +178,16 @@ router
}
})
.post('/user/resetpass', async(c, n) => {
let arr = c.request.body;
if (!arr.data) throw 'CE0000';
if (!arr.data.account) throw 'CE0001';
if (arr.data.resettype != 'pass' && arr.data.resettype != 'token') throw 'CE0008';
if (arr.data.resettype == 'pass') {
if (!arr.data.password) throw 'CE0002';
let arr = c.request.body
if (!arr.data) throw 'CE0000'
if (!arr.data.account) throw 'CE0001'
if (arr.data.resettype !== 'pass' && arr.data.resettype !== 'token') throw 'CE0008'
if (arr.data.resettype === 'pass') {
if (!arr.data.password) throw 'CE0002'
} else {
if (!arr.data.token) throw 'CE0009';
if (!arr.data.token) throw 'CE0009'
}
if (!arr.data.newpass) throw 'CE0002';
if (!arr.data.newpass) throw 'CE0002'
})
module.exports = router;
module.exports = router

View File

@ -1,73 +1,72 @@
const Router = require('koa-router');
const router = new Router();
const koaBody = require('koa-body');
const Router = require('koa-router')
const router = new Router()
const koaBody = require('koa-body')
// import tools
const mysql = require('../../libs/mysql_pool.js');
const so = require('../../libs/storeObject');
const config = require('../../config.json');
const msgMng = require('./msgManager');
const mysql = require('../../libs/mysql_pool.js')
// const so = require('../../libs/storeObject')
// const config = require('../../config.json')
const msgMng = require('./msgManager')
// routes
const account_api = require('./account.js');
const accountApi = require('./account.js')
// api response handler
router.use(async(c, n) => {
// get MySQL connection
c.db = await mysql.getConn();
c.db = await mysql.getConn()
// set Async/Await Query
c.syncQuery = (query, param = null) => {
return new Promise((resolve, reject) => {
if (param != null) {
c.db.query(query, param, (err, row) => {
if (err) return reject(err);
if (err) return reject(err)
return resolve(row)
});
})
} else {
c.db.query(query, (err, row) => {
if (err) return reject(err);
if (err) return reject(err)
return resolve(row)
});
})
}
})
}
c.token = c.headers['x-auth-token'] || '';
c.token = c.headers['x-auth-token'] || ''
// console.log(c.headers['accept-language'])
try {
await n();
await n()
c.body = {
data: c.body,
status: 1
}
} catch (e) {
let msg = msgMng.getMsg(e, c.headers['accept-language']);
let msg = msgMng.getMsg(e, c.headers['accept-language'])
c.body = {
errorCode: e,
message: msg,
servErr: c.serr ? c.serr.toString() : '',
status: 0
}
if (e[0] == 'C' || e[0] == 'c') c.status = 400;
if (e[0] == 'S' || e[0] == 's') c.status = 500;
if (e[0] === 'C' || e[0] === 'c') c.status = 400
if (e[0] === 'S' || e[0] === 's') c.status = 500
}
if ('db' in c && typeof c.db == 'object' && 'release' in c.db && typeof c.db.release == 'function') c.db.release();
if ('db' in c && typeof c.db === 'object' && 'release' in c.db && typeof c.db.release === 'function') c.db.release()
})
// enable bodyParser
router.all('*', koaBody({
multipart: true,
// upload file size 10mb
maxFieldSize: 10 * 1024 * 1024
}), async(c, n) => { await n(); })
}), async(c, n) => { await n() })
router
.get('/', async(c, n) => {
c.body = {
msg: 'API Endpoint'
};
}
})
.use('/account', account_api.routes())
.use('/account', accountApi.routes())
module.exports = router;
module.exports = router

View File

@ -1,46 +1,46 @@
const fs = require('fs');
const path = require('path');
// const fs = require('fs')
// const path = require('path')
class msgManager {
constructor() {
this.errs = {};
this.defLang = 'zh';
let err = require(`./language/zh`);
this.errs['zh'] = err;
class MsgManager {
constructor () {
this.errs = {}
this.defLang = 'zh'
let err = require(`./language/zh`)
this.errs['zh'] = err
}
checkLang(lang = '') {
let lng = this.defLang;
if (typeof lang == 'string' && lang.trim().length > 0) {
let l = lang.split(',');
checkLang (lang = '') {
let lng = this.defLang
if (typeof lang === 'string' && lang.trim().length > 0) {
let l = lang.split(',')
if (l.length > 0) {
let tmp = l[0].substring(0, 2);
if (tmp.trim().length > 0) lng = tmp;
let tmp = l[0].substring(0, 2)
if (tmp.trim().length > 0) lng = tmp
}
}
if (!(lng in this.errs)) {
try {
let errs = require(`./language/${lng}`);
this.errs[lng] = errs;
let errs = require(`./language/${lng}`)
this.errs[lng] = errs
} catch (err) {
lng = this.defLang;
lng = this.defLang
}
}
return lng;
return lng
}
getMsg(code, lang = '') {
let lng = this.checkLang(lang);
getMsg (code, lang = '') {
let lng = this.checkLang(lang)
return this.errs[lng][code] || 'errorCode not found';
return this.errs[lng][code] || 'errorCode not found'
}
getMailTemplate(type, lang = '') {
let lng = this.checkLang(lang);
getMailTemplate (type, lang = '') {
let lng = this.checkLang(lang)
return this.errs[lng]['mail'][type] || {};
return this.errs[lng]['mail'][type] || {}
}
}
module.exports = new msgManager();
module.exports = new MsgManager()

File diff suppressed because it is too large Load Diff