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
+26 -26
View File
@@ -1,48 +1,48 @@
var crypto = require('crypto');
var crypto = require('crypto')
/**
*
* @param {number} len
*
* @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')
}
/**
*
* @param {string} str
*
* @param {string} str
*/
var sha256 = (str) => {
return crypto.createHash("sha256").update(str).digest('base64');
return crypto.createHash('sha256').update(str).digest('base64')
}
/**
*
* @param {string} 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}`
}
/**
*
* @param {string} plain
* @param {string} hash
*
* @param {string} plain
* @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 = {
random,
sha256,
genPassHash,
comparePass
}
random,
sha256,
genPassHash,
comparePass
}
+35 -35
View File
@@ -1,48 +1,48 @@
const Memcached = require('memcached');
const Memcached = require('memcached')
class memcachedLib {
constructor() {
this._host = ''
this._port = ''
this._expire = 86400
this._conn = null;
}
class MemcachedLib {
constructor () {
this._host = ''
this._port = ''
this._expire = 86400
this._conn = null
}
connect() {
this._conn = new Memcached(`${this._host}:${this._port}`)
}
connect () {
this._conn = new Memcached(`${this._host}:${this._port}`)
}
/**
* set object to memcached
* @param {string} key
* @param {string} val
* @param {number} expire
* @param {string} key
* @param {string} val
* @param {number} 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);
})
})
}
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)
})
})
}
/**
* get object from memcached
* @param {string} key
* @param {string} key
*/
async getVal(key) {
return new Promise((resolve, reject) => {
this._conn.get(key, (err, data) => {
if (err) return reject(err);
return resolve(data);
})
})
}
async getVal (key) {
return new Promise((resolve, reject) => {
this._conn.get(key, (err, 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()
+25 -25
View File
@@ -1,40 +1,40 @@
const mongoose = require('mongoose');
const mongoose = require('mongoose')
const tokenSchema = mongoose.Schema({
object: Object,
expire: {
type: Number,
default: Date.now
}
});
object: Object,
expire: {
type: Number,
default: Date.now
}
})
tokenSchema.statics.clearExpire = function (cb) {
console.log(Date.now())
return this.remove({ expire: { $lte: Date.now() } }, cb);
console.log(Date.now())
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;
return new Promise((resolve, reject) => {
self.findOne({ _id: str, expire: { $gte: Date.now() } }, (err, row) => {
if (err || !row) return resolve(false);
return resolve(true);
});
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)
})
})
}
tokenSchema.statics.getToken = async function (str) {
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);
})
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)
})
})
}
const token = mongoose.model('token', tokenSchema, 'token');
const Token = mongoose.model('token', tokenSchema, 'token')
module.exports = {
token
}
Token
}
+79 -80
View File
@@ -1,89 +1,88 @@
const mysql = require('mysql');
const mysql = require('mysql')
class MySQLPool {
constructor() {
this._user = '';
this._password = '';
this._host = '';
this._port = 3306;
this._database = '';
this._socketPath = ''
this._pool = null;
this.autoclose = false;
this._useSocket = false;
constructor () {
this._user = ''
this._password = ''
this._host = ''
this._port = 3306
this._database = ''
this._socketPath = ''
this._pool = null
this.autoclose = false
this._useSocket = false
}
createPool () {
let json = {
connectionLimit: 30,
user: this._user,
password: this._password,
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)
}
async getConn () {
return new Promise((resolve, reject) => {
this._pool.getConnection((err, conn) => {
if (err) return reject(err)
return resolve(conn)
})
})
}
formatQuery (query, arg) {
return mysql.format(query, arg)
}
escape (val) {
return mysql.escape(val)
}
recordPage (rows, page, maxPage) {
if (!page || !isFinite(page) || page < 1) page = 1
let totalPage = Math.ceil(rows / maxPage)
let prevPage = page - 1
let nextPage = page + 1
if (prevPage < 1) prevPage = 1
if (nextPage > totalPage) nextPage = totalPage
let recStart = (page - 1) * maxPage + 1
let recEnd = (recStart + maxPage - 1)
if (recEnd > rows) recEnd = rows
let json = {
recStart,
recEnd,
total: rows,
prevPage,
nextPage,
totalPage,
page
}
createPool() {
let json = {
connectionLimit: 30,
user: this._user,
password: this._password,
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);
}
return json
}
async getConn() {
return new Promise((resolve, reject) => {
this._pool.getConnection((err, conn) => {
if (err) return reject(err);
return resolve(conn)
})
})
}
formatQuery(query, arg) {
return mysql.format(query, arg);
}
escape(val) {
return mysql.escape(val);
}
recordPage(rows, page, maxPage) {
if (!page || !isFinite(page) || page < 1) page = 1;
let totalpage = Math.ceil(rows / maxPage);
let prevpage = page - 1;
let nextpage = page + 1;
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 json = {
rec_start,
rec_end,
total: rows,
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; }
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 = {
// user: 'root',
@@ -116,4 +115,4 @@ class MySQLPool {
// return pool
// })()
module.exports = new MySQLPool();
module.exports = new MySQLPool()
+28 -28
View File
@@ -1,35 +1,35 @@
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({
host: config.smtp.host,
port: config.smtp.port,
secure: config.smtp.secure, // secure:true for port 465, secure:false for port 587
auth: {
user: config.smtp.user,
pass: config.smtp.pass
}
});
let transporter = nodemailer.createTransport({
host: config.smtp.host,
port: config.smtp.port,
secure: config.smtp.secure, // secure:true for port 465, secure:false for port 587
auth: {
user: config.smtp.user,
pass: config.smtp.pass
}
})
// setup email data with unicode symbols
let mailOptions = {
from: config.smtp.sys_mail, // sender address
to: toMail, // list of receivers
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
};
let mailOptions = {
from: config.smtp.sys_mail, // sender address
to: toMail, // list of receivers
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) => {
return new Promise((resolve, reject) => {
// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return reject(error);
}
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return reject(error)
}
// console.log('Mepassage %s sent: %s', info.messageId, info.response);
return resolve(info);
});
});
}
return resolve(info)
})
})
}
+62 -56
View File
@@ -1,68 +1,74 @@
const StoreObj = (() => {
let memStore = {}
let maxAge = 86400000
let memStore = {};
let maxAge = 86400000;
/**
* @param {string} uuid
* @param {object} obj
*/
const set = (uuid, obj) => {
memStore[uuid] = {
obj,
age: Date.now() + maxAge
}
/**
* @param {string} uuid
* @param {object} obj
*/
const set = (uuid, obj) => {
memStore[uuid] = {
obj,
age: Date.now() + maxAge
}
}
/**
* @param {string} uuid
*/
const get = (uuid) => {
if (uuid in memStore) {
let s = memStore[uuid];
if (Date.now() < s.age) {
s.age = Date.now() + maxAge;
return s.obj;
} else {
delete memStore[uuid];
}
}
return null;
/**
* @param {string} uuid
*/
const get = (uuid) => {
if (uuid in memStore) {
let s = memStore[uuid]
if (Date.now() < s.age) {
s.age = Date.now() + maxAge
return s.obj
} else {
delete memStore[uuid]
}
}
return null
}
/**
* @param {string} uuid
*/
const chkKey = (uuid) => {
if (uuid in memStore) return true;
return false;
/**
* @param {string} uuid
*/
const chkKey = (uuid) => {
if (uuid in memStore) return true
return false
}
/**
* @param {string} uuid
*/
const del = (uuid) => {
if (uuid in memStore) delete memStore[uuid]
}
const clear = () => {
let t = Date.now()
for (var i in memStore) {
let s = memStore[i]
if (s.age < t) delete memStore[i]
}
}
/**
* @param {string} uuid
*/
const del = (uuid) => {
if (uuid in memStore) delete memStore[uuid];
}
/**
* @param {string} uuid if not input return all
*/
const show = (uuid) => {
if (uuid && uuid in memStore) return memStore[uuid]
const clear = () => {
let t = Date.now();
for (var i in memStore) {
let s = memStore[i];
if (s.age < t) delete memStore[i];
}
}
return memStore
}
/**
* @param {string} uuid if not input return all
*/
const show = (uuid) => {
if (uuid && uuid in memStore) return memStore[uuid];
return memStore;
}
return {set, get, chkKey, clear, del, show };
return {
set,
get,
chkKey,
clear,
del,
show
}
})()
module.exports = StoreObj;
module.exports = StoreObj