summary refs log tree commit diff
path: root/api/src/util/route.ts
diff options
context:
space:
mode:
authorFlam3rboy <34555296+Flam3rboy@users.noreply.github.com>2021-09-12 21:21:08 +0200
committerFlam3rboy <34555296+Flam3rboy@users.noreply.github.com>2021-09-12 21:21:08 +0200
commitbffeb4af0d34546747e5d1941da3544d2482f3e0 (patch)
tree4979a07ddeaf8df6287dd5ebb66614c9476975e9 /api/src/util/route.ts
parent:bug: fix gateway (diff)
downloadserver-bffeb4af0d34546747e5d1941da3544d2482f3e0.tar.xz
:construction: :sparkles: new body parser (bans route)
Diffstat (limited to '')
-rw-r--r--api/src/util/route.ts66
1 files changed, 66 insertions, 0 deletions
diff --git a/api/src/util/route.ts b/api/src/util/route.ts
new file mode 100644
index 00000000..0302f3ec
--- /dev/null
+++ b/api/src/util/route.ts
@@ -0,0 +1,66 @@
+import { DiscordApiErrors, Event, EventData, getPermission, PermissionResolvable, Permissions } from "@fosscord/util";
+import { NextFunction, Request, Response } from "express";
+import fs from "fs";
+import path from "path";
+import Ajv from "ajv";
+import { AnyValidateFunction } from "ajv/dist/core";
+import { FieldErrors } from "..";
+
+const SchemaPath = path.join(__dirname, "..", "..", "assets", "schemas.json");
+const schemas = JSON.parse(fs.readFileSync(SchemaPath, { encoding: "utf8" }));
+export const ajv = new Ajv({ allErrors: true, parseDate: true, allowDate: true, schemas, messages: true });
+
+declare global {
+	namespace Express {
+		interface Request {
+			permission?: Permissions;
+		}
+	}
+}
+
+export type RouteSchema = string; // typescript interface name
+export type RouteResponse = { status: number; body?: RouteSchema; headers?: Record<string, string> };
+
+export interface RouteOptions {
+	permission?: PermissionResolvable;
+	body?: RouteSchema;
+	response?: RouteResponse;
+	example?: {
+		body?: any;
+		path?: string;
+		event?: EventData;
+		headers?: Record<string, string>;
+	};
+}
+
+export function route(opts: RouteOptions) {
+	var validate: AnyValidateFunction<any>;
+	if (opts.body) {
+		// @ts-ignore
+		validate = ajv.getSchema(opts.body);
+		if (!validate) throw new Error(`Body schema ${opts.body} not found`);
+	}
+
+	return async (req: Request, res: Response, next: NextFunction) => {
+		if (opts.permission) {
+			const required = new Permissions(opts.permission);
+			const permission = await getPermission(req.user_id, req.params.guild_id, req.params.channel_id);
+			console.log(required.bitfield, permission.bitfield, permission.bitfield & required.bitfield);
+
+			// bitfield comparison: check if user lacks certain permission
+			if (!permission.has(required)) {
+				throw DiscordApiErrors.MISSING_PERMISSIONS.withParams(opts.permission as string);
+			}
+
+			if (validate) {
+				const valid = validate(req.body);
+				if (!valid) {
+					const fields: Record<string, { code?: string; message: string }> = {};
+					validate.errors?.forEach((x) => (fields[x.instancePath] = { code: x.keyword, message: x.message || "" }));
+					throw FieldErrors(fields);
+				}
+			}
+		}
+		next();
+	};
+}