root 3 years ago
commit
3ea8547fbd
7 changed files with 431 additions and 0 deletions
  1. 6 0
      .gitignore
  2. 68 0
      app.js
  3. 67 0
      game.js
  4. 124 0
      login.js
  5. 77 0
      mysql.js
  6. 24 0
      package.json
  7. 65 0
      query.js

+ 6 - 0
.gitignore

@@ -0,0 +1,6 @@
+# See https://help.github.com/ignore-files/ for more about ignoring files.
+
+# dependencies
+/node_modules
+/package-lock.json
+

+ 68 - 0
app.js

@@ -0,0 +1,68 @@
+// call the packages we need
+var express = require('express');        // call express
+var app = express();                 // define our app using express
+var bodyParser = require('body-parser');
+var request = require("request");
+const edurouter = require('./query');
+const morgan = require('morgan');
+var path = require("path");
+var port = "5005";        // set our port
+//const cors = require('cors')
+app.use(morgan('dev'));
+// configure app to use bodyParser()
+// this will let us get the data from a POST
+app.use(bodyParser.urlencoded({ extended: true, limit: '3mb' }));
+app.use(bodyParser.json({ limit: '3mb' }));
+
+//暂时全跨域
+app.use(function (req, res, next) {
+    ///var allowedOrigins = [config.local.origin,'http://cocorobo.hk','http://www.cocorobo.hk','https://cocorobo.hk','http://cloud.cocorobo.hk','https://cloud.cocorobo.hk'];
+    var origin = req.headers.origin || "*";
+    //if(allowedOrigins.indexOf(origin) > -1){
+    res.setHeader('Access-Control-Allow-Origin', origin);
+    //}
+    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
+    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
+    res.header('Access-Control-Allow-Credentials', true);
+    //修改程序信息与版本
+    res.header('X-Powered-By', ' 3.2.1')
+    //内容类型:如果是post请求必须指定这个属性
+    res.header('Content-Type', 'application/json;charset=utf-8')
+    next();
+});
+
+/*
+app.use(cors({
+    origin:[`http:${config.local.origin}`,'http://www.cocorobo.hk','https://cocorobo.hk','http://cloud.cocorobo.hk','https://cloud.cocorobo.hk'],
+    methods:['GET','POST','PUT','DELETE'],
+    credentials: true // enable set cookie
+}));
+*/
+// all of our routes will be prefixed with /api
+app.use('/query', edurouter);
+// app.use('/game', game);
+
+app.all('/download', function (req, res, next) {
+    //req.body.url = "https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/%E4%B8%8B%E8%BD%BD%20%284%29.doc";
+    request({
+        url: req.body.url,
+        method: "GET",
+        encoding: null,
+        headers: {
+            'Accept-Encoding': 'gzip, deflate'
+        }
+    },
+        function (error, response, body) {
+            if (!error && response.statusCode == 200) {
+                res.setHeader('Content-Type', 'application/force-download');
+                res.setHeader('Content-Disposition', 'attachment; filename=' + path.basename(req.body.url));
+                res.setHeader('Content-Length', body.length);
+                res.send(body);
+            }
+        });
+});
+
+// START THE SERVER
+// =============================================================================
+app.listen(port);
+console.log('app happens on port ' + port);

+ 67 - 0
game.js

@@ -0,0 +1,67 @@
+// ROUTES FOR OUR API
+// =============================================================================
+var express = require('express');
+ var bcrypt = require('bcryptjs');
+var router = express.Router();              // get an instance of the express Router
+const querystring = require('querystring');
+var mysql = require('./mysql');
+// const _mysqlLabor = ["123.58.32.151", "cocoroboK12"]; //edu數據庫信息
+const _mysqlLabor = ["172.16.12.5", "cocoroboK12"]; //edu數據庫信息
+
+//統壹處理區域
+router.use(async function (req, res, next) {
+    await asynnext(req, res, next);
+    //// make sure we go to the next routes and don't stop here
+    //res.end("");
+});
+
+/**
+ * @des 參數解釋同上
+ */
+function asynnext(req, res, next) {
+    //異步處理
+    return new Promise(async (resolve, reject) => {
+        next();
+        //resolve(true);aa
+    });
+}
+/*測試*/ 
+router.route('/a').all((req, res, next) => {
+    var json = queryString(req.url);
+    getmysql(req, res, "a", json['ph'], json['pa']);
+});
+router.route('/b').all((req, res, next) => {
+    var json = queryString(req.url);
+    getmysql(req, res, "b", json['ph'], json['pa']);
+});
+
+
+
+queryString = function (url) {
+    var a = url.split("?");
+    var json = querystring.parse(a[1])
+    return json;
+}
+
+//post存儲過程處理
+postmysql = function (req, res, functionname) {
+    //mode的處理
+    if (req.body[0]) {
+        p = Object.values(req.body[0]);
+        p.unshift(_mysqlLabor[0], _mysqlLabor[1], functionname);
+        //執行存儲過程
+        mysql.usselect(p, function (ret) { res.end(JSON.stringify(ret)); });
+    }
+}
+
+//get獲取數據庫信息
+getmysql = function (req, res, functionname, ...p) {
+    p = p || [];
+    p.unshift(_mysqlLabor[0], _mysqlLabor[1], functionname);
+    //執行存儲過程
+    mysql.usselect(p, function (ret) { res.end(JSON.stringify(ret)); });  //
+}
+
+
+module.exports = router;
+

