sprinklers3/server/express/api/mosquitto.ts

59 lines
2.1 KiB
TypeScript
Raw Normal View History

2018-08-27 23:09:45 -06:00
import PromiseRouter from "express-promise-router";
2018-08-28 05:34:23 -06:00
import ApiError from "@common/ApiError";
import { ErrorCode } from "@common/ErrorCode";
import { DEVICE_PREFIX } from "@common/sprinklersRpc/mqtt";
import { DeviceToken, SuperuserToken } from "@common/TokenClaims";
2018-08-29 08:00:41 -06:00
import { verifyToken } from "@server/authentication";
2018-08-27 23:09:45 -06:00
import { ServerState } from "@server/state";
2018-08-28 05:34:23 -06:00
export const SUPERUSER = "sprinklers3";
2018-08-27 23:09:45 -06:00
export function mosquitto(state: ServerState) {
const router = PromiseRouter();
router.post("/auth", async (req, res) => {
2018-08-28 05:34:23 -06:00
const body = req.body;
const { username, password, topic, acc } = body;
if (typeof username !== "string" || typeof password !== "string") {
throw new ApiError("Must specify a username and password", ErrorCode.BadRequest);
}
if (username === SUPERUSER) {
await verifyToken<SuperuserToken>(password, "superuser");
return res.status(200).send({ username });
}
const claims = await verifyToken<DeviceToken>(password, "device");
if (claims.aud !== username) {
throw new ApiError("Username does not match token", ErrorCode.BadRequest);
}
res.status(200).send({
username, id: claims.id,
});
2018-08-27 23:09:45 -06:00
});
router.post("/superuser", async (req, res) => {
2018-08-28 05:34:23 -06:00
const { username } = req.body;
if (typeof username !== "string") {
throw new ApiError("Must specify a username", ErrorCode.BadRequest);
}
if (username !== SUPERUSER) {
return res.status(403).send();
}
2018-08-27 23:09:45 -06:00
res.status(200).send();
});
router.post("/acl", async (req, res) => {
2018-08-28 05:34:23 -06:00
const { username, topic, clientid, acc } = req.body;
if (typeof username !== "string" || typeof topic !== "string") {
throw new ApiError("username and topic must be specified as strings", ErrorCode.BadRequest);
}
const prefix = DEVICE_PREFIX + "/" + username;
if (!topic.startsWith(prefix)) {
throw new ApiError(`device ${username} cannot access topic ${topic}`);
}
2018-08-27 23:09:45 -06:00
res.status(200).send();
});
2018-08-28 03:22:16 -06:00
2018-08-27 23:09:45 -06:00
return router;
2018-08-28 03:22:16 -06:00
}