|
|
|
let express = require("express");
|
|
|
|
let ipaddr = require("ipaddr.js");
|
|
|
|
let moment = require("moment");
|
|
|
|
let db = require("../libs/Database").instance();
|
|
|
|
let router = express.Router();
|
|
|
|
|
|
|
|
const IP_TYPES = ["ipv4", "ipv6"];
|
|
|
|
|
|
|
|
function combineToList(a, b) {
|
|
|
|
return a + "\n" + b;
|
|
|
|
}
|
|
|
|
|
|
|
|
function toList(array) {
|
|
|
|
return array.reduce(combineToList, "").trim();
|
|
|
|
}
|
|
|
|
|
|
|
|
function testIP(req, res, next) {
|
|
|
|
let addr = ipaddr.parse(req.ip);
|
|
|
|
if (!IP_TYPES.includes(addr.kind())) return res.status(400).send("Invalid ip address");
|
|
|
|
req.params.addr = addr;
|
|
|
|
next();
|
|
|
|
}
|
|
|
|
|
|
|
|
router.use((req, res, next) => {
|
|
|
|
res.type('text/plain');
|
|
|
|
next();
|
|
|
|
});
|
|
|
|
|
|
|
|
router.get("/", testIP, (req, res) => {
|
|
|
|
res.send(req.params.addr.toString());
|
|
|
|
});
|
|
|
|
|
|
|
|
router.get("/:fqdn", (req, res) => {
|
|
|
|
db.q.select(IP_TYPES.concat(IP_TYPES.map(e => e + "LastPing"))).from("addresses").filter("fqdn", req.params.fqdn).first((e, d) => {
|
|
|
|
if (e) return res.status(400).send("Error");
|
|
|
|
if (!d) return res.status(404).send("Unknown FQDN");
|
|
|
|
res.send([
|
|
|
|
d.ipv4 ? d.ipv4 : "0.0.0.0",
|
|
|
|
moment(d.ipv4LastPing).toISOString(),
|
|
|
|
d.ipv6 ? d.ipv6 : "::",
|
|
|
|
moment(d.ipv6LastPing).toISOString(),
|
|
|
|
].reduce((a, b) => a + "\n" + b));
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
router.get("/:fqdn/:code", testIP, (req, res) => {
|
|
|
|
let addr = req.params.addr;
|
|
|
|
db.query("UPDATE addresses SET " + addr.kind() + " = ?, " + addr.kind() + "LastPing = CURRENT_TIMESTAMP WHERE fqdn = ? AND code = ?", [addr.toString(), req.params.fqdn, req.params.code], (e, d) => {
|
|
|
|
if (e) return res.status(400).send("Error");
|
|
|
|
if (d.affectedRows <= 0) return res.status(400).send("Invalid token");
|
|
|
|
res.send(addr.toString());
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
module.exports = router;
|