+ 124 - 0
login.js

@@ -0,0 +1,124 @@
+// ROUTES FOR OUR API
+// =============================================================================
+var express = require('express');
+var router = express.Router();              // get an instance of the express Router
+var bcrypt = require('bcryptjs');
+const querystring = require('querystring');
+
+var mysql = require('./mysql');
+const _mysqluser = ["127.0.0.1", "cocorobouser"]; //用户数据库信息
+var _api_key = '27fe2452da5fdcae2ced5ee1bbb3c5f9-b892f62e-09baaac5';
+var _DOMAIN = 'mail.cocorobo.hk';
+var _mailgun = require('mailgun-js')({ apiKey: _api_key, domain: _DOMAIN });
+
+//统一处理区域
+router.use(function (req, res, next) {
+  next(); // make sure we go to the next routes and don't stop here
+});
+
+//创建edu课程
+router.route('/register').post(function (req, res, next) {
+  //mode的处理
+  if (req.body.mode) {
+    // 0 用户名 1 用户密码 2用户身份 3 第三方id(可有可无)
+    p = req.body.mode.split(","); //获取用户密码
+    //没有第三方id的处理
+    if (p.length < 4) {
+      p.push("")
+    }
+    p[1] = bcrypt.hashSync(p[1], bcrypt.genSaltSync(10));
+    //密码加密
+    // bcrypt.hash(p[1], 10, function (err, hash) {
+    //   if (err) {
+    //     return next(err);
+    //   }
+    //   p[1] = hash;
+    // });
+    //参数拼接,注册
+    p.unshift(_mysqledu[0], _mysqledu[1], "add_register");
+    //返回注册用户数据
+    mysql.usselect(p, function (ret) {
+      res.end(ret);
+    });
+  }
+});
+
+//创建edu课程
+router.route('/login').post(function (req, res, next) {
+  //mode的处理
+  if (req.body.mode) {
+    // 0 用户名 1 用户密码
+    p = req.body.mode.split(","); //获取用户密码
+
+    p[1] = bcrypt.hashSync(p[1], bcrypt.genSaltSync(10));
+    //密码加密
+    // bcrypt.hash(p[1], 10, function (err, hash) {
+    //     if (err) {
+    //         return next(err);
+    //     }
+    //     p[1] = hash;
+    // });
+    //参数拼接,注册
+    p.unshift(_mysqledu[0], _mysqledu[1], "select_login");
+    //执行存储过程
+    mysql.usselect(p, function (ret) {
+
+      //res.end(ret.toString()); 
+    });
+  }
+});
+
+
+//注册信息激活处理
+function sendRegisterEmail(email, activeKey) {
+  let htmlForm = `
+    <html>
+      <h4>感謝註冊, 請點擊以下連結完成註冊。</h4>
+      <br>
+      <a href='${config.local.server}/activate/${email}/${activeKey}'>
+        <button>點擊進行激活</button>
+      </a>
+      <p>Best regards,</p>
+      <p>Tony Xin</p>
+      <p>CEO</p>
+      <p>CocoRobo Limited</p>
+    </html>`;
+
+  var emailData = {
+    from: 'activation@cocorobo.cc',
+    to: email,
+    subject: '註冊帳號激活',
+    html: htmlForm,
+  };
+
+  //发送激活邮箱
+  mailgun.messages().send(emailData, function (error, body) {
+    if (error) {
+      console.log(error)
+    } else {
+      console.log(body);
+    }
+  });
+}
+
+
+//post存储过程处理
+postmysql = function (req, res, functionname) {
+  //mode的处理
+  if (req.body.mode) {
+    p = req.body.mode.split(",");
+    p.unshift(_mysqledu[0], _mysqledu[1], functionname);
+    //执行存储过程
+    mysql.usselect(p, function (ret) { res.end(JSON.stringify(ret)); });
+  }
+}
+
+//get获取数据库信息
+getmysql = function (req, res, functionname, ...p) {
+  p = p || [];
+  p.unshift(_mysqledu[0], _mysqledu[1], functionname);
+  //执行存储过程
+  mysql.usselect(p, function (ret) { res.end(JSON.stringify(ret)); });  //
+}
+
+module.exports = router;

+ 77 - 0
mysql.js

@@ -0,0 +1,77 @@
+//参数
+var us = {
+    mysql: require('mysql'),
+    sqle: {}
+};
+
+//连接数据库
+us.mysqlconnection = function (host, database) {
+    if (!us.sqle[host] || !us.sqle[host][database]) { //配置数据库连接 
+        us.sqle[host] = us.sqle[host] || {};
+        us.sqle[host][database] = us.mysql.createPool({
+            connectionLimit: 0,
+            host: host, //数据库地址
+            user: "root", //用户名
+            password: "cocorobo", //密码
+            database: database, //数据库名称
+            port: 3306 //端口
+        }); //连接超时和错误从连
+    }
+    return us.sqle[host][database]; //返回连接对象
+}
+
+
+//连接数据库调用
+exports.usselect = function (param, callback) {
+    if (param.length > 1) {
+        var _mysqlconnection = us.mysqlconnection(param[0], param[1]); //创建连接池
+        _mysqlconnection.getConnection(function (error, connection) { //获取连接
+            if (error) { //连接错误
+                console.log("连接失败:", error);
+            } else { //连接成功
+                for (i = 0; i < param.length; i++) {
+                    param[i] = decodeURIComponent(param[i]);
+                    
+                } //格式化处理参数
+                var i, _sql = "CALL ";
+                var _param = new Array();
+                if (param.length > 3) { //带有参数的sql语句  如:'call test(?, ?, ?);'
+                    _param = param.slice(3) //截取有效参数
+                    _sql += (param[2] || "") + "(?"; //拼接存储过程名称 
+                    //_s += (p[2] || "") + "('" + p.slice(3).join("','") + "');";
+                    //, + ? 拼接参数 该方法拼接后比数组长度少一因此上一句代码中默认拼接了第一个参数
+                    _sql += Array(_param.length).join(",?");
+                    _sql += ");"; //拼接结果语句
+                } else { //不带参数的sql语句 如:'call test();'
+                    _sql += param[2] + "();";
+                }
+                console.log("拼凑的MySQl语句为:", _sql);
+                connection.query(_sql, _param, function (error, results, fields) { //执行sql语句 
+                    if (results) {
+                        callback(results.affectedRows != null ? results.affectedRows : results.length > 1 ? results : results[0]);
+                    } 
+                    else { //执行错误
+                        console.log("sql执行失败", error || "");
+                        callback(error);
+                    }
+                });
+                
+                connection.release(function (error) { //释放资源
+                    if (error) console.log("连接释放错误", error);
+                });
+                
+            }
+        });
+    }
+}
+
+
+//重新连接处理
+// us.mysqlconnet.reconnection = function (host, database, error) {
+//     if (error) {
+//         console.log("连接失败,尝试重连", error);
+//         setTimeout(function () {
+//             us.mysqlconnection(host, database)
+//         }, 2000);
+//     }
+// }

+ 24 - 0
package.json

@@ -0,0 +1,24 @@
+{
+  "name": "CocoRoboQuery",
+  "version": "1.0.0",
+  "description": "",
+  "main": "app.js",
+  "scripts": {
+    "test": "echo \"Error: no test specified\" && exit 1"
+  },
+  "repository": {
+    "type": "git",
+    "url": "https://git.cocorobo.hk/jack/CocoRoboQuery.git"
+  },
+  "keywords": [],
+  "author": "",
+  "license": "ISC",
+  "dependencies": {
+    "body-parser": "^1.19.0",
+    "express": "^4.17.1",
+    "morgan": "^1.10.0",
+    "mysql": "^2.18.1",
+    "path": "^0.12.7",
+    "request": "^2.88.2"
+  }
+}

+ 65 - 0
query.js

@@ -0,0 +1,65 @@
+// ROUTES FOR OUR API
+// =============================================================================
+var express = require('express');
+var bcrypt = require('bcryptjs');
+var router = express.Router();              // get an instance of the express Router
+const querystring = require('querystring');
+var mysql = require('./mysql');
+const { json } = require('express');
+// const _mysqlLabor = ["123.58.32.151", "LaborEdu"]; //edu數據庫信息
+const _mysqlLabor = ["172.16.12.5", "LaborEdu"]; //edu數據庫信息 
+
+
+//統壹處理區域
+router.use(async function (req, res, next) {
+    await asynnext(req, res, next);
+    //// make sure we go to the next routes and don't stop here
+    //res.end("");
+});
+
+/**
+ * @des 參數解釋同上
+ */
+function asynnext(req, res, next) {
+    //異步處理
+    return new Promise(async (resolve, reject) => {
+        next();
+        //resolve(true);
+    });
+}
+
+//
+router.route('/query').all((req, res, next) => {
+    postmysql(req, res, "");
+});
+
+queryString = function (url) {
+    var a = url.split("?");
+    var json = querystring.parse(a[1])
+    return json;
+}
+
+//post存儲過程處理
+postmysql = function (req, res, functionname) {
+    //mode的處理
+    if (req.body[0]) {
+        p = Object.values(req.body[0]);
+        p.unshift(_mysqlLabor[0], _mysqlLabor[1], functionname);
+        //執行存儲過程
+        mysql.usselect(p, function (ret) { res.end(JSON.stringify(ret)); });
+    }
+}
+
+//get獲取數據庫信息
+getmysql = function (req, res, functionname, ...p) {
+    p = p || [];
+    p.unshift(_mysqlLabor[0], _mysqlLabor[1], functionname);
+    //執行存儲過程
+    mysql.usselect(p, function (ret) {
+        res.end(JSON.stringify(ret));
+    });  //
+}
+
+
+module.exports = router;
+