1 | const express = require('express');
|
2 | const bodyParser = require('body-parser');
|
3 | const http = require('http');
|
4 | const url = require('url');
|
5 | const auth = require('./auth');
|
6 | const logger = require('./logger');
|
7 |
|
8 | const app = express();
|
9 | app.use(bodyParser.json());
|
10 |
|
11 | app.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 |
|
32 | app.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 |
|
41 | app.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 |
|
47 | app.post('/api/register', function (req, res) {
|
48 |
|
49 | });
|
50 |
|
51 |
|
52 | const server = http.createServer(app);
|
53 | const application = {};
|
54 |
|
55 |
|
56 |
|
57 |
|
58 |
|
59 |
|
60 | application.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 |
|
69 |
|
70 | application.get = function (path, callback) {
|
71 | app.get(path, callback);
|
72 | }
|
73 |
|
74 |
|
75 |
|
76 |
|
77 | application.post = function (path, callback) {
|
78 | app.post(path, callback);
|
79 | }
|
80 | module.exports = application; |
\ | No newline at end of file |