Jelajahi Sumber

航班查询相关

kindring 3 tahun lalu
induk
melakukan
9b160f72a5
17 mengubah file dengan 339 tambahan dan 64 penghapusan
  1. 9 21
      app.js
  2. 2 2
      configs/server.json
  3. 8 2
      controller/account.js
  4. 11 0
      controller/flight.js
  5. 16 0
      database/d_air.js
  6. 1 1
      db.md
  7. 61 0
      logger.js
  8. 5 3
      maps/field.js
  9. 12 0
      maps/progress.js
  10. 17 6
      middleware/checkLogin.js
  11. 1 16
      middleware/paramsCheck.js
  12. 5 5
      package.json
  13. 68 5
      routes/admin.js
  14. 36 0
      routes/admin_api.js
  15. 27 0
      routes/captcha.js
  16. 59 2
      routes/citys.js
  17. 1 1
      routes/indexApi.js

+ 9 - 21
app.js

@@ -1,7 +1,5 @@
-const createError = require('http-errors');
 const express = require('express');
 const path = require('path');
-const cookieParser = require('cookie-parser');
 const session = require('express-session');
 const ejs = require('ejs');
 const bodyParser = require('body-parser');
@@ -9,7 +7,9 @@ const bodyParser = require('body-parser');
 
 const indexRouter = require('./routes/index');
 const usersRouter = require('./routes/users');
-
+const citysRouter = require('./routes/citys');
+const adminRouter = require('./routes/admin');
+const captcha = require('./routes/captcha');
 const app = express();
 
 const serverConfig = require('./configs/server.json');
@@ -28,7 +28,7 @@ app.use(
       secret: 'air',
       name: 'session', //这里的name值得是cookie的name,默认cookie的name是:connect.sid
       cookie: { maxAge: 1800000 }, //过期时间半小时
-      keys: ['owner', 'captcha'], // 用户登陆信息,验证码字段
+      keys: ['owner','admin', 'captcha'], // 用户登陆信息,验证码字段
       resave: true,
       saveUninitialized: true,
     })
@@ -40,26 +40,14 @@ app.use(bodyParser.json({ limit: '10mb' }));
 
 app.use('/', indexRouter);
 app.use('/users', usersRouter);
+app.use('/admin', adminRouter);
+app.use('/api/citys/',citysRouter);
+app.use('/api/captcha', captcha);
 
 
-// catch 404 and forward to error handler
-app.use(function(req, res, next) {
-  next(createError(404));
-});
-
-
-// error handler
-app.use(function(err, req, res, next) {
-  // set locals, only providing error in development
-  res.locals.message = err.message;
-  res.locals.error = req.app.get('env') === 'development' ? err : {};
-
-  // render the error page
-  res.status(err.status || 500);
-  res.render('error');
-});
 
 app.listen(serverConfig.port, serverConfig.host, ()=>{
-  log.warn(`服务启动 server is running to @http://${serverConfig.host}:${serverConfig.port}`);
+  console.warn(`服务启动 server is running to @http://${serverConfig.host}:${serverConfig.port}`);
 })
+
 module.exports = app;

+ 2 - 2
configs/server.json

@@ -1,4 +1,4 @@
 {
     "host": "127.0.0.1",
-    "port": "8181"
-}
+    "port": 8181
+}

+ 8 - 2
controller/account.js

