-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhttp.js
112 lines (93 loc) · 2.22 KB
/
http.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
const express = require("express");
const expressWs = require("express-ws");
const {EventEmitter} = require("events");
module.exports.NixHTTPApp = class NixHTTPApp {
constructor() {
this.requests = 0;
}
isAuthorized(authorization) {
if (!authorization) {
return false;
}
return true;
}
async handlePost(req, res) {
this.requests++;
return {
data: {}
}
}
async handleGet(req, res) {
this.requests++;
res.end();
}
status() {
return "Unknown";
}
}
module.exports.NixHTTPServer = class NixHTTPServer extends EventEmitter {
constructor(port, nix) {
super();
this.requests = {
handled: 0,
gotten: 0,
auth_failure: 0
}
this.app = express();
expressWs(this.app);
this.apps = Object.create(null);
this.app.use(express.json());
this.app.use(express.urlencoded({
extended: true
}));
this.app.post('/app/:appid/:auth', this.appValidator.bind(this), this.authorizationHandler.bind(this), this.postHandler.bind(this));
this.app.get('/app/:appid', this.appValidator.bind(this), this.getHandler.bind(this));
this.app.get("/mapconfig.json", (req, res) => {
res.end(JSON.stringify(nix.mapConfig));
});
this.app.listen(port, () => {
console.log(`NixHTTPServer listening on port ${port}`);
});
}
resultData(status, data) {
return JSON.stringify({
status,
data
})
}
appValidator(req, res, next) {
let app = this.apps[req.params.appid]
this.requests.gotten++;
if (!app) {
this.requests.auth_failure++;
return res.send(this.resultData("unknown appid"));
}
req.nixapp = app;
next();
}
authorizationHandler(req, res, next) {
if (!req.params.auth) {
this.requests.auth_failure++;
return res.send(this.resultData("missing authorization"));
}
if (!req.nixapp.isAuthorized(req.params.auth)) {
return res.send(this.resultData("invalid authorization"));
}
next();
}
async postHandler(req, res) {
try {
let response = await req.nixapp.handlePost(req, res);
this.requests.handled++;
res.end(this.resultData(response.status, response.data));
}
catch (e) {
console.error(e.stack);
res.end(this.resultData("internal error"));
}
}
async getHandler(req, res) {
this.requests.handled++;
req.nixapp.handleGet(req, res);
}
}