UNPKG

2.3 kBJavaScriptView Raw
1const express = require('express');
2const bodyParser = require('body-parser');
3const http = require('http');
4const url = require('url');
5const auth = require('./auth');
6const logger = require('./logger');
7
8const app = express();
9app.use(bodyParser.json());
10//authentication middleware.
11app.use(function (req, res, next) {
12 var pathName = url.parse(req.url).pathname;
13 logger.info('application', `url:${req.url},pathname:${pathName}`);
14 if (pathName === '/api/login' || pathName === '/api/register') {
15 next();
16 } else {
17 if (!req.headers['authorization']) {
18 res.send({ status: 1, code: 400, msg: '认证失败,您未获取访问此api的授权' });
19 return;
20 };
21 let token = req.headers['authorization'].split(' ').pop();
22 let obj = auth.decrypt(token);
23 logger.warning('application', `token:${token},obj:${obj}`);
24 if (!obj) {
25 res.send({ status: 1, code: 400, msg: '认证失败,您未获取访问此api的授权' });
26 return;
27 };
28 next();
29 }
30});
31//error middleware.
32app.use(function (err, req, res, next) {
33 if (err) {
34 logger.err("application", `get ${req.url} failed`);
35 res.send({ status: 1, code: 500, msg: "服务器异常,请联系管理员" });
36 return;
37 };
38 next();
39});
40//default login.
41app.post('/api/login', function (req, res) {
42 logger.warning('application', JSON.stringify(req.body));
43 let token = auth.encrypt(req.body);
44 res.send({ status: 0, code: 200, msg: 'token获取成功', data: token });
45});
46//default register.
47app.post('/api/register', function (req, res) {
48
49});
50
51
52const server = http.createServer(app);
53const application = {};
54
55/**
56 * Starts server.
57 * @param host
58 * @param port
59 */
60application.start = function (host, port) {
61
62 server.listen(port, host, function () {
63 logger.info("application", ["Server started,please visit http://", host, ":", port].join(''));
64 });
65};
66
67/**
68 * get request.
69 */
70application.get = function (path, callback) {
71 app.get(path, callback);
72}
73
74/**
75 * post request.
76 */
77application.post = function (path, callback) {
78 app.post(path, callback);
79}
80module.exports = application;
\No newline at end of file