-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsandstorm-generic-rest.js
More file actions
81 lines (76 loc) · 2.75 KB
/
Copy pathsandstorm-generic-rest.js
File metadata and controls
81 lines (76 loc) · 2.75 KB
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
var Future = Npm.require("fibers/future");
MongoData = new Mongo.Collection("data");
if (Meteor.isServer) {
MongoData._ensureIndex({path: 1});
}
if (Meteor.isClient) {
}
function validatePost (req) {
var permissions = req.headers["x-sandstorm-permissions"];
return permissions && permissions.indexOf("post") !== -1;
}
function validateGet (req) {
var permissions = req.headers["x-sandstorm-permissions"];
return permissions && permissions.indexOf("get") !== -1;
}
if (Meteor.isServer) {
var Future = Npm.require("fibers/future");
var Url = Npm.require("url");
Meteor.startup(function () {
WebApp.rawConnectHandlers.use(Meteor.bindEnvironment(function (req, res, next) {
if (req.url.lastIndexOf("/api", 0) === 0) {
try {
if (req.method === "POST") {
if (!validatePost(req)) {
res.writeHead(403, { "Content-Type": "text/plain" });
res.end("You do not have permission to POST.");
return;
}
var ip = req.headers["x-real-ip"];
var fut = new Future();
var bufs = [];
req.on("data", function (d) { bufs.push(d); });
req.on("error", function (err) { fut.throw(err); });
req.on("end", function () {
var buf = Buffer.concat(bufs);
fut.return(buf);
});
var data = fut.wait();
// Assume data to be text/plain or json
MongoData.insert({path: req.url, ip: ip, timestamp: new Date(), data: JSON.parse(data.toString())});
res.writeHead(200, { "Content-Type": "text/plain" });
res.end();
} else if (req.method === "GET") {
if (!validateGet(req)) {
res.writeHead(403, { "Content-Type": "text/plain" });
res.end("You do not have permission to GET.");
return;
}
var url = Url.parse(req.url, true);
// TODO(soon); look at url.query.timestamp
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(MongoData.find({path: req.url}).map(function (row) {
var ret = row.data;
ret["_jd_timestamp"] = row.timestamp;
ret["_jd_id"] = row._id;
if (row.ip) {
ret["_jd_ip"] = row.ip;
}
return ret;
})));
} else {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end(`404 not found: ${req.url}\n`);
}
return;
} catch (err) {
console.error(err);
res.writeHead(500, { "Content-Type": "text/plain" });
res.end("Internal Server Error");
return;
}
}
next();
}));
});
}