Parcourir la source

refactor: Authorize subscribe job using event classes

Owen Diffey il y a 10 mois
Parent
commit
0b8420f5f7

+ 7 - 14
backend/src/modules/EventsModule/jobs/Subscribe.ts

@@ -1,5 +1,6 @@
 import Job, { JobOptions } from "@/Job";
 import EventsModule from "@/modules/EventsModule";
+import Event from "../Event";
 
 const channelRegex =
 	/^(?<moduleName>[a-z]+)\.(?<modelName>[A-z]+)\.(?<event>[A-z]+):?(?<modelId>[A-z0-9]+)?$/;
@@ -22,22 +23,14 @@ export default class Subscribe extends Job {
 	protected override async _authorize() {
 		const { channel } = this._payload;
 
-		const { moduleName, modelName, event, modelId } =
-			channelRegex.exec(channel)?.groups ?? {};
+		const { path, scope } = Event.parseKey(channel);
 
-		let permission = `event.${channel}`;
+		const EventClass = EventsModule.getEvent(path);
 
-		if (
-			moduleName === "data" &&
-			modelName &&
-			(modelId || event === "created")
-		) {
-			if (event === "created")
-				permission = `event.model.${modelName}.created`;
-			else permission = `data.${modelName}.findById.${modelId}`;
-		}
-
-		await this._context.assertPermission(permission);
+		await EventClass.hasPermission(
+			await this._context.getUser().catch(() => null),
+			scope
+		);
 	}
 
 	protected async _execute() {

+ 11 - 19
backend/src/modules/EventsModule/jobs/SubscribeMany.ts

@@ -1,5 +1,7 @@
+import { forEachIn } from "@common/utils/forEachIn";
 import Job, { JobOptions } from "@/Job";
 import EventsModule from "@/modules/EventsModule";
+import Event from "../Event";
 
 const channelRegex =
 	/^(?<moduleName>[a-z]+)\.(?<modelName>[A-z]+)\.(?<event>[A-z]+):?(?<modelId>[A-z0-9]+)?$/;
@@ -25,26 +27,16 @@ export default class SubscribeMany extends Job {
 	}
 
 	protected override async _authorize() {
-		const permissions = this._payload.channels.map((channel: string) => {
-			const { moduleName, modelName, event, modelId } =
-				channelRegex.exec(channel)?.groups ?? {};
-
-			let permission = `event.${channel}`;
-
-			if (
-				moduleName === "data" &&
-				modelName &&
-				(modelId || event === "created")
-			) {
-				if (event === "created")
-					permission = `event.model.${modelName}.created`;
-				else permission = `data.${modelName}.findById.${modelId}`;
-			}
-
-			return permission;
-		});
+		await forEachIn(this._payload.channels, async channel => {
+			const { path, scope } = Event.parseKey(channel);
+
+			const EventClass = EventsModule.getEvent(path);
 
-		await this._context.assertPermissions(permissions);
+			await EventClass.hasPermission(
+				await this._context.getUser().catch(() => null),
+				scope
+			);
+		});
 	}
 
 	protected async _execute() {