@@ -62,7 +62,7 @@ async function changePhone(type,account,passwd,newPhone){
     // 修改手机号
     [err,result] = await handle(db_user.changePhone(id,newPhone));
     if(err)throw err;
-    return;
+    return result;
 }
 
 /**
@@ -82,7 +82,13 @@ async function register(type,account,passwd,nickName){
     [err,result] = await handle(db_user.register(type,nickName,account,passwd));
     if(err)throw err;
     // 注册成功
-    return;
+    return result;
 }
 
+module.exports = {
+    register,
+    changePhone,
+    changePasswd,
+    login,
+}
 

+ 11 - 0
controller/flight.js

@@ -20,6 +20,17 @@ async function searchFlight(departureCity,targetCity,routeType,startUnixTime,end
     return result;
 }
 
+/**
+ * 航班列表
+ * @param routeType 航班类型
+ * @returns {Promise<*>}
+ */
+async function flightList(routeType){
+    let [err,result] = await handle(db_air.flightList(routeType));
+    if(err){throw err}
+    return result;
+}
+
 
 
 async function addFlight(departureCity,targetCity,routeType,startUnixTime,endUnixTime){

+ 16 - 0
database/d_air.js

@@ -43,6 +43,21 @@ function flightSearch(departureCity,targetCity,routeType,startUnixTime,endUnixTi
 }
 
 
+/**
+ * 显示所有航班列表
+ * @param routeType
+ * @returns {Promise | Promise<unknown>}
+ */
+function flightList(routeType){
+    let sql=``,values=[];
+    sql=`select * from flight`;
+    if(routeType){
+        sql += ` where routeType = ?`
+        values.push(routeType);
+    }
+    return mysql.pq(sql,values);
+}
+
 /**
  * 获取航班票数
  * @param flightId
@@ -200,4 +215,5 @@ module.exports = {
     flightSearch,
     addFlight,
     updateFlight,
+    flightList
 }

+ 1 - 1
db.md

@@ -18,7 +18,7 @@
 | account | varchar |     | 账号    |
 | phone | varchar |     | 手机号,绑定后等同账号 |
 | passwd | varchar |     | 密码    |
-| accountType | char | 2   | 账户类型  |
+| accountType | char | 1用户,2管理员   | 账户类型1,2  |
 | accountState | char | 1   | 账号状态,封禁 |
 | createTime | date | now | 创建时间  |
 

+ 61 - 0
logger.js

@@ -0,0 +1,61 @@
+/*
+ * @Description: 日志工具函数
+ * @Autor: kindring
+ * @Date: 2021-12-14 14:07:17
+ * @LastEditors: kindring
+ * @LastEditTime: 2021-12-14 14:46:16
+ * @LastDescript: 
+ */
+const Path = require('path');
+
+const log4js = require('log4js');
+
+levels = {
+    'trace': log4js.levels.TRACE,
+    'debug': log4js.levels.DEBUG,
+    'info': log4js.levels.INFO,
+    'warn': log4js.levels.WARN,
+    'error': log4js.levels.ERROR,
+    'fatal': log4js.levels.FATAL,
+}
+
+const logFileName = 'info.log';
+
+const _path = Path.resolve(__dirname, `log/${logFileName}`)
+console.log(_path);
+log4js.configure({
+    // 输出到控制台的内容,同时也输出到日志文件中
+    replaceConsole: true,
+    appenders: {
+        cheese: {
+            // 设置类型为 dateFile
+            type: 'dateFile',
+            // 配置文件名
+            filename: _path,
+            // 指定编码格式为 utf-8
+            encoding: 'utf-8',
+            // 配置 layout,此处使用自定义模式 pattern
+            // layout: 'basic',
+            // 日志文件按日期(天)切割
+            pattern: "yyyy-MM-dd",
+            // 回滚旧的日志文件时,保证以 .log 结尾 (只有在 alwaysIncludePattern 为 false 生效)
+            keepFileExt: true,
+            // 输出的日志文件名是都始终包含 pattern 日期结尾
+            alwaysIncludePattern: true,
+        },
+        console: {
+            type: 'console'
+        }
+    },
+    categories: {
+        // 设置默认的 categories
+        default: { appenders: ['cheese', 'console'], level: 'debug' },
+    }
+})
+
+exports.logger = (name, level) => {
+    const logger = log4js.getLogger(name)
+        // 默认为debug权限及以上
+    logger.level = levels[level] || levels['debug']
+    return logger
+}

+ 5 - 3
maps/field.js

@@ -1,7 +1,8 @@
 module.exports = {
-    superAdmin:1,
-    userType:2,
-    adminType:3,
+    // 普通用户状态
+    userType:1,
+    // 管理员账户
+    adminType:2,
     // 用户表正常状态
     userNomalState: 1,
     // 用户表封禁状态
@@ -16,4 +17,5 @@ module.exports = {
     cityType_domestic:1,
     // 国际城市
     cityType_international:2,
+
 }

+ 12 - 0
maps/progress.js

@@ -0,0 +1,12 @@
+module.exports = {
+    // 普通用户session字段
+    userSessionField:'user',
+    // 管理员账户session字段
+    adminSessionField:'admin',
+    // 验证码session字段
+    captchaSessionField: 'captcha',
+    // 后台登陆地址
+    adminLoginUrl: '/admin/login',
+    // 用户登陆地址
+    userLoginUrl: '/login',
+}

+ 17 - 6
middleware/checkLogin.js

@@ -7,22 +7,33 @@
  * @LastDescript: 
  */
 const codeMap = require('../maps/rcodeMap');
+const progress = require('../maps/progress');
 /**
  * 检查是否登录
+ * @param accountType 账户类型
  * @param {'json'|'view'} type 返回的数据类型
- * @returns 
+ * @returns
  */
-function checkLogin(type = 'json') {
+function checkLogin(accountType,type = 'json') {
     return function(req, res, next) {
-        console.log('检查是否有登陆');
-        if (!req.session.owner) {
+        let field,redirectPath = progress.userLoginUrl;
+        switch (accountType) {
+            case 2:
+                field = progress.adminSessionField;
+                redirectPath = progress.adminLoginUrl;
+                break;
+            case 1:
+            default:
+                field = progress.userSessionField;
+        }
+        if (!req.session[field]) {
             // 类型
             let resAction;
             switch (type) {
                 case 'view':
                     resAction = {
                         action: 'redirect',
-                        params: [302, '/login']
+                        params: [302, redirectPath]
                     }
                     break;
                 case 'json':
@@ -43,4 +54,4 @@ function checkLogin(type = 'json') {
 }
 
 
-module.exports = checkLogin;
+module.exports = checkLogin;

+ 1 - 16
middleware/paramsCheck.js

@@ -14,21 +14,6 @@ const rcodeMap = require('../maps/rcodeMap');
 // 错误代码
 const failedRcode = rcodeMap.notParam;
 
-// 是否为必须 required
-// let optionsTemplate = {
-//     body: {
-//         owner: {
-//             required: true,
-//             default: 'admin'
-//         }, //检查条件
-//         passwd: {
-//             required: true
-//         },
-//     },
-//     get: {
-
-//     }
-// }
 
 function paramsCheck(ruleParams) {
     // 确定该接口需要检查什么参数
@@ -110,4 +95,4 @@ function checkUrlParams(type = 'get', rules, params) {
     return { pass: true };
 }
 
-module.exports = paramsCheck;
+module.exports = paramsCheck;

+ 5 - 5
package.json

@@ -3,15 +3,15 @@
   "version": "0.0.0",
   "private": true,
   "scripts": {
-    "start": "node ./bin/www"
+    "start": "node app.js"
   },
   "dependencies": {
-    "cookie-parser": "~1.4.4",
-    "debug": "~2.6.9",
     "ejs": "~2.6.1",
     "express": "~4.16.1",
     "express-session": "^1.17.2",
-    "http-errors": "~1.6.3",
-    "morgan": "~1.9.1"
+    "body-parser": "^1.19.1",
+    "mysql2": "^2.3.3",
+    "log4js": "^6.3.0",
+    "svg-captcha": "^1.4.0"
   }
 }

+ 68 - 5
routes/admin.js

@@ -1,9 +1,72 @@
-var express = require('express');
-var router = express.Router();
-
-/* GET users listing. */
-router.get('/', function(req, res, next) {
+const router = require('express').Router();
+const api_admin_router = require('./admin_api');
+const checkLogin = require('../middleware/checkLogin');
+const field = require('../maps/field')
+const c_user = require("../controller/account");
+const code = require("../maps/rcodeMap");
+const progress = require("../maps/progress");
+const paramsCheck = require("../middleware/paramsCheck");
+// 管理员主页
+router.get('/',
+    checkLogin(field.adminType,'view'),
+    function(req, res, next) {
     res.send('respond with a resource');
 });
 
+// 管理员登陆页
+router.get('/login',
+    function(req, res, next) {
+        res.send('respond with a resource');
+    });
+
+// 登陆接口
+router.post('/login',
+    paramsCheck({
+        post:{
+            account:{required:true},
+            passwd:{required:true}
+        }}),
+    async (req,res)=>{
+        try{
+            let results = await c_user.login(field.adminType,req.body.account,req.body.passwd);
+            req.session[progress.adminSessionField] = results;
+            res.json({
+                rcode: code.ok,
+                data: results
+            })
+        }catch (error) {
+            if (error.rcode !== code.customError) {
+                console.log(error);
+                console.log.error(`login error ${error.message||error.msg}`);
+            }
+            res.json({
+                rcode: error.rcode || code.serverError,
+                msg: error.msg || error.message
+            });
+        }
+})
+
+// 退出登陆
+router.post('/logout',
+    async (req,res)=>{
+        try{
+            req.session[progress.adminSessionField] = null;
+            res.json({
+                rcode: code.ok,
+            })
+        }catch (error) {
+            if (error.rcode !== code.customError) {
+                console.log(error);
+                console.log.error(`logout error ${error.message||error.msg}`);
+            }
+            res.json({
+                rcode: error.rcode || code.serverError,
+                msg: error.msg || error.message
+            });
+        }
+    });
+
+// 后台相关接口
+router.use('/api',checkLogin(field.adminType),api_admin_router)
+
 module.exports = router;

+ 36 - 0
routes/admin_api.js

@@ -0,0 +1,36 @@
+const router = require('express').Router();
+const field = require('../maps/field')
+// const c_user = require("../controller/account");
+const code = require("../maps/rcodeMap");
+const progress = require("../maps/progress");
+const c_user = require("../controller/account");
+const c_flight = require("../controller/flight");
+const paramsCheck = require("../middleware/paramsCheck");
+// 获取航班列表数据
+router.get('/flights',
+    paramsCheck({
+        get:{
+            departure:{required:true},
+            target:{required:true}
+        }}),
+    async (req,res)=>{
+    try{
+        let results = await c_flight.searchFlight(field.adminType,req.body.account,req.body.passwd);
+        req.session[progress.adminSessionField] = results;
+        res.json({
+            rcode: code.ok,
+            data: results
+        })
+    }catch (error) {
+        if (error.rcode !== code.customError) {
+            console.log(error);
+            console.log.error(`login error ${error.message||error.msg}`);
+        }
+        res.json({
+            rcode: error.rcode || code.serverError,
+            msg: error.msg || error.message
+        });
+    }
+})
+
+module.exports = router;

+ 27 - 0
routes/captcha.js

@@ -0,0 +1,27 @@
+/*
+ * @Description: 验证码相关函数
+ * @Autor: kindring
+ * @Date: 2022-01-17 17:52:23
+ * @LastEditors: kindring
+ * @LastEditTime: 2022-01-26 17:36:02
+ * @LastDescript: 
+ */
+const router = require('express').Router();
+const svgCaptcha = require('svg-captcha');
+const progress = require("../maps/progress");
+// 获取新的验证码.图片,忽略大小写
+router.get('/', async(req, res) => {
+    let captcha = svgCaptcha.create({
+        noise: 7, //生成干扰线的条数 默认值为1
+        size: 4, // 验证码长度
+        ignoreChars: '0oi', // 验证码字符中排除 0oi
+        color: true, // 验证码的字符是否有颜色,默认没有,如果设定了背景,则默认有
+        // background: '#cc9966', // 验证码图片背景颜色
+    });
+    req.session[progress.captchaSessionField] = captcha.text.toLowerCase();
+    console.log(req.session[progress.captchaSessionField]);
+    res.type('svg');
+    res.status(200).send(captcha.data);
+});
+
+module.exports = router;

+ 59 - 2
routes/citys.js

@@ -1,10 +1,13 @@
 const router = require('express').Router();
 const c_area = require('../controller/c_area')
+const paramsCheck = require('../middleware/paramsCheck');
+const checkLogin = require('../middleware/checkLogin');
 const code = require('../maps/rcodeMap')
-router.get('/api/citys',async (req,res)=>{
+const field = require('../maps/field')
+
+router.get('/list',async (req,res)=>{
     try{
         let results = await c_area.searchCity(req.query.cityType);
-        // console.log(province);
         res.json({
             rcode: code.ok,
             data: results
@@ -21,4 +24,58 @@ router.get('/api/citys',async (req,res)=>{
     }
 })
 
+// 新增地区
+router.post('/add',
+    checkLogin(field.adminType),
+    paramsCheck({
+        post:{
+            cityType:{required:true},
+            cityName:{required:true}
+        }
+    }),
+    async (req,res)=>{
+    try{
+        let results = await c_area.addCity(req.body.cityType,req.body.cityName);
+        res.json({
+            rcode: code.ok,
+            data: results
+        })
+    }catch (error) {
+        if (error.rcode !== code.customError) {
+            console.log(error);
+            console.log.error(`get area map error ${error.message||error.msg}`);
+        }
+        res.json({
+            rcode: error.rcode || code.serverError,
+            msg: error.msg || error.message
+        });
+    }
+})
+
+// 修改地区
+router.post('/change',
+    checkLogin(field.adminType),
+    paramsCheck({
+        body:{
+            cityType:{required:true},
+            cityName:{required:true}
+        }}),async (req,res)=>{
+        try{
+            let results = await c_area.addCity(req.body.cityType,req.body.cityName);
+            res.json({
+                rcode: code.ok,
+                data: results
+            })
+        }catch (error) {
+            if (error.rcode !== code.customError) {
+                console.log(error);
+                console.log.error(`get area map error ${error.message||error.msg}`);
+            }
+            res.json({
+                rcode: error.rcode || code.serverError,
+                msg: error.msg || error.message
+            });
+        }
+    })
+
 module.exports = router;

+ 1 - 1
routes/indexApi.js

@@ -1,4 +1,4 @@
 const router = require('express').Router();
 
 
-module.exports = router;
+module.exports = router;