This repository has been archived on 2021-06-02. You can view files and clone it, but cannot push or open issues or pull requests.
Files
RealtimeDB-OLD/src/web/v1/index.ts
Fabian Stamm 1434036b42
Some checks failed
continuous-integration/drone/tag Build is failing
Enabling rules
2020-03-24 15:16:21 +01:00

63 lines
1.7 KiB
TypeScript

import * as Router from "koa-router";
import AdminRoute from "./admin";
import { DatabaseManager } from "../../database/database";
import {
NotFoundError,
NoPermissionError,
BadRequestError
} from "../helper/errors";
import Logging from "@hibas123/nodelogging";
import Session from "../../database/session";
import nanoid = require("nanoid");
import { verifyJWT } from "../../helper/jwt";
import { QueryError } from "../../database/query";
const V1 = new Router({ prefix: "/v1" });
V1.use("/admin", AdminRoute.routes(), AdminRoute.allowedMethods());
V1.post("/db/:database/query", async ctx => {
const { database } = ctx.params;
const { accesskey, authkey, rootkey } = ctx.query;
const query = ctx.request.body;
if (!query) {
throw new BadRequestError("Query not defined!");
}
const session = new Session(nanoid());
const db = DatabaseManager.getDatabase(database);
if (!db) {
throw new NotFoundError("Database not found!");
}
if (db.accesskey) {
if (!accesskey || accesskey !== db.accesskey) {
throw new NoPermissionError("Invalid Access Key");
}
}
if (authkey && db.publickey) {
let res = await verifyJWT(authkey, db.publickey);
if (!res || !res.uid) {
throw new BadRequestError("Invalid JWT");
} else {
session.uid = res.uid;
}
}
if (rootkey && db.rootkey) {
if (rootkey === db.rootkey) {
session.root = true;
Logging.warning(`Somebody logged into ${database} via rootkey`);
}
}
ctx.body = await db.run([query], session).catch(err => {
if (err instanceof QueryError) {
throw new BadRequestError(err.message);
}
throw err;
});
});
export default V